Skip to content
Closed
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
43 changes: 17 additions & 26 deletions src/Microsoft.OpenApi/Models/OpenApiSchema.cs
Original file line number Diff line number Diff line change
Expand Up @@ -510,31 +510,30 @@ private void SerializeInternal(IOpenApiWriter writer, OpenApiSpecVersion version
});

// enum
var enumValue = Enum is not { Count: > 0 }
&& !string.IsNullOrEmpty(Const)
&& version < OpenApiSpecVersion.OpenApi3_1
? new List<JsonNode> { JsonValue.Create(Const)! }
: Enum;
var enumValue = Type is JsonSchemaType.Null && version == OpenApiSpecVersion.OpenApi3_0
? new List<JsonNode> { JsonNullSentinel.JsonNull }
: Enum is not { Count: > 0 }
&& !string.IsNullOrEmpty(Const)
&& version < OpenApiSpecVersion.OpenApi3_1
? new List<JsonNode> { JsonValue.Create(Const)! }
: Enum;
writer.WriteOptionalCollection(OpenApiConstants.Enum, enumValue, (nodeWriter, s) => nodeWriter.WriteAny(s));

// Handle oneOf/anyOf with null type for v3.0 downcast
IList<IOpenApiSchema>? effectiveOneOf = OneOf;
IList<IOpenApiSchema>? effectiveAnyOf = AnyOf;
bool hasNullInComposition = false;
JsonSchemaType? inferredType = null;

if (version == OpenApiSpecVersion.OpenApi3_0)
{
(effectiveOneOf, var inferredOneOf, var nullInOneOf) = ProcessCompositionForNull(OneOf);
(effectiveOneOf, var nullInOneOf) = ProcessCompositionForNull(OneOf);
hasNullInComposition |= nullInOneOf;
inferredType = inferredOneOf ?? inferredType;
(effectiveAnyOf, var inferredAnyOf, var nullInAnyOf) = ProcessCompositionForNull(AnyOf);
(effectiveAnyOf, var nullInAnyOf) = ProcessCompositionForNull(AnyOf);
hasNullInComposition |= nullInAnyOf;
inferredType = inferredAnyOf ?? inferredType;
}

// type
SerializeTypeProperty(writer, version, inferredType);
SerializeTypeProperty(writer, version);

// allOf
writer.WriteOptionalCollection(OpenApiConstants.AllOf, AllOf, callback);
Expand Down Expand Up @@ -971,10 +970,9 @@ private void SerializeAsV2(
writer.WriteEndObject();
}

private void SerializeTypeProperty(IOpenApiWriter writer, OpenApiSpecVersion version, JsonSchemaType? inferredType = null)
private void SerializeTypeProperty(IOpenApiWriter writer, OpenApiSpecVersion version)
{
// Use original type or inferred type when the explicit type is not set
var typeToUse = Type ?? inferredType;
var typeToUse = Type;

if (typeToUse is null)
{
Expand Down Expand Up @@ -1050,14 +1048,14 @@ private void SerializeNullable(IOpenApiWriter writer, OpenApiSpecVersion version
/// Processes a composition (oneOf or anyOf) for null types, filtering out null schemas and inferring common type.
/// </summary>
/// <param name="composition">The list of schemas in the composition.</param>
/// <returns>A tuple with the effective list, inferred type, and whether null is present in composition.</returns>
private static (IList<IOpenApiSchema>? effective, JsonSchemaType? inferredType, bool hasNullInComposition)
/// <returns>A tuple with the effective list and whether null is present in composition.</returns>
private static (IList<IOpenApiSchema>? effective, bool hasNullInComposition)
ProcessCompositionForNull(IList<IOpenApiSchema>? composition)
{
if (composition is null || !composition.Any(static s => s.Type is JsonSchemaType.Null))
{
// Nothing to patch
return (composition, null, false);
return (composition, false);
}

var nonNullSchemas = composition
Expand All @@ -1066,18 +1064,11 @@ private static (IList<IOpenApiSchema>? effective, JsonSchemaType? inferredType,

if (nonNullSchemas.Count > 0)
{
JsonSchemaType commonType = 0;

foreach (var schema in nonNullSchemas)
{
commonType |= schema.Type.GetValueOrDefault() & ~JsonSchemaType.Null;
}

return (nonNullSchemas, commonType, true);
return (nonNullSchemas, true);
}
else
{
return (null, null, true);
return (null, true);
}
}

Expand Down
8 changes: 7 additions & 1 deletion src/Microsoft.OpenApi/Reader/JsonNodeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,13 @@ public static List<JsonNode> CreateListOfAny(this JsonNode? node, ParsingContext
throw new OpenApiReaderException("Cannot create a list from this type of node.", context);
}

return jsonArray.OfType<JsonNode>().ToList();
var list = new List<JsonNode>(jsonArray.Count);
foreach (var element in jsonArray)
{
list.Add(element ?? JsonNullSentinel.JsonNull);
}

return list;
}

public static List<T> CreateSimpleList<T>(this JsonNode? node, Func<JsonNode, OpenApiDocument?, T> map, OpenApiDocument? openApiDocument, ParsingContext context)
Expand Down
7 changes: 7 additions & 0 deletions src/Microsoft.OpenApi/Reader/V3/OpenApiSchemaDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,13 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
schema.Extensions.Remove(OpenApiConstants.NullableExtension);
}

if ((schema.Type is null or JsonSchemaType.Null) && schema.Enum is { Count: 1 } &&
schema.Enum[0].IsJsonNullSentinel())
{
schema.Enum = null;
schema.Type = JsonSchemaType.Null;
}

return schema;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,12 @@ public async Task SerializeSchemaWithNullableShouldSucceed()
public async Task SerializeSchemaWithOnlyNullableShouldSucceed()
{
// Arrange
var expected = @"nullable: true";
var expected =
"""
enum:
- null
nullable: true
""";

var path = Path.Combine(SampleFolderPath, "schemaWithOnlyNullable.yaml");

Expand Down
3 changes: 0 additions & 3 deletions test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -956,7 +956,6 @@ public async Task SerializeOneOfWithNullAsV3ShouldUseNullableAsync()
var expectedV3Schema =
"""
{
"type": "string",
"oneOf": [
{
"maxLength": 10,
Expand Down Expand Up @@ -1045,7 +1044,6 @@ public async Task SerializeAnyOfWithNullAsV3ShouldUseNullableAsync()
var expectedV3Schema =
"""
{
"type": "object",
"anyOf": [
{
"type": "object",
Expand Down Expand Up @@ -1227,7 +1225,6 @@ public async Task SerializeOneOfWithNullAndRefAsV3ShouldUseNullableAsync()
var expectedV3Schema =
"""
{
"type": "object",
"oneOf": [
{
"$ref": "#/components/schemas/Pet"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Xunit;

namespace Microsoft.OpenApi.Tests.Models
{
[Collection("DefaultSettings")]
public class OpenApiSchemaV30CompatibilityTests
{
private static IOpenApiSchema ParseSchemaFromV30Document(string schemaJson)
{
var jsonContent = $$"""
{
"openapi": "3.0.0",
"info": { "title": "Test", "version": "1.0" },
"paths": {},
"components": {
"schemas": {
"TestSchema": {{schemaJson}}
}
}
}
""";

var readResult = OpenApiDocument.Parse(jsonContent, "json");
Assert.Empty(readResult.Diagnostic.Errors);
return readResult.Document.Components.Schemas["TestSchema"];
}

[Fact]
public async Task NullableEnumShouldRoundTripCorrectly()
{
var schema = new OpenApiSchema
{
Enum =
[
JsonValue.Create(1),
JsonValue.Create(2),
JsonNullSentinel.JsonNull,
]
};

var actual = await schema.SerializeAsJsonAsync(OpenApiSpecVersion.OpenApi3_0);
var deserializedSchema = ParseSchemaFromV30Document(actual);

Assert.Equal(3, deserializedSchema.Enum.Count);
Assert.Equal(1, deserializedSchema.Enum[0].GetValue<int>());
Assert.Equal(2, deserializedSchema.Enum[1].GetValue<int>());
Assert.True(deserializedSchema.Enum[2].IsJsonNullSentinel());
}

[Fact]
public async Task TypeNullAloneAsV3ShouldRoundTripCorrectly()
{
var schema = new OpenApiSchema { Type = JsonSchemaType.Null };

var actual = await schema.SerializeAsJsonAsync(OpenApiSpecVersion.OpenApi3_0);
var expected =
"""
{
"enum": [
null
],
"nullable": true
}
""";
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(expected), JsonNode.Parse(actual)));

var deserializedSchema = ParseSchemaFromV30Document(actual);

Assert.Equal(JsonSchemaType.Null, deserializedSchema.Type);
Assert.Null(deserializedSchema.Enum);
}

[Fact]
public async Task NullableTypeAsV3ShouldRoundTripCorrectly()
{
var schema = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null };

var actual = await schema.SerializeAsJsonAsync(OpenApiSpecVersion.OpenApi3_0);
var deserializedSchema = ParseSchemaFromV30Document(actual);

Assert.Equal(JsonSchemaType.String | JsonSchemaType.Null, deserializedSchema.Type);
}
}
}