diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 7482b6baf..8734c19a2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System.Collections.Generic; @@ -630,6 +630,10 @@ internal void WriteAsSchemaProperties( } // format + Format ??= AllOf?.FirstOrDefault(static x => x.Format != null)?.Format ?? + AnyOf?.FirstOrDefault(static x => x.Format != null)?.Format ?? + OneOf?.FirstOrDefault(static x => x.Format != null)?.Format; + writer.WriteProperty(OpenApiConstants.Format, Format); // title @@ -695,7 +699,7 @@ internal void WriteAsSchemaProperties( // allOf writer.WriteOptionalCollection(OpenApiConstants.AllOf, AllOf, (w, s) => s.SerializeAsV2(w)); - // If there isn't already an AllOf, and the schema contains a oneOf or anyOf write an allOf with the first + // If there isn't already an allOf, and the schema contains a oneOf or anyOf write an allOf with the first // schema in the list as an attempt to guess at a graceful downgrade situation. if (AllOf == null || AllOf.Count == 0) { diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index ae13944e6..429129c1e 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -422,5 +422,46 @@ public async Task SerializeSchemaWRequiredPropertiesAsV2JsonWorksAsync(bool prod // Assert await Verifier.Verify(actual).UseParameters(produceTerseOutput); } + + [Fact] + public void SerializeAsV2ShouldSetFormatPropertyInParentSchemaIfPresentInChildrenSchema() + { + // Arrange + var schema = new OpenApiSchema() + { + OneOf = new List + { + new OpenApiSchema + { + Type = "number", + Format = "decimal" + }, + new OpenApiSchema { Type = "string" }, + } + }; + + var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); + var openApiJsonWriter = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = false }); + + // Act + // Serialize as V2 + schema.SerializeAsV2(openApiJsonWriter); + openApiJsonWriter.Flush(); + + var v2Schema = outputStringWriter.GetStringBuilder().ToString().MakeLineBreaksEnvironmentNeutral(); + + var expectedV2Schema = @"{ + ""format"": ""decimal"", + ""allOf"": [ + { + ""format"": ""decimal"", + ""type"": ""number"" + } + ] +}".MakeLineBreaksEnvironmentNeutral(); + + // Assert + Assert.Equal(expectedV2Schema, v2Schema); + } } }