Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix missing models when multipart is present in document. #4747

Merged
merged 3 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fixes a bug where request executors would be missing Untyped parameters in dotnet [#4692](https://github.com/microsoft/kiota/issues/4692)
- Fixes a bug where indexers in include/exclude patters were not normalized if the indexer was the last segment without a slash at the end [#4715](https://github.com/microsoft/kiota/issues/4715)
- Fixes a bug where CLI generation doesnot handle parameters of type string array. [#4707](https://github.com/microsoft/kiota/issues/4707)
- Fixed a bug where models would not be created when a multipart content schema existed with no encoding [#4734](https://github.com/microsoft/kiota/issues/4734)

## [1.14.0] - 2024-05-02

Expand Down
9 changes: 9 additions & 0 deletions src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ internal static bool IsMultipartFormDataSchema(this IDictionary<string, OpenApiM
return source.GetValidSchemas(structuredMimeTypes).FirstOrDefault() is OpenApiSchema schema &&
source.GetValidSchemas(multipartMimeTypes).FirstOrDefault() == schema;
}
internal static bool IsMultipartTopMimeType(this IDictionary<string, OpenApiMediaType> source, StructuredMimeTypesCollection structuredMimeTypes)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(structuredMimeTypes);
if (structuredMimeTypes.Count == 0) return false;
if (!source.ContainsKey(multipartMimeTypes.First())) return false;
if (source.Count == 1) return true;
return structuredMimeTypes.First() == multipartMimeTypes.First();
}
internal static IEnumerable<OpenApiSchema> GetValidSchemas(this IDictionary<string, OpenApiMediaType> source, StructuredMimeTypesCollection structuredMimeTypes)
{
ArgumentNullException.ThrowIfNull(source);
Expand Down
40 changes: 26 additions & 14 deletions src/Kiota.Builder/KiotaBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1473,26 +1473,37 @@ private void AddRequestBuilderMethodParameters(OpenApiUrlTreeNode currentNode, O
if (operation.GetRequestSchema(config.StructuredMimeTypes) is OpenApiSchema requestBodySchema)
{
CodeTypeBase requestBodyType;
if (operation.RequestBody.Content.IsMultipartFormDataSchema(config.StructuredMimeTypes))
if (operation.RequestBody.Content.IsMultipartFormDataSchema(config.StructuredMimeTypes)
&& operation.RequestBody.Content.IsMultipartTopMimeType(config.StructuredMimeTypes))
{
requestBodyType = new CodeType
{
Name = "MultipartBody",
IsExternal = true,
};
var mediaType = operation.RequestBody.Content.First(x => x.Value.Schema == requestBodySchema).Value;
foreach (var encodingEntry in mediaType.Encoding
.Where(x => !string.IsNullOrEmpty(x.Value.ContentType) &&
config.StructuredMimeTypes.Contains(x.Value.ContentType)))
if (mediaType.Encoding.Any())
{
if (CreateModelDeclarations(currentNode, requestBodySchema.Properties[encodingEntry.Key], operation, method, $"{operationType}RequestBody", isRequestBody: true) is CodeType propertyType &&
propertyType.TypeDefinition is not null)
multipartPropertiesModels.TryAdd(propertyType.TypeDefinition, true);
requestBodyType = new CodeType { Name = "MultipartBody", IsExternal = true, };
foreach (var encodingEntry in mediaType.Encoding
.Where(x => !string.IsNullOrEmpty(x.Value.ContentType) &&
config.StructuredMimeTypes.Contains(x.Value.ContentType)))
{
if (CreateModelDeclarations(currentNode, requestBodySchema.Properties[encodingEntry.Key],
operation, method, $"{operationType}RequestBody",
isRequestBody: true) is CodeType propertyType &&
propertyType.TypeDefinition is not null)
multipartPropertiesModels.TryAdd(propertyType.TypeDefinition, true);
}
}
else
{
requestBodyType = CreateModelDeclarations(currentNode, requestBodySchema, operation, method,
$"{operationType}RequestBody", isRequestBody: true) ??
throw new InvalidSchemaException();
}
}
else
requestBodyType = CreateModelDeclarations(currentNode, requestBodySchema, operation, method, $"{operationType}RequestBody", isRequestBody: true) ??
throw new InvalidSchemaException();
{
requestBodyType = CreateModelDeclarations(currentNode, requestBodySchema, operation, method,
$"{operationType}RequestBody", isRequestBody: true) ??
throw new InvalidSchemaException();
}
method.AddParameter(new CodeParameter
{
Name = "body",
Expand Down Expand Up @@ -1550,6 +1561,7 @@ private void AddRequestBuilderMethodParameters(OpenApiUrlTreeNode currentNode, O
PossibleValues = contentTypes.ToList()
});
}

method.AddParameter(new CodeParameter
{
Name = "requestConfiguration",
Expand Down
281 changes: 280 additions & 1 deletion tests/Kiota.Builder.Tests/KiotaBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7180,7 +7180,7 @@ public async Task CleanupSymbolNameDoesNotCauseNameConflictsInQueryParameters()
Assert.Equal("int64", select.Type.Name);
}
[Fact]
public async Task SupportsMultiPartFormAsRequestBody()
public async Task SupportsMultiPartFormAsRequestBodyWithDefaultMimeTypes()
{
var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
await using var fs = await GetDocumentStream(@"openapi: 3.0.1
Expand Down Expand Up @@ -7246,6 +7246,285 @@ public async Task SupportsMultiPartFormAsRequestBody()
Assert.NotNull(addressClass);
}
[Fact]
public async Task SupportsMultiPartFormAsRequestBodyWithoutEncodingWithDefaultMimeTypes()
{
var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
await using var fs = await GetDocumentStream(@"openapi: 3.0.1
info:
title: Example
description: Example
version: 1.0.1
servers:
- url: https://example.org
paths:
/directoryObject:
post:
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
$ref: '#/components/schemas/address'
profileImage:
type: string
format: binary
responses:
'204':
content:
application/json:
schema:
type: string
components:
schemas:
address:
type: object
properties:
street:
type: string
city:
type: string");
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath, IncludeAdditionalData = false }, _httpClient);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
Assert.NotNull(codeModel);
var rbClass = codeModel.FindChildByName<CodeClass>("directoryObjectRequestBuilder");
Assert.NotNull(rbClass);
var postMethod = rbClass.FindChildByName<CodeMethod>("Post", false);
Assert.NotNull(postMethod);
var bodyParameter = postMethod.Parameters.FirstOrDefault(static x => x.IsOfKind(CodeParameterKind.RequestBody));
Assert.NotNull(bodyParameter);
Assert.Equal("directoryObjectPostRequestBody", bodyParameter.Type.Name, StringComparer.OrdinalIgnoreCase);
var addressClass = codeModel.FindChildByName<CodeClass>("Address");
Assert.NotNull(addressClass);
}
[Fact]
public async Task SupportsMultipleContentTypesAsRequestBodyWithDefaultMimeTypes()
{
var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
await using var fs = await GetDocumentStream(@"openapi: 3.0.1
info:
title: Example
description: Example
version: 1.0.1
servers:
- url: https://example.org
paths:
/directoryObject:
post:
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
$ref: '#/components/schemas/address'
profileImage:
type: string
format: binary
application/json:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
$ref: '#/components/schemas/address'
profileImage:
type: string
format: binary
responses:
'204':
content:
application/json:
schema:
type: string
components:
schemas:
address:
type: object
properties:
street:
type: string
city:
type: string");
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath, IncludeAdditionalData = false }, _httpClient);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
Assert.NotNull(codeModel);
var rbClass = codeModel.FindChildByName<CodeClass>("directoryObjectRequestBuilder");
Assert.NotNull(rbClass);
var postMethod = rbClass.FindChildByName<CodeMethod>("Post", false);
Assert.NotNull(postMethod);
var bodyParameter = postMethod.Parameters.FirstOrDefault(static x => x.IsOfKind(CodeParameterKind.RequestBody));
Assert.NotNull(bodyParameter);
Assert.Equal("directoryObjectPostRequestBody", bodyParameter.Type.Name, StringComparer.OrdinalIgnoreCase);
var addressClass = codeModel.FindChildByName<CodeClass>("Address");
Assert.NotNull(addressClass);
}
[Fact]
public async Task SupportsMultipleContentTypesAsRequestBodyWithMultipartPriorityNoEncoding()
{
var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
await using var fs = await GetDocumentStream(@"openapi: 3.0.1
info:
title: Example
description: Example
version: 1.0.1
servers:
- url: https://example.org
paths:
/directoryObject:
post:
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
$ref: '#/components/schemas/address'
profileImage:
type: string
format: binary
application/json:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
$ref: '#/components/schemas/address'
profileImage:
type: string
format: binary
responses:
'204':
content:
application/json:
schema:
type: string
components:
schemas:
address:
type: object
properties:
street:
type: string
city:
type: string");
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath, IncludeAdditionalData = false, StructuredMimeTypes = new StructuredMimeTypesCollection { "multipart/form-data;q=1", "application/json;q=0.1" } }, _httpClient);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
Assert.NotNull(codeModel);
var rbClass = codeModel.FindChildByName<CodeClass>("directoryObjectRequestBuilder");
Assert.NotNull(rbClass);
var postMethod = rbClass.FindChildByName<CodeMethod>("Post", false);
Assert.NotNull(postMethod);
var bodyParameter = postMethod.Parameters.FirstOrDefault(static x => x.IsOfKind(CodeParameterKind.RequestBody));
Assert.NotNull(bodyParameter);
Assert.Equal("directoryObjectPostRequestBody", bodyParameter.Type.Name, StringComparer.OrdinalIgnoreCase);
var addressClass = codeModel.FindChildByName<CodeClass>("Address");
Assert.NotNull(addressClass);
}
[Fact]
public async Task SupportsMultipleContentTypesAsRequestBodyWithMultipartPriorityAndEncoding()
{
var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
await using var fs = await GetDocumentStream(@"openapi: 3.0.1
info:
title: Example
description: Example
version: 1.0.1
servers:
- url: https://example.org
paths:
/directoryObject:
post:
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
$ref: '#/components/schemas/address'
profileImage:
type: string
format: binary
encoding:
id:
contentType: text/plain
address:
contentType: application/json
profileImage:
contentType: image/png
application/json:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
$ref: '#/components/schemas/address'
profileImage:
type: string
format: binary
responses:
'204':
content:
application/json:
schema:
type: string
components:
schemas:
address:
type: object
properties:
street:
type: string
city:
type: string");
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath, IncludeAdditionalData = false, StructuredMimeTypes = new StructuredMimeTypesCollection { "multipart/form-data;q=1", "application/json;q=0.1" } }, _httpClient);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
Assert.NotNull(codeModel);
var rbClass = codeModel.FindChildByName<CodeClass>("directoryObjectRequestBuilder");
Assert.NotNull(rbClass);
var postMethod = rbClass.FindChildByName<CodeMethod>("Post", false);
Assert.NotNull(postMethod);
var bodyParameter = postMethod.Parameters.FirstOrDefault(static x => x.IsOfKind(CodeParameterKind.RequestBody));
Assert.NotNull(bodyParameter);
Assert.Equal("MultipartBody", bodyParameter.Type.Name, StringComparer.OrdinalIgnoreCase);
var addressClass = codeModel.FindChildByName<CodeClass>("Address");
Assert.NotNull(addressClass);
}
[Fact]
public async Task ComplexInheritanceStructures()
{
var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
Expand Down
Loading