From e6535f7380e424668163f812da80d8e8c270b649 Mon Sep 17 00:00:00 2001 From: Fabian Niederer Date: Tue, 28 Apr 2020 11:09:22 +0200 Subject: [PATCH 001/855] added validation & renabled OpenApiPaths validators --- .../Properties/SRResource.Designer.cs | 11 ++++- .../Properties/SRResource.resx | 3 ++ .../Services/OpenApiWalker.cs | 2 + .../Validations/OpenApiValidator.cs | 6 +++ .../Validations/Rules/OpenApiPathsRules.cs | 26 ++++++++++ .../OpenApiPathsValidationTests.cs | 49 +++++++++++++++++++ .../Validations/ValidationRuleSetTests.cs | 2 +- 7 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 test/Microsoft.OpenApi.Tests/Validations/OpenApiPathsValidationTests.cs diff --git a/src/Microsoft.OpenApi/Properties/SRResource.Designer.cs b/src/Microsoft.OpenApi/Properties/SRResource.Designer.cs index 47f9493b9..69cc96223 100644 --- a/src/Microsoft.OpenApi/Properties/SRResource.Designer.cs +++ b/src/Microsoft.OpenApi/Properties/SRResource.Designer.cs @@ -19,7 +19,7 @@ namespace Microsoft.OpenApi.Properties { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SRResource { @@ -330,6 +330,15 @@ internal static string Validation_PathItemMustBeginWithSlash { } } + /// + /// Looks up a localized string similar to The path signature '{0}' MUST begin be unique.. + /// + internal static string Validation_PathSignatureMustBeUnique { + get { + return ResourceManager.GetString("Validation_PathSignatureMustBeUnique", resourceCulture); + } + } + /// /// Looks up a localized string similar to The same rule cannot be in the same rule set twice.. /// diff --git a/src/Microsoft.OpenApi/Properties/SRResource.resx b/src/Microsoft.OpenApi/Properties/SRResource.resx index 48f910a95..5e439868b 100644 --- a/src/Microsoft.OpenApi/Properties/SRResource.resx +++ b/src/Microsoft.OpenApi/Properties/SRResource.resx @@ -207,6 +207,9 @@ The path item name '{0}' MUST begin with a slash. + + The path signature '{0}' MUST begin be unique. + The same rule cannot be in the same rule set twice. diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index dd3c09564..6167d8d24 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -219,6 +219,7 @@ internal void Walk(OpenApiPaths paths) _visitor.CurrentKeys.Path = null; } } + } /// @@ -1036,6 +1037,7 @@ internal void Walk(IOpenApiElement element) case OpenApiOAuthFlow e: Walk(e); break; case OpenApiOperation e: Walk(e); break; case OpenApiParameter e: Walk(e); break; + case OpenApiPaths e: Walk(e); break; case OpenApiRequestBody e: Walk(e); break; case OpenApiResponse e: Walk(e); break; case OpenApiSchema e: Walk(e); break; diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index 69bcda93d..e6edd8fc7 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -131,6 +131,12 @@ public void AddError(OpenApiValidatorError error) /// The object to be validated public override void Visit(OpenApiParameter item) => Validate(item); + /// + /// Execute validation rules against an + /// + /// The object to be validated + public override void Visit(OpenApiPaths item) => Validate(item); + /// /// Execute validation rules against an /// diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs index 7ac374b62..5e5424870 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System.Collections.Generic; +using System.Text.RegularExpressions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; @@ -34,6 +36,30 @@ public static class OpenApiPathsRules } }); + /// + /// A relative path to an individual endpoint. The field name MUST begin with a slash. + /// + public static ValidationRule PathMustBeUnique => + new ValidationRule( + (context, item) => + { + const string regexPath = "\\{([^/]+)\\}"; + var hashSet = new HashSet(); + + foreach (var path in item.Keys) + { + context.Enter(path); + + var pathSignature = Regex.Replace(path, regexPath, "{}"); + + if (!hashSet.Add(pathSignature)) + context.CreateError(nameof(PathMustBeUnique), + string.Format(SRResource.Validation_PathSignatureMustBeUnique, pathSignature)); + + context.Exit(); + } + }); + // add more rules } } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiPathsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiPathsValidationTests.cs new file mode 100644 index 000000000..23a0a3e0f --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiPathsValidationTests.cs @@ -0,0 +1,49 @@ +using System.Linq; +using FluentAssertions; +using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Properties; +using Xunit; + +namespace Microsoft.OpenApi.Validations.Tests +{ + public class OpenApiPathsValidationTests + { + [Fact] + public void ValidatePathsMustBeginWithSlash() + { + // Arrange + var error = string.Format(SRResource.Validation_PathItemMustBeginWithSlash, "pets/{petId}"); + var paths = new OpenApiPaths + { + {"pets/{petId}",new OpenApiPathItem() } + }; + + // Act + var errors = paths.Validate(ValidationRuleSet.GetDefaultRuleSet()); + + // Assert + errors.Should().NotBeEmpty(); + errors.Select(e => e.Message).Should().BeEquivalentTo(error); + } + + [Fact] + public void ValidatePathsAreUnique() + { + // Arrange + var error = string.Format(SRResource.Validation_PathSignatureMustBeUnique, "/pets/{}"); + var paths = new OpenApiPaths + { + {"/pets/{petId}",new OpenApiPathItem() }, + {"/pets/{name}",new OpenApiPathItem() } + }; + + // Act + var errors = paths.Validate(ValidationRuleSet.GetDefaultRuleSet()); + + // Assert + errors.Should().NotBeEmpty(); + errors.Select(e => e.Message).Should().BeEquivalentTo(error); + } + } +} diff --git a/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs b/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs index af259cf1b..8153e6054 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs @@ -43,7 +43,7 @@ public void DefaultRuleSetPropertyReturnsTheCorrectRules() Assert.NotEmpty(rules); // Update the number if you add new default rule(s). - Assert.Equal(21, rules.Count); + Assert.Equal(22, rules.Count); } } } From 6bf85c5bd09203f8fcf4e6d8111b83cddeb306cc Mon Sep 17 00:00:00 2001 From: Darrel Date: Tue, 28 Jul 2020 22:59:08 -0400 Subject: [PATCH 002/855] Update src/Microsoft.OpenApi/Properties/SRResource.resx --- src/Microsoft.OpenApi/Properties/SRResource.resx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Properties/SRResource.resx b/src/Microsoft.OpenApi/Properties/SRResource.resx index 5e439868b..8039212f9 100644 --- a/src/Microsoft.OpenApi/Properties/SRResource.resx +++ b/src/Microsoft.OpenApi/Properties/SRResource.resx @@ -208,7 +208,7 @@ The path item name '{0}' MUST begin with a slash. - The path signature '{0}' MUST begin be unique. + The path signature '{0}' MUST be unique. The same rule cannot be in the same rule set twice. @@ -219,4 +219,4 @@ The string '{0}' MUST be in the format of an email address. - \ No newline at end of file + From 45968f3263f39206bc31dbf9f8488e1991a380cf Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 15 Aug 2021 13:34:03 -0400 Subject: [PATCH 003/855] Can validate external references now --- .../OpenApiYamlDocumentReader.cs | 6 +- .../Services/DefaultStreamLoader.cs | 21 ++++-- .../V3/OpenApiV3VersionService.cs | 20 +++++- src/Microsoft.OpenApi.Tool/OpenApiService.cs | 71 ++++++++++++++----- src/Microsoft.OpenApi.Tool/Program.cs | 5 +- .../Models/OpenApiReference.cs | 18 +++-- .../OpenApiWorkspaceStreamTests.cs | 5 +- .../Models/OpenApiReferenceTests.cs | 54 ++++++++++---- 8 files changed, 150 insertions(+), 50 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index bb00fb370..63b78ccba 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -88,7 +88,7 @@ public async Task ReadAsync(YamlDocument input) // Parse the OpenAPI Document document = context.Parse(input); - await ResolveReferencesAsync(diagnostic, document); + await ResolveReferencesAsync(diagnostic, document, _settings.BaseUrl); } catch (OpenApiException ex) { @@ -133,7 +133,7 @@ private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument doc } } - private async Task ResolveReferencesAsync(OpenApiDiagnostic diagnostic, OpenApiDocument document) + private async Task ResolveReferencesAsync(OpenApiDiagnostic diagnostic, OpenApiDocument document, Uri baseUrl) { List errors = new List(); @@ -146,7 +146,7 @@ private async Task ResolveReferencesAsync(OpenApiDiagnostic diagnostic, OpenApiD var openApiWorkSpace = new OpenApiWorkspace(); // Load this root document into the workspace - var streamLoader = new DefaultStreamLoader(); + var streamLoader = new DefaultStreamLoader(baseUrl); var workspaceLoader = new OpenApiWorkspaceLoader(openApiWorkSpace, _settings.CustomExternalLoader ?? streamLoader, _settings); await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document); diff --git a/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs b/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs index 4659db711..09f16632b 100644 --- a/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs @@ -14,18 +14,25 @@ namespace Microsoft.OpenApi.Readers.Services /// internal class DefaultStreamLoader : IStreamLoader { + private readonly Uri baseUrl; private HttpClient _httpClient = new HttpClient(); + + public DefaultStreamLoader(Uri baseUrl) + { + this.baseUrl = baseUrl; + } + public Stream Load(Uri uri) { + var absoluteUri = new Uri(baseUrl, uri); switch (uri.Scheme) { case "file": - return File.OpenRead(uri.AbsolutePath); + return File.OpenRead(absoluteUri.AbsolutePath); case "http": case "https": - return _httpClient.GetStreamAsync(uri).GetAwaiter().GetResult(); - + return _httpClient.GetStreamAsync(absoluteUri).GetAwaiter().GetResult(); default: throw new ArgumentException("Unsupported scheme"); } @@ -33,13 +40,15 @@ public Stream Load(Uri uri) public async Task LoadAsync(Uri uri) { - switch (uri.Scheme) + var absoluteUri = new Uri(baseUrl, uri); + + switch (absoluteUri.Scheme) { case "file": - return File.OpenRead(uri.AbsolutePath); + return File.OpenRead(absoluteUri.AbsolutePath); case "http": case "https": - return await _httpClient.GetStreamAsync(uri); + return await _httpClient.GetStreamAsync(absoluteUri); default: throw new ArgumentException("Unsupported scheme"); } diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 2663b6a3b..1a0b1bae2 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -53,6 +53,8 @@ internal class OpenApiV3VersionService : IOpenApiVersionService /// /// Parse the string to a object. /// + /// The URL of the reference + /// The type of object refefenced based on the context of the reference public OpenApiReference ConvertToOpenApiReference( string reference, ReferenceType? type) @@ -95,8 +97,22 @@ public OpenApiReference ConvertToOpenApiReference( // $ref: externalSource.yaml#/Pet if (id.StartsWith("/components/")) { - id = segments[1].Split('/')[3]; - } + var localSegments = segments[1].Split('/'); + var referencedType = localSegments[2].GetEnumFromDisplayName(); + if (type == null) + { + type = referencedType; + } + else + { + if (type != referencedType) + { + throw new OpenApiException("Referenced type mismatch"); + } + } + id = localSegments[3]; + } + return new OpenApiReference { ExternalResource = segments[0], diff --git a/src/Microsoft.OpenApi.Tool/OpenApiService.cs b/src/Microsoft.OpenApi.Tool/OpenApiService.cs index c52c08941..3b3afcbd0 100644 --- a/src/Microsoft.OpenApi.Tool/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Tool/OpenApiService.cs @@ -5,6 +5,7 @@ using System.Net; using System.Net.Http; using System.Text; +using System.Threading.Tasks; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers; @@ -29,14 +30,16 @@ public static void ProcessOpenApiDocument( throw new ArgumentNullException("input"); } - var stream = GetStream(input); + var inputUrl = GetInputUrl(input); + var stream = GetStream(inputUrl); OpenApiDocument document; var result = new OpenApiStreamReader(new OpenApiReaderSettings { ReferenceResolution = resolveExternal == true ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, - RuleSet = ValidationRuleSet.GetDefaultRuleSet() + RuleSet = ValidationRuleSet.GetDefaultRuleSet(), + BaseUrl = new Uri(inputUrl.AbsoluteUri) } ).ReadAsync(stream).GetAwaiter().GetResult(); @@ -91,10 +94,22 @@ public static void ProcessOpenApiDocument( } } - private static Stream GetStream(string input) + private static Uri GetInputUrl(string input) { - Stream stream; if (input.StartsWith("http")) + { + return new Uri(input); + } + else + { + return new Uri("file://" + Path.GetFullPath(input)); + } + } + + private static Stream GetStream(Uri input) + { + Stream stream; + if (input.Scheme == "http" || input.Scheme == "https") { var httpClient = new HttpClient(new HttpClientHandler() { @@ -105,32 +120,40 @@ private static Stream GetStream(string input) }; stream = httpClient.GetStreamAsync(input).Result; } - else + else if (input.Scheme == "file") { - var fileInput = new FileInfo(input); + var fileInput = new FileInfo(input.AbsolutePath); stream = fileInput.OpenRead(); + } + else + { + throw new ArgumentException("Unrecognized exception"); } return stream; } - internal static void ValidateOpenApiDocument(string input) + internal static async Task ValidateOpenApiDocument(string input, bool resolveExternal) { if (input == null) { throw new ArgumentNullException("input"); } - - var stream = GetStream(input); + var inputUrl = GetInputUrl(input); + var stream = GetStream(GetInputUrl(input)); OpenApiDocument document; - document = new OpenApiStreamReader(new OpenApiReaderSettings + var result = await new OpenApiStreamReader(new OpenApiReaderSettings { - //ReferenceResolution = resolveExternal == true ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, - RuleSet = ValidationRuleSet.GetDefaultRuleSet() + ReferenceResolution = resolveExternal == true ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, + RuleSet = ValidationRuleSet.GetDefaultRuleSet(), + BaseUrl = new Uri(inputUrl.AbsoluteUri) } - ).Read(stream, out var context); + ).ReadAsync(stream); + + document = result.OpenApiDocument; + var context = result.OpenApiDiagnostic; if (context.Errors.Count != 0) { @@ -140,11 +163,25 @@ internal static void ValidateOpenApiDocument(string input) } } - var statsVisitor = new StatsVisitor(); - var walker = new OpenApiWalker(statsVisitor); - walker.Walk(document); + if (document.Workspace == null) { + var statsVisitor = new StatsVisitor(); + var walker = new OpenApiWalker(statsVisitor); + walker.Walk(document); + Console.WriteLine(statsVisitor.GetStatisticsReport()); + } + else + { + foreach (var memberDocument in document.Workspace.Documents) + { + Console.WriteLine("Stats for " + memberDocument.Info.Title); + var statsVisitor = new StatsVisitor(); + var walker = new OpenApiWalker(statsVisitor); + walker.Walk(memberDocument); + Console.WriteLine(statsVisitor.GetStatisticsReport()); + } + } - Console.WriteLine(statsVisitor.GetStatisticsReport()); + } } } diff --git a/src/Microsoft.OpenApi.Tool/Program.cs b/src/Microsoft.OpenApi.Tool/Program.cs index 446e2829a..0ae4cb782 100644 --- a/src/Microsoft.OpenApi.Tool/Program.cs +++ b/src/Microsoft.OpenApi.Tool/Program.cs @@ -36,9 +36,10 @@ static async Task Main(string[] args) var validateCommand = new Command("validate") { - new Option("--input", "Input OpenAPI description file path or URL", typeof(string) ) + new Option("--input", "Input OpenAPI description file path or URL", typeof(string) ), + new Option("--resolveExternal","Resolve external $refs", typeof(bool)) }; - validateCommand.Handler = CommandHandler.Create(OpenApiService.ValidateOpenApiDocument); + validateCommand.Handler = CommandHandler.Create(OpenApiService.ValidateOpenApiDocument); var transformCommand = new Command("transform") { diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index 2c8f738ca..cbe64d3e6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -54,7 +54,7 @@ public string ReferenceV3 { if (IsExternal) { - return GetExternalReference(); + return GetExternalReferenceV3(); } if (!Type.HasValue) @@ -85,7 +85,7 @@ public string ReferenceV2 { if (IsExternal) { - return GetExternalReference(); + return GetExternalReferenceV2(); } if (!Type.HasValue) @@ -171,11 +171,21 @@ public void SerializeAsV2(IOpenApiWriter writer) writer.WriteEndObject(); } - private string GetExternalReference() + private string GetExternalReferenceV3() { if (Id != null) { - return ExternalResource + "#/" + Id; + return ExternalResource + "#/components/" + Type.GetDisplayName() + "/"+ Id; + } + + return ExternalResource; + } + + private string GetExternalReferenceV2() + { + if (Id != null) + { + return ExternalResource + "#/" + GetReferenceTypeNameAsV2((ReferenceType)Type) + "/" + Id; } return ExternalResource; diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs index d684144cb..4a35301c6 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs @@ -19,7 +19,7 @@ public class OpenApiWorkspaceStreamTests // Use OpenApiWorkspace to load a document and a referenced document [Fact] - public async Task LoadDocumentIntoWorkspace() + public async Task LoadingDocumentWithResolveAllReferencesShouldLoadDocumentIntoWorkspace() { // Create a reader that will resolve all references var reader = new OpenApiStreamReader(new OpenApiReaderSettings() @@ -48,7 +48,7 @@ public async Task LoadDocumentIntoWorkspace() [Fact] - public async Task LoadTodoDocumentIntoWorkspace() + public async Task LoadDocumentWithExternalReferenceShouldLoadBothDocumentsIntoWorkspace() { // Create a reader that will resolve all references var reader = new OpenApiStreamReader(new OpenApiReaderSettings() @@ -65,6 +65,7 @@ public async Task LoadTodoDocumentIntoWorkspace() Assert.NotNull(result.OpenApiDocument.Workspace); Assert.True(result.OpenApiDocument.Workspace.Contains("TodoComponents.yaml")); + var referencedSchema = result.OpenApiDocument .Paths["/todos"] .Operations[OperationType.Get] diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs index c251814db..b9edd2a32 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs @@ -37,30 +37,54 @@ public void SettingInternalReferenceForComponentsStyleReferenceShouldSucceed( } [Theory] - [InlineData("Pet.json", "Pet.json", null)] - [InlineData("Pet.yaml", "Pet.yaml", null)] - [InlineData("abc", "abc", null)] - [InlineData("Pet.json#/Pet", "Pet.json", "Pet")] - [InlineData("Pet.yaml#/Pet", "Pet.yaml", "Pet")] - [InlineData("abc#/Pet", "abc", "Pet")] - public void SettingExternalReferenceShouldSucceed(string expected, string externalResource, string id) + [InlineData("Pet.json", "Pet.json", null, null)] + [InlineData("Pet.yaml", "Pet.yaml", null, null)] + [InlineData("abc", "abc", null, null)] + [InlineData("Pet.json#/components/schemas/Pet", "Pet.json", "Pet", ReferenceType.Schema)] + [InlineData("Pet.yaml#/components/schemas/Pet", "Pet.yaml", "Pet", ReferenceType.Schema)] + [InlineData("abc#/components/schemas/Pet", "abc", "Pet", ReferenceType.Schema)] + public void SettingExternalReferenceV3ShouldSucceed(string expected, string externalResource, string id, ReferenceType? type) { // Arrange & Act var reference = new OpenApiReference { ExternalResource = externalResource, + Type = type, Id = id }; // Assert reference.ExternalResource.Should().Be(externalResource); - reference.Type.Should().BeNull(); reference.Id.Should().Be(id); reference.ReferenceV3.Should().Be(expected); + } + + [Theory] + [InlineData("Pet.json", "Pet.json", null, null)] + [InlineData("Pet.yaml", "Pet.yaml", null, null)] + [InlineData("abc", "abc", null, null)] + [InlineData("Pet.json#/definitions/Pet", "Pet.json", "Pet", ReferenceType.Schema)] + [InlineData("Pet.yaml#/definitions/Pet", "Pet.yaml", "Pet", ReferenceType.Schema)] + [InlineData("abc#/definitions/Pet", "abc", "Pet", ReferenceType.Schema)] + public void SettingExternalReferenceV2ShouldSucceed(string expected, string externalResource, string id, ReferenceType? type) + { + // Arrange & Act + var reference = new OpenApiReference + { + ExternalResource = externalResource, + Type = type, + Id = id + }; + + // Assert + reference.ExternalResource.Should().Be(externalResource); + reference.Id.Should().Be(id); + reference.ReferenceV2.Should().Be(expected); } + [Fact] public void SerializeSchemaReferenceAsJsonV3Works() { @@ -144,11 +168,12 @@ public void SerializeExternalReferenceAsJsonV2Works() var reference = new OpenApiReference { ExternalResource = "main.json", + Type= ReferenceType.Schema, Id = "Pets" }; var expected = @"{ - ""$ref"": ""main.json#/Pets"" + ""$ref"": ""main.json#/definitions/Pets"" }"; // Act @@ -167,9 +192,10 @@ public void SerializeExternalReferenceAsYamlV2Works() var reference = new OpenApiReference { ExternalResource = "main.json", + Type = ReferenceType.Schema, Id = "Pets" }; - var expected = @"$ref: main.json#/Pets"; + var expected = @"$ref: main.json#/definitions/Pets"; // Act var actual = reference.SerializeAsYaml(OpenApiSpecVersion.OpenApi2_0); @@ -182,10 +208,10 @@ public void SerializeExternalReferenceAsYamlV2Works() public void SerializeExternalReferenceAsJsonV3Works() { // Arrange - var reference = new OpenApiReference { ExternalResource = "main.json", Id = "Pets" }; + var reference = new OpenApiReference { ExternalResource = "main.json", Type = ReferenceType.Schema,Id = "Pets" }; var expected = @"{ - ""$ref"": ""main.json#/Pets"" + ""$ref"": ""main.json#/components/schemas/Pets"" }"; // Act @@ -201,8 +227,8 @@ public void SerializeExternalReferenceAsJsonV3Works() public void SerializeExternalReferenceAsYamlV3Works() { // Arrange - var reference = new OpenApiReference { ExternalResource = "main.json", Id = "Pets" }; - var expected = @"$ref: main.json#/Pets"; + var reference = new OpenApiReference { ExternalResource = "main.json", Type = ReferenceType.Schema, Id = "Pets" }; + var expected = @"$ref: main.json#/components/schemas/Pets"; // Act var actual = reference.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); From 89cc609f419df85a48008391e0f1dbc671967fed Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 31 Oct 2021 21:30:09 -0400 Subject: [PATCH 004/855] Fixed inlining settings --- .../OpenApiStreamReader.cs | 7 ++ .../EnumBindingSourceExtension.cs | 53 ++++++++++ src/Microsoft.OpenApi.Workbench/MainModel.cs | 98 +++++++++++++++---- .../MainWindow.xaml | 5 +- .../MainWindow.xaml.cs | 11 ++- .../Microsoft.OpenApi.Workbench.csproj | 1 + .../Models/OpenApiCallback.cs | 2 +- .../Models/OpenApiComponents.cs | 2 +- .../Models/OpenApiDocument.cs | 2 +- .../Models/OpenApiExample.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 4 +- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 2 +- .../Models/OpenApiParameter.cs | 4 +- .../Models/OpenApiPathItem.cs | 4 +- .../Models/OpenApiResponse.cs | 4 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 4 +- .../Writers/OpenApiWriterSettings.cs | 54 +++++++++- .../OpenApiWorkspaceStreamTests.cs | 6 +- .../PublicApi/PublicApi.approved.txt | 4 + .../Writers/OpenApiYamlWriterTests.cs | 8 +- 20 files changed, 229 insertions(+), 48 deletions(-) create mode 100644 src/Microsoft.OpenApi.Workbench/EnumBindingSourceExtension.cs diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index cab5d1a83..7f721cadd 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.IO; using System.Threading.Tasks; using Microsoft.OpenApi.Interfaces; @@ -23,6 +24,12 @@ public class OpenApiStreamReader : IOpenApiReader public OpenApiStreamReader(OpenApiReaderSettings settings = null) { _settings = settings ?? new OpenApiReaderSettings(); + + if(_settings.ReferenceResolution == ReferenceResolutionSetting.ResolveAllReferences + && _settings.BaseUrl == null) + { + throw new ArgumentException("BaseUrl must be provided to resolve external references."); + } } /// diff --git a/src/Microsoft.OpenApi.Workbench/EnumBindingSourceExtension.cs b/src/Microsoft.OpenApi.Workbench/EnumBindingSourceExtension.cs new file mode 100644 index 000000000..d1f8bd798 --- /dev/null +++ b/src/Microsoft.OpenApi.Workbench/EnumBindingSourceExtension.cs @@ -0,0 +1,53 @@ +// Thanks Brian! https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/ +using System; +using System.Windows.Markup; + +namespace Microsoft.OpenApi.Workbench +{ + public class EnumBindingSourceExtension : MarkupExtension + { + private Type _enumType; + public Type EnumType + { + get { return this._enumType; } + set + { + if (value != this._enumType) + { + if (null != value) + { + Type enumType = Nullable.GetUnderlyingType(value) ?? value; + if (!enumType.IsEnum) + throw new ArgumentException("Type must be for an Enum."); + } + + this._enumType = value; + } + } + } + + public EnumBindingSourceExtension() { } + + public EnumBindingSourceExtension(Type enumType) + { + this.EnumType = enumType; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + if (null == this._enumType) + throw new InvalidOperationException("The EnumType must be specified."); + + Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType; + Array enumValues = Enum.GetValues(actualEnumType); + + if (actualEnumType == this._enumType) + return enumValues; + + Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1); + enumValues.CopyTo(tempArray, 1); + return tempArray; + } + } + +} diff --git a/src/Microsoft.OpenApi.Workbench/MainModel.cs b/src/Microsoft.OpenApi.Workbench/MainModel.cs index 6304b7f23..70074736b 100644 --- a/src/Microsoft.OpenApi.Workbench/MainModel.cs +++ b/src/Microsoft.OpenApi.Workbench/MainModel.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; @@ -6,7 +6,9 @@ using System.Diagnostics; using System.Globalization; using System.IO; +using System.Net.Http; using System.Text; +using System.Threading.Tasks; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers; @@ -23,6 +25,11 @@ public class MainModel : INotifyPropertyChanged { private string _input; + private bool _inlineLocal = false; + private bool _inlineExternal = false; + + private bool _resolveExternal = false; + private string _inputFile; private string _output; @@ -33,11 +40,7 @@ public class MainModel : INotifyPropertyChanged private string _renderTime; - /// - /// Default format. - /// - private bool _Inline = false; - + /// /// Default format. /// @@ -48,6 +51,9 @@ public class MainModel : INotifyPropertyChanged /// private OpenApiSpecVersion _version = OpenApiSpecVersion.OpenApi3_0; + + private HttpClient _httpClient = new HttpClient(); + public string Input { get => _input; @@ -58,6 +64,16 @@ public string Input } } + public bool ResolveExternal + { + get => _resolveExternal; + set + { + _resolveExternal = value; + OnPropertyChanged(nameof(ResolveExternal)); + } + } + public string InputFile { get => _inputFile; @@ -67,7 +83,6 @@ public string InputFile OnPropertyChanged(nameof(InputFile)); } } - public string Output { get => _output; @@ -119,13 +134,23 @@ public OpenApiFormat Format } } - public bool Inline + public bool InlineLocal + { + get => _inlineLocal; + set + { + _inlineLocal = value; + OnPropertyChanged(nameof(InlineLocal)); + } + } + + public bool InlineExternal { - get => _Inline; + get => _inlineExternal; set { - _Inline = value; - OnPropertyChanged(nameof(Inline)); + _inlineExternal = value; + OnPropertyChanged(nameof(InlineExternal)); } } @@ -180,17 +205,28 @@ protected void OnPropertyChanged(string propertyName) /// The core method of the class. /// Runs the parsing and serializing. /// - internal void ParseDocument() + internal async Task ParseDocument() { + Stream stream = null; try { - Stream stream; - if (!String.IsNullOrWhiteSpace(_inputFile)) + if (!string.IsNullOrWhiteSpace(_inputFile)) { - stream = new FileStream(_inputFile, FileMode.Open); + if (_inputFile.StartsWith("http")) + { + stream = await _httpClient.GetStreamAsync(_inputFile); + } + else + { + stream = new FileStream(_inputFile, FileMode.Open); + } } else { + if (ResolveExternal) + { + throw new ArgumentException("Input file must be used to resolve external references"); + } stream = CreateStream(_input); } @@ -198,12 +234,27 @@ internal void ParseDocument() var stopwatch = new Stopwatch(); stopwatch.Start(); - var document = new OpenApiStreamReader(new OpenApiReaderSettings + var settings = new OpenApiReaderSettings { - ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences, + ReferenceResolution = ResolveExternal ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, RuleSet = ValidationRuleSet.GetDefaultRuleSet() + }; + if (ResolveExternal) + { + if (_inputFile.StartsWith("http")) + { + settings.BaseUrl = new Uri(_inputFile); + } + else + { + settings.BaseUrl = new Uri("file://" + Path.GetDirectoryName(_inputFile) + "/"); + } } - ).Read(stream, out var context); + var readResult = await new OpenApiStreamReader(settings + ).ReadAsync(stream); + var document = readResult.OpenApiDocument; + var context = readResult.OpenApiDiagnostic; + stopwatch.Stop(); ParseTime = $"{stopwatch.ElapsedMilliseconds} ms"; @@ -241,6 +292,14 @@ internal void ParseDocument() Output = string.Empty; Errors = "Failed to parse input: " + ex.Message; } + finally { + if (stream != null) + { + stream.Close(); + stream.Dispose(); + } + + } } /// @@ -255,7 +314,8 @@ private string WriteContents(OpenApiDocument document) Version, Format, new OpenApiWriterSettings() { - ReferenceInline = this.Inline == true ? ReferenceInlineSetting.InlineLocalReferences : ReferenceInlineSetting.DoNotInlineReferences + InlineLocalReferences = InlineLocal, + InlineExternalReferences = InlineExternal }); outputStream.Position = 0; diff --git a/src/Microsoft.OpenApi.Workbench/MainWindow.xaml b/src/Microsoft.OpenApi.Workbench/MainWindow.xaml index daf8a2209..41a4f2543 100644 --- a/src/Microsoft.OpenApi.Workbench/MainWindow.xaml +++ b/src/Microsoft.OpenApi.Workbench/MainWindow.xaml @@ -4,6 +4,7 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Microsoft.OpenApi.Workbench" + xmlns:writers="clr-namespace:Microsoft.OpenApi.Writers;assembly=Microsoft.OpenApi" mc:Ignorable="d" Title="OpenAPI Workbench" Height="600" Width="800"> @@ -42,7 +43,9 @@ - + + + diff --git a/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs b/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs index f33132359..08bbb177d 100644 --- a/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs +++ b/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Windows; namespace Microsoft.OpenApi.Workbench @@ -18,9 +19,15 @@ public MainWindow() DataContext = _mainModel; } - private void Button_Click(object sender, RoutedEventArgs e) + private async void Button_Click(object sender, RoutedEventArgs e) { - _mainModel.ParseDocument(); + try + { + await _mainModel.ParseDocument(); + } catch (Exception ex) + { + _mainModel.Errors = ex.Message; + } } } } diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index 47a9d6ffe..8d8239222 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -58,6 +58,7 @@ MSBuild:Compile Designer + MSBuild:Compile diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index 4f685d2de..644334ab4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -70,7 +70,7 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV3(writer); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 08b8bd020..cd8cdae74 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -80,7 +80,7 @@ public void SerializeAsV3(IOpenApiWriter writer) // If references have been inlined we don't need the to render the components section // however if they have cycles, then we will need a component rendered - if (writer.GetSettings().ReferenceInline != ReferenceInlineSetting.DoNotInlineReferences) + if (writer.GetSettings().InlineLocalReferences) { var loops = writer.GetSettings().LoopDetector.Loops; writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 0db9b2391..4f4e673af 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -135,7 +135,7 @@ public void SerializeAsV2(IOpenApiWriter writer) // If references have been inlined we don't need the to render the components section // however if they have cycles, then we will need a component rendered - if (writer.GetSettings().ReferenceInline != ReferenceInlineSetting.DoNotInlineReferences) + if (writer.GetSettings().InlineLocalReferences) { var loops = writer.GetSettings().LoopDetector.Loops; diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index d9bc08e30..787c2972e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -64,7 +64,7 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV3(writer); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index eb6736183..d94681a1c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -96,7 +96,7 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV3(writer); return; @@ -161,7 +161,7 @@ public void SerializeAsV2(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV2(writer); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index fb7396db2..82502f14a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -71,7 +71,7 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV3(writer); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 03b465109..50d78ae00 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -145,7 +145,7 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV3(writer); return; @@ -216,7 +216,7 @@ public void SerializeAsV2(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV2(writer); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index b222ba34f..78e97ec18 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -75,7 +75,7 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineAllReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV3(writer); return; @@ -95,7 +95,7 @@ public void SerializeAsV2(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineAllReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV2(writer); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index bc2e4e525..ef30602b9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -61,7 +61,7 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV3(writer); return; @@ -105,7 +105,7 @@ public void SerializeAsV2(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && writer.GetSettings().ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) { Reference.SerializeAsV2(writer); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 60e314fcf..1d579a89a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -255,7 +255,7 @@ public void SerializeAsV3(IOpenApiWriter writer) if (Reference != null) { - if (settings.ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (!settings.ShouldInlineReference(Reference)) { Reference.SerializeAsV3(writer); return; @@ -445,7 +445,7 @@ internal void SerializeAsV2( if (Reference != null) { var settings = writer.GetSettings(); - if (settings.ReferenceInline != ReferenceInlineSetting.InlineLocalReferences) + if (!settings.ShouldInlineReference(Reference)) { Reference.SerializeAsV2(writer); return; diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs index 45eedc831..458d8f4a3 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs @@ -1,36 +1,80 @@  +using System; +using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Services; namespace Microsoft.OpenApi.Writers { /// - /// Indicates if and when the reader should convert references into complete object renderings + /// Indicates if and when the writer should convert references into complete object renderings /// + [Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] public enum ReferenceInlineSetting { /// - /// Create placeholder objects with an OpenApiReference instance and UnresolvedReference set to true. + /// Render all references as $ref. /// DoNotInlineReferences, /// - /// Convert local references to references of valid domain objects. + /// Render all local references as inline objects /// InlineLocalReferences, /// - /// Convert all references to references of valid domain objects. + /// Render all references as inline objects. /// InlineAllReferences } + /// /// Configuration settings to control how OpenAPI documents are written /// public class OpenApiWriterSettings { + private ReferenceInlineSetting referenceInline = ReferenceInlineSetting.DoNotInlineReferences; + internal LoopDetector LoopDetector { get; } = new LoopDetector(); /// /// Indicates how references in the source document should be handled. /// - public ReferenceInlineSetting ReferenceInline { get; set; } = ReferenceInlineSetting.DoNotInlineReferences; + [Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] + public ReferenceInlineSetting ReferenceInline { + get { return referenceInline; } + set { + referenceInline = value; + switch(referenceInline) + { + case ReferenceInlineSetting.DoNotInlineReferences: + InlineLocalReferences = false; + InlineExternalReferences = false; + break; + case ReferenceInlineSetting.InlineLocalReferences: + InlineLocalReferences = true; + InlineExternalReferences = false; + break; + case ReferenceInlineSetting.InlineAllReferences: + InlineLocalReferences = true; + InlineExternalReferences = true; + break; + } + } + } + /// + /// Indicates if local references should be rendered as an inline object + /// + public bool InlineLocalReferences { get; set; } = false; + + /// + /// Indicates if external references should be rendered as an inline object + /// + public bool InlineExternalReferences { get; set; } = false; + + + internal bool ShouldInlineReference(OpenApiReference reference) + { + return (reference.IsLocal && InlineLocalReferences) + || (reference.IsExternal && InlineExternalReferences); + } + } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs index 4a35301c6..b3cbb8c6d 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs @@ -25,7 +25,8 @@ public async Task LoadingDocumentWithResolveAllReferencesShouldLoadDocumentIntoW var reader = new OpenApiStreamReader(new OpenApiReaderSettings() { ReferenceResolution = ReferenceResolutionSetting.ResolveAllReferences, - CustomExternalLoader = new MockLoader() + CustomExternalLoader = new MockLoader(), + BaseUrl = new Uri("file://c:\\") }); // Todo: this should be ReadAsync @@ -54,7 +55,8 @@ public async Task LoadDocumentWithExternalReferenceShouldLoadBothDocumentsIntoWo var reader = new OpenApiStreamReader(new OpenApiReaderSettings() { ReferenceResolution = ReferenceResolutionSetting.ResolveAllReferences, - CustomExternalLoader = new ResourceLoader() + CustomExternalLoader = new ResourceLoader(), + BaseUrl = new Uri("fie://c:\\") }); ReadResult result; diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index d5a89e586..e4c3f4282 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1323,6 +1323,9 @@ namespace Microsoft.OpenApi.Writers public class OpenApiWriterSettings { public OpenApiWriterSettings() { } + public bool InlineExternalReferences { get; set; } + public bool InlineLocalReferences { get; set; } + [System.Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] public Microsoft.OpenApi.Writers.ReferenceInlineSetting ReferenceInline { get; set; } } public class OpenApiYamlWriter : Microsoft.OpenApi.Writers.OpenApiWriterBase @@ -1341,6 +1344,7 @@ namespace Microsoft.OpenApi.Writers public override void WriteValue(string value) { } protected override void WriteValueSeparator() { } } + [System.Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] public enum ReferenceInlineSetting { DoNotInlineReferences = 0, diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs index a73fdbb9b..29e8c7676 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs @@ -373,7 +373,7 @@ public void WriteInlineSchema() components: { }"; var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { ReferenceInline = ReferenceInlineSetting.InlineLocalReferences}); + var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true } ); // Act doc.SerializeAsV3(writer); @@ -409,7 +409,7 @@ public void WriteInlineSchemaV2() type: object"; var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { ReferenceInline = ReferenceInlineSetting.InlineLocalReferences }); + var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true }); // Act doc.SerializeAsV2(writer); @@ -515,7 +515,7 @@ public void WriteInlineRecursiveSchema() // Component schemas that are there due to cycles are still inlined because the items they reference may not exist in the components because they don't have cycles. var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { ReferenceInline = ReferenceInlineSetting.InlineLocalReferences }); + var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true }); // Act doc.SerializeAsV3(writer); @@ -629,7 +629,7 @@ public void WriteInlineRecursiveSchemav2() // Component schemas that are there due to cycles are still inlined because the items they reference may not exist in the components because they don't have cycles. var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { ReferenceInline = ReferenceInlineSetting.InlineLocalReferences }); + var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true }); // Act doc.SerializeAsV2(writer); From a4519b4627c3d056e7f062740ab57e08437cd192 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 29 Jan 2022 17:12:59 -0500 Subject: [PATCH 005/855] Updated hidi parameters to control both local and remote inlining independently --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 12 +++++++----- src/Microsoft.OpenApi.Hidi/Program.cs | 6 +++--- .../OpenApiReaderSettings.cs | 2 +- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index e381dd64f..05b44c9c6 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -26,11 +26,12 @@ public static void ProcessOpenApiDocument( FileInfo output, OpenApiSpecVersion? version, OpenApiFormat? format, + bool inlineExternal, + bool inlineLocal, string filterByOperationIds, string filterByTags, - string filterByCollection, - bool inline, - bool resolveExternal) + string filterByCollection + ) { if (string.IsNullOrEmpty(input)) { @@ -52,7 +53,7 @@ public static void ProcessOpenApiDocument( var result = new OpenApiStreamReader(new OpenApiReaderSettings { - ReferenceResolution = resolveExternal == true ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, + ReferenceResolution = inlineExternal == true ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, RuleSet = ValidationRuleSet.GetDefaultRuleSet(), BaseUrl = new Uri(inputUrl.AbsoluteUri) } @@ -105,7 +106,8 @@ public static void ProcessOpenApiDocument( var settings = new OpenApiWriterSettings() { - ReferenceInline = inline ? ReferenceInlineSetting.InlineLocalReferences : ReferenceInlineSetting.DoNotInlineReferences + InlineLocalReferences = inlineLocal, + InlineExternalReferences = inlineExternal }; var openApiFormat = format ?? GetOpenApiFormat(input); diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 8bc54e2fc..c6f7eff44 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -28,13 +28,13 @@ static async Task Main(string[] args) new Option("--output","Output OpenAPI description file", typeof(FileInfo), arity: ArgumentArity.ZeroOrOne), new Option("--version", "OpenAPI specification version", typeof(OpenApiSpecVersion)), new Option("--format", "File format",typeof(OpenApiFormat) ), - new Option("--inline", "Inline $ref instances", typeof(bool) ), - new Option("--resolveExternal","Resolve external $refs", typeof(bool)), + new Option("--inlineExternal", "Inline external $ref instances", typeof(bool) ), + new Option("--inlineLocal", "Inline local $ref instances", typeof(bool) ), new Option("--filterByOperationIds", "Filters OpenApiDocument by OperationId(s) provided", typeof(string)), new Option("--filterByTags", "Filters OpenApiDocument by Tag(s) provided", typeof(string)), new Option("--filterByCollection", "Filters OpenApiDocument by Postman collection provided", typeof(string)) }; - transformCommand.Handler = CommandHandler.Create( + transformCommand.Handler = CommandHandler.Create( OpenApiService.ProcessOpenApiDocument); rootCommand.Add(transformCommand); diff --git a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs index 732708459..2e8d50adb 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs @@ -30,7 +30,7 @@ public enum ReferenceResolutionSetting /// ResolveLocalReferences, /// - /// Convert all references to references of valid domain objects. + /// Not used anymore. Will be removed in v2. Convert all references to references of valid domain objects. /// ResolveAllReferences } From 4c26dbb5727b2b8412a380e7dd7ae61df96cf780 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 19 Feb 2022 12:38:48 -0500 Subject: [PATCH 006/855] Added hostdocument to OpenApiReference --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 2 +- .../OpenApiReaderSettings.cs | 13 +- .../OpenApiStreamReader.cs | 2 +- .../OpenApiYamlDocumentReader.cs | 56 ++++----- .../Interfaces/IEffective.cs | 23 ++++ .../Interfaces/IOpenApiReferenceable.cs | 1 + .../Models/OpenApiDocument.cs | 34 ++++-- .../Models/OpenApiParameter.cs | 14 ++- .../Models/OpenApiReference.cs | 5 + src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 24 +++- .../Models/OpenApiSecurityScheme.cs | 4 +- .../Services/OpenApiReferenceResolver.cs | 43 ++++--- .../OpenApiWorkspaceStreamTests.cs | 13 +- .../TryLoadReferenceV2Tests.cs | 13 +- .../V2Tests/OpenApiDocumentTests.cs | 28 +++-- .../V3Tests/OpenApiCallbackTests.cs | 2 + .../V3Tests/OpenApiDocumentTests.cs | 115 +++++++++++++----- .../V3Tests/OpenApiSchemaTests.cs | 28 +++-- .../Workspaces/OpenApiWorkspaceTests.cs | 5 +- .../Writers/OpenApiYamlWriterTests.cs | 13 +- 20 files changed, 287 insertions(+), 151 deletions(-) create mode 100644 src/Microsoft.OpenApi/Interfaces/IEffective.cs diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 05b44c9c6..890327ddc 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -53,7 +53,7 @@ string filterByCollection var result = new OpenApiStreamReader(new OpenApiReaderSettings { - ReferenceResolution = inlineExternal == true ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, + LoadExternalRefs = inlineExternal, RuleSet = ValidationRuleSet.GetDefaultRuleSet(), BaseUrl = new Uri(inputUrl.AbsoluteUri) } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs index 2e8d50adb..12ccdb681 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs @@ -4,15 +4,10 @@ using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Readers.Interface; -using Microsoft.OpenApi.Readers.ParseNodes; -using Microsoft.OpenApi.Readers.Services; using Microsoft.OpenApi.Validations; using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Microsoft.OpenApi.Readers { @@ -30,7 +25,7 @@ public enum ReferenceResolutionSetting /// ResolveLocalReferences, /// - /// Not used anymore. Will be removed in v2. Convert all references to references of valid domain objects. + /// ResolveAllReferences effectively means load external references. Will be removed in v2. External references are never "resolved". /// ResolveAllReferences } @@ -43,8 +38,14 @@ public class OpenApiReaderSettings /// /// Indicates how references in the source document should be handled. /// + /// This setting will be going away in the next major version of this library. Use GetEffective on model objects to get resolved references. public ReferenceResolutionSetting ReferenceResolution { get; set; } = ReferenceResolutionSetting.ResolveLocalReferences; + /// + /// When external references are found, load them into a shared workspace + /// + public bool LoadExternalRefs { get; set; } = false; + /// /// Dictionary of parsers for converting extensions into strongly typed classes /// diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index 987e79ceb..13bdbdef8 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -25,7 +25,7 @@ public OpenApiStreamReader(OpenApiReaderSettings settings = null) { _settings = settings ?? new OpenApiReaderSettings(); - if(_settings.ReferenceResolution == ReferenceResolutionSetting.ResolveAllReferences + if((_settings.ReferenceResolution == ReferenceResolutionSetting.ResolveAllReferences || _settings.LoadExternalRefs) && _settings.BaseUrl == null) { throw new ArgumentException("BaseUrl must be provided to resolve external references."); diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 63b78ccba..6cf64a5bb 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -53,6 +53,11 @@ public OpenApiDocument Read(YamlDocument input, out OpenApiDiagnostic diagnostic // Parse the OpenAPI Document document = context.Parse(input); + if (_settings.LoadExternalRefs) + { + throw new InvalidOperationException("Cannot load external refs using the synchronous Read, use ReadAsync instead."); + } + ResolveReferences(diagnostic, document); } catch (OpenApiException ex) @@ -88,7 +93,12 @@ public async Task ReadAsync(YamlDocument input) // Parse the OpenAPI Document document = context.Parse(input); - await ResolveReferencesAsync(diagnostic, document, _settings.BaseUrl); + if (_settings.LoadExternalRefs) + { + await LoadExternalRefs(document); + } + + ResolveReferences(diagnostic, document); } catch (OpenApiException ex) { @@ -112,28 +122,18 @@ public async Task ReadAsync(YamlDocument input) }; } - - private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument document) + private async Task LoadExternalRefs(OpenApiDocument document) { - // Resolve References if requested - switch (_settings.ReferenceResolution) - { - case ReferenceResolutionSetting.ResolveAllReferences: - throw new ArgumentException("Cannot resolve all references via a synchronous call. Use ReadAsync."); - case ReferenceResolutionSetting.ResolveLocalReferences: - var errors = document.ResolveReferences(false); + // Create workspace for all documents to live in. + var openApiWorkSpace = new OpenApiWorkspace(); - foreach (var item in errors) - { - diagnostic.Errors.Add(item); - } - break; - case ReferenceResolutionSetting.DoNotResolveReferences: - break; - } + // Load this root document into the workspace + var streamLoader = new DefaultStreamLoader(_settings.BaseUrl); + var workspaceLoader = new OpenApiWorkspaceLoader(openApiWorkSpace, _settings.CustomExternalLoader ?? streamLoader, _settings); + await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document); } - private async Task ResolveReferencesAsync(OpenApiDiagnostic diagnostic, OpenApiDocument document, Uri baseUrl) + private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument document) { List errors = new List(); @@ -141,23 +141,9 @@ private async Task ResolveReferencesAsync(OpenApiDiagnostic diagnostic, OpenApiD switch (_settings.ReferenceResolution) { case ReferenceResolutionSetting.ResolveAllReferences: - - // Create workspace for all documents to live in. - var openApiWorkSpace = new OpenApiWorkspace(); - - // Load this root document into the workspace - var streamLoader = new DefaultStreamLoader(baseUrl); - var workspaceLoader = new OpenApiWorkspaceLoader(openApiWorkSpace, _settings.CustomExternalLoader ?? streamLoader, _settings); - await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document); - - // Resolve all references in all the documents loaded into the OpenApiWorkspace - foreach (var doc in openApiWorkSpace.Documents) - { - errors.AddRange(doc.ResolveReferences(true)); - } - break; + throw new ArgumentException("Resolving external references is not supported"); case ReferenceResolutionSetting.ResolveLocalReferences: - errors.AddRange(document.ResolveReferences(false)); + errors.AddRange(document.ResolveReferences()); break; case ReferenceResolutionSetting.DoNotResolveReferences: break; diff --git a/src/Microsoft.OpenApi/Interfaces/IEffective.cs b/src/Microsoft.OpenApi/Interfaces/IEffective.cs new file mode 100644 index 000000000..b62ec12ab --- /dev/null +++ b/src/Microsoft.OpenApi/Interfaces/IEffective.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Microsoft.OpenApi.Models; + +namespace Microsoft.OpenApi.Interfaces +{ + /// + /// OpenApiElements that implement IEffective indicate that their description is not self-contained. + /// External elements affect the effective description. + /// + /// Currently this will only be used for accessing external references. + /// In the next major version, this will be the approach accessing all referenced elements. + /// This will enable us to support merging properties that are peers of the $ref + /// Type of OpenApi Element that is being referenced. + public interface IEffective where T : class,IOpenApiElement + { + /// + /// Returns a calculated and cloned version of the element. + /// + T GetEffective(OpenApiDocument document); + } +} diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs index eb47c64bc..c790e1fda 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs @@ -31,5 +31,6 @@ public interface IOpenApiReferenceable : IOpenApiSerializable /// Serialize to OpenAPI V2 document without using reference. /// void SerializeAsV2WithoutReference(IOpenApiWriter writer); + } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 4f4e673af..6ffc260d1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -321,27 +321,37 @@ private static void WriteHostInfoV2(IOpenApiWriter writer, IList /// /// Walk the OpenApiDocument and resolve unresolved references /// - /// Indicates if external references should be resolved. Document needs to reference a workspace for this to be possible. - public IEnumerable ResolveReferences(bool useExternal = false) + /// + /// This method will be replaced by a LoadExternalReferences in the next major update to this library. + /// Resolving references at load time is going to go away. + /// + public IEnumerable ResolveReferences() { - var resolver = new OpenApiReferenceResolver(this, useExternal); + var resolver = new OpenApiReferenceResolver(this, false); var walker = new OpenApiWalker(resolver); walker.Walk(this); return resolver.Errors; } - /// - /// Load the referenced object from a object - /// - public IOpenApiReferenceable ResolveReference(OpenApiReference reference) + /// + /// Load the referenced object from a object + /// + internal T ResolveReferenceTo(OpenApiReference reference) where T : class, IOpenApiReferenceable + { + if (reference.IsExternal) { - return ResolveReference(reference, false); + return ResolveReference(reference, true) as T; } + else + { + return ResolveReference(reference, false) as T; + } + } - /// - /// Load the referenced object from a object - /// - public IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) + /// + /// Load the referenced object from a object + /// + internal IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) { if (reference == null) { diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 50d78ae00..ebc70465a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -12,7 +12,7 @@ namespace Microsoft.OpenApi.Models /// /// Parameter Object. /// - public class OpenApiParameter : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible + public class OpenApiParameter : IOpenApiSerializable, IOpenApiReferenceable, IEffective, IOpenApiExtensible { private bool? _explode; @@ -332,6 +332,18 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) writer.WriteEndObject(); } + + public OpenApiParameter GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } + } } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index cbe64d3e6..3f1370800 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -45,6 +45,11 @@ public class OpenApiReference : IOpenApiSerializable /// public bool IsLocal => ExternalResource == null; + /// + /// The OpenApiDocument that is hosting the OpenApiReference instance. This is used to enable dereferencing the reference. + /// + public OpenApiDocument HostDocument { get; set; } = null; + /// /// Gets the full reference string for v3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 1d579a89a..c98c32c17 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Models /// /// Schema Object. /// - public class OpenApiSchema : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible + public class OpenApiSchema : IOpenApiSerializable, IOpenApiReferenceable, IEffective, IOpenApiExtensible { /// /// Follow JSON Schema definition. Short text providing information about the data. @@ -252,6 +252,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } var settings = writer.GetSettings(); + var target = this; if (Reference != null) { @@ -259,6 +260,13 @@ public void SerializeAsV3(IOpenApiWriter writer) { Reference.SerializeAsV3(writer); return; + } + else + { + if (Reference.IsExternal) // Temporary until v2 + { + target = this.GetEffective(Reference.HostDocument); + } } // If Loop is detected then just Serialize as a reference. @@ -270,7 +278,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } } - SerializeAsV3WithoutReference(writer); + target.SerializeAsV3WithoutReference(writer); if (Reference != null) { @@ -283,6 +291,7 @@ public void SerializeAsV3(IOpenApiWriter writer) /// public void SerializeAsV3WithoutReference(IOpenApiWriter writer) { + writer.WriteStartObject(); // title @@ -666,5 +675,16 @@ internal void WriteAsSchemaProperties( // extensions writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); } + + public OpenApiSchema GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } else + { + return this; + } + } } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 7694c5fd4..902ce19bc 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; @@ -83,7 +84,8 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null) + + if (Reference != null) { Reference.SerializeAsV3(writer); return; diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index 6755883b6..840f9c660 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -42,6 +42,13 @@ public override void Visit(OpenApiDocument doc) } } + public override void Visit(IOpenApiReferenceable referenceable) + { + if (referenceable.Reference != null) + { + referenceable.Reference.HostDocument = _currentDocument; + } + } public override void Visit(OpenApiComponents components) { ResolveMap(components.Parameters); @@ -237,7 +244,7 @@ private void ResolveTags(IList tags) { try { - return _currentDocument.ResolveReference(reference) as T; + return _currentDocument.ResolveReference(reference, false) as T; } catch (OpenApiException ex) { @@ -245,24 +252,26 @@ private void ResolveTags(IList tags) return null; } } - else if (_resolveRemoteReferences == true) - { - if (_currentDocument.Workspace == null) - { - _errors.Add(new OpenApiReferenceError(reference,"Cannot resolve external references for documents not in workspaces.")); - // Leave as unresolved reference - return new T() - { - UnresolvedReference = true, - Reference = reference - }; - } - var target = _currentDocument.Workspace.ResolveReference(reference); + // The concept of merging references with their target at load time is going away in the next major version + // External references will not support this approach. + //else if (_resolveRemoteReferences == true) + //{ + // if (_currentDocument.Workspace == null) + // { + // _errors.Add(new OpenApiReferenceError(reference,"Cannot resolve external references for documents not in workspaces.")); + // // Leave as unresolved reference + // return new T() + // { + // UnresolvedReference = true, + // Reference = reference + // }; + // } + // var target = _currentDocument.Workspace.ResolveReference(reference); - // TODO: If it is a document fragment, then we should resolve it within the current context + // // TODO: If it is a document fragment, then we should resolve it within the current context - return target as T; - } + // return target as T; + //} else { // Leave as unresolved reference diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs index b3cbb8c6d..4a2c2cafe 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs @@ -1,13 +1,9 @@ using System; -using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using System.Threading.Tasks; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.Interface; -using Microsoft.OpenApi.Readers.Services; -using Microsoft.OpenApi.Services; using Xunit; namespace Microsoft.OpenApi.Readers.Tests.OpenApiWorkspaceTests @@ -24,7 +20,7 @@ public async Task LoadingDocumentWithResolveAllReferencesShouldLoadDocumentIntoW // Create a reader that will resolve all references var reader = new OpenApiStreamReader(new OpenApiReaderSettings() { - ReferenceResolution = ReferenceResolutionSetting.ResolveAllReferences, + LoadExternalRefs = true, CustomExternalLoader = new MockLoader(), BaseUrl = new Uri("file://c:\\") }); @@ -54,7 +50,7 @@ public async Task LoadDocumentWithExternalReferenceShouldLoadBothDocumentsIntoWo // Create a reader that will resolve all references var reader = new OpenApiStreamReader(new OpenApiReaderSettings() { - ReferenceResolution = ReferenceResolutionSetting.ResolveAllReferences, + LoadExternalRefs = true, CustomExternalLoader = new ResourceLoader(), BaseUrl = new Uri("fie://c:\\") }); @@ -73,7 +69,7 @@ public async Task LoadDocumentWithExternalReferenceShouldLoadBothDocumentsIntoWo .Operations[OperationType.Get] .Responses["200"] .Content["application/json"] - .Schema; + .Schema.GetEffective(result.OpenApiDocument); Assert.Equal("object", referencedSchema.Type); Assert.Equal("string", referencedSchema.Properties["subject"].Type); Assert.False(referencedSchema.UnresolvedReference); @@ -81,8 +77,9 @@ public async Task LoadDocumentWithExternalReferenceShouldLoadBothDocumentsIntoWo var referencedParameter = result.OpenApiDocument .Paths["/todos"] .Operations[OperationType.Get] - .Parameters + .Parameters.Select(p => p.GetEffective(result.OpenApiDocument)) .Where(p => p.Name == "filter").FirstOrDefault(); + Assert.Equal("string", referencedParameter.Schema.Type); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs index d7f110b10..a641b7d6f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs @@ -38,7 +38,7 @@ public void LoadSchemaReference() }; // Act - var referencedObject = document.ResolveReference(reference); + var referencedObject = document.ResolveReferenceTo(reference); // Assert referencedObject.Should().BeEquivalentTo( @@ -93,7 +93,7 @@ public void LoadParameterReference() }; // Act - var referencedObject = document.ResolveReference(reference); + var referencedObject = document.ResolveReferenceTo(reference); // Assert referencedObject.Should().BeEquivalentTo( @@ -136,7 +136,7 @@ public void LoadSecuritySchemeReference() }; // Act - var referencedObject = document.ResolveReference(reference); + var referencedObject = document.ResolveReferenceTo(reference); // Assert referencedObject.Should().BeEquivalentTo( @@ -173,7 +173,7 @@ public void LoadResponseReference() }; // Act - var referencedObject = document.ResolveReference(reference); + var referencedObject = document.ResolveReferenceTo(reference); // Assert referencedObject.Should().BeEquivalentTo( @@ -212,7 +212,7 @@ public void LoadResponseAndSchemaReference() }; // Act - var referencedObject = document.ResolveReference(reference); + var referencedObject = document.ResolveReferenceTo(reference); // Assert referencedObject.Should().BeEquivalentTo( @@ -241,7 +241,8 @@ public void LoadResponseAndSchemaReference() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "SampleObject2" + Id = "SampleObject2", + HostDocument = document } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index ad8e7e445..57593a79e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -8,15 +8,23 @@ using FluentAssertions; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Exceptions; +using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Writers; using Xunit; namespace Microsoft.OpenApi.Readers.Tests.V2Tests { + + public class OpenApiDocumentTests { private const string SampleFolderPath = "V2Tests/Samples/"; + + + [Fact] public void ShouldThrowWhenReferenceTypeIsInvalid() { @@ -161,7 +169,8 @@ public void ShouldParseProducesInAnyOrder() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "Item" + Id = "Item", + HostDocument = doc }, Items = new OpenApiSchema() { @@ -177,7 +186,8 @@ public void ShouldParseProducesInAnyOrder() Reference = new OpenApiReference() { Type = ReferenceType.Schema, - Id = "Item" + Id = "Item", + HostDocument = doc } } }; @@ -187,7 +197,8 @@ public void ShouldParseProducesInAnyOrder() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "Item" + Id = "Item", + HostDocument = doc }, Properties = new Dictionary() { @@ -205,7 +216,8 @@ public void ShouldParseProducesInAnyOrder() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "Error" + Id = "Error", + HostDocument= doc }, Properties = new Dictionary() { @@ -375,7 +387,8 @@ public void ShouldAssignSchemaToAllResponses() Reference = new OpenApiReference { Id = "Item", - Type = ReferenceType.Schema + Type = ReferenceType.Schema, + HostDocument = document } } }; @@ -402,7 +415,8 @@ public void ShouldAssignSchemaToAllResponses() Reference = new OpenApiReference { Id = "Error", - Type = ReferenceType.Schema + Type = ReferenceType.Schema, + HostDocument= document } }; var responses = document.Paths["/items"].Operations[OperationType.Get].Responses; @@ -430,7 +444,7 @@ public void ShouldAllowComponentsThatJustContainAReference() OpenApiDocument doc = reader.Read(stream, out OpenApiDiagnostic diags); OpenApiSchema schema1 = doc.Components.Schemas["AllPets"]; Assert.False(schema1.UnresolvedReference); - OpenApiSchema schema2 = (OpenApiSchema)doc.ResolveReference(schema1.Reference); + OpenApiSchema schema2 = doc.ResolveReferenceTo(schema1.Reference); if (schema2.UnresolvedReference && schema1.Reference.Id == schema2.Reference.Id) { // detected a cycle - this code gets triggered diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs index f23bee9f9..320f01fae 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs @@ -127,6 +127,7 @@ public void ParseCallbackWithReferenceShouldSucceed() { Type = ReferenceType.Callback, Id = "simpleHook", + HostDocument = openApiDoc } }); } @@ -185,6 +186,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { Type = ReferenceType.Callback, Id = "simpleHook", + HostDocument = openApiDoc } }); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 93d3c1a1b..f1d8b805f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -9,9 +9,12 @@ using System.Threading; using FluentAssertions; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Validations; using Microsoft.OpenApi.Validations.Rules; +using Microsoft.OpenApi.Writers; using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; @@ -25,6 +28,49 @@ public class OpenApiDocumentTests private readonly ITestOutputHelper _output; + public T Clone(T element) where T : IOpenApiSerializable + { + using (var stream = new MemoryStream()) + { + IOpenApiWriter writer; + var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); + writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() { + InlineLocalReferences = true}); + element.SerializeAsV3(writer); + writer.Flush(); + stream.Position = 0; + + using (var streamReader = new StreamReader(stream)) + { + var result = streamReader.ReadToEnd(); + return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); + } + } + } + + public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) + { + using (var stream = new MemoryStream()) + { + IOpenApiWriter writer; + var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); + writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() + { + InlineLocalReferences = true + }); + element.SerializeAsV3WithoutReference(writer); + writer.Flush(); + stream.Position = 0; + + using (var streamReader = new StreamReader(stream)) + { + var result = streamReader.ReadToEnd(); + return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); + } + } + } + + public OpenApiDocumentTests(ITestOutputHelper output) { _output = output; @@ -256,7 +302,8 @@ public void ParseStandardPetStoreDocumentShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "pet" + Id = "pet", + HostDocument = actual } }, ["newPet"] = new OpenApiSchema @@ -285,7 +332,8 @@ public void ParseStandardPetStoreDocumentShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "newPet" + Id = "newPet", + HostDocument = actual } }, ["errorModel"] = new OpenApiSchema @@ -311,38 +359,39 @@ public void ParseStandardPetStoreDocumentShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "errorModel" + Id = "errorModel", + HostDocument = actual } }, } }; // Create a clone of the schema to avoid modifying things in components. - var petSchema = - JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(components.Schemas["pet"])); + var petSchema = Clone(components.Schemas["pet"]); + petSchema.Reference = new OpenApiReference { Id = "pet", - Type = ReferenceType.Schema + Type = ReferenceType.Schema, + HostDocument = actual }; - var newPetSchema = - JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(components.Schemas["newPet"])); + var newPetSchema = Clone(components.Schemas["newPet"]); + newPetSchema.Reference = new OpenApiReference { Id = "newPet", - Type = ReferenceType.Schema + Type = ReferenceType.Schema, + HostDocument = actual }; - var errorModelSchema = - JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(components.Schemas["errorModel"])); + var errorModelSchema = Clone(components.Schemas["errorModel"]); + errorModelSchema.Reference = new OpenApiReference { Id = "errorModel", - Type = ReferenceType.Schema + Type = ReferenceType.Schema, + HostDocument = actual }; var expected = new OpenApiDocument @@ -683,7 +732,8 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "pet" + Id = "pet", + HostDocument = actual } }, ["newPet"] = new OpenApiSchema @@ -712,7 +762,8 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "newPet" + Id = "newPet", + HostDocument = actual } }, ["errorModel"] = new OpenApiSchema @@ -752,7 +803,8 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() Reference = new OpenApiReference { Id = "securitySchemeName1", - Type = ReferenceType.SecurityScheme + Type = ReferenceType.SecurityScheme, + HostDocument = actual } }, @@ -763,34 +815,31 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() Reference = new OpenApiReference { Id = "securitySchemeName2", - Type = ReferenceType.SecurityScheme + Type = ReferenceType.SecurityScheme, + HostDocument = actual } } } }; // Create a clone of the schema to avoid modifying things in components. - var petSchema = - JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(components.Schemas["pet"])); + var petSchema = Clone(components.Schemas["pet"]); petSchema.Reference = new OpenApiReference { Id = "pet", Type = ReferenceType.Schema }; - var newPetSchema = - JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(components.Schemas["newPet"])); + var newPetSchema = Clone(components.Schemas["newPet"]); + newPetSchema.Reference = new OpenApiReference { Id = "newPet", Type = ReferenceType.Schema }; - var errorModelSchema = - JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(components.Schemas["errorModel"])); + var errorModelSchema = Clone(components.Schemas["errorModel"]); + errorModelSchema.Reference = new OpenApiReference { Id = "errorModel", @@ -814,16 +863,16 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() Name = "tagName2" }; - var securityScheme1 = JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(components.SecuritySchemes["securitySchemeName1"])); + var securityScheme1 = CloneSecurityScheme(components.SecuritySchemes["securitySchemeName1"]); + securityScheme1.Reference = new OpenApiReference { Id = "securitySchemeName1", Type = ReferenceType.SecurityScheme }; - var securityScheme2 = JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(components.SecuritySchemes["securitySchemeName2"])); + var securityScheme2 = CloneSecurityScheme(components.SecuritySchemes["securitySchemeName2"]); + securityScheme2.Reference = new OpenApiReference { Id = "securitySchemeName2", @@ -1170,7 +1219,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() } }; - actual.Should().BeEquivalentTo(expected); + actual.Should().BeEquivalentTo(expected, options => options.Excluding(m => m.Name == "HostDocument")); } context.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index dbf0cf3f6..9bdafeba6 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -359,7 +359,8 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "ErrorModel" + Id = "ErrorModel", + HostDocument = openApiDoc }, Required = { @@ -372,7 +373,8 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "ExtendedErrorModel" + Id = "ExtendedErrorModel", + HostDocument = openApiDoc }, AllOf = { @@ -381,7 +383,8 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "ErrorModel" + Id = "ErrorModel", + HostDocument = openApiDoc }, // Schema should be dereferenced in our model, so all the properties // from the ErrorModel above should be propagated here. @@ -420,7 +423,7 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() } } } - }); + },options => options.Excluding(m => m.Name == "HostDocument")); } } @@ -469,7 +472,8 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() Reference = new OpenApiReference() { Id= "Pet", - Type = ReferenceType.Schema + Type = ReferenceType.Schema, + HostDocument = openApiDoc } }, ["Cat"] = new OpenApiSchema @@ -482,7 +486,8 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "Pet" + Id = "Pet", + HostDocument = openApiDoc }, // Schema should be dereferenced in our model, so all the properties // from the Pet above should be propagated here. @@ -532,7 +537,8 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() Reference = new OpenApiReference() { Id= "Cat", - Type = ReferenceType.Schema + Type = ReferenceType.Schema, + HostDocument = openApiDoc } }, ["Dog"] = new OpenApiSchema @@ -545,7 +551,8 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() Reference = new OpenApiReference { Type = ReferenceType.Schema, - Id = "Pet" + Id = "Pet", + HostDocument = openApiDoc }, // Schema should be dereferenced in our model, so all the properties // from the Pet above should be propagated here. @@ -591,11 +598,12 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() Reference = new OpenApiReference() { Id= "Dog", - Type = ReferenceType.Schema + Type = ReferenceType.Schema, + HostDocument = openApiDoc } } } - }); + }, options => options.Excluding(m => m.Name == "HostDocument")); } } diff --git a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs index bee746eae..63045847b 100644 --- a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs @@ -126,11 +126,12 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther_short() workspace.AddDocument("root", doc); workspace.AddDocument("common", CreateCommonDocument()); - var errors = doc.ResolveReferences(true); + var errors = doc.ResolveReferences(); Assert.Empty(errors); var schema = doc.Paths["/"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema; - Assert.False(schema.UnresolvedReference); + var effectiveSchema = schema.GetEffective(doc); + Assert.False(effectiveSchema.UnresolvedReference); } [Fact] diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs index 29e8c7676..bfaa3da51 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs @@ -468,6 +468,8 @@ private static OpenApiDocument CreateDocWithSimpleSchemaToInline() ["thing"] = thingSchema} } }; + thingSchema.Reference.HostDocument = doc; + return doc; } @@ -544,12 +546,6 @@ private static OpenApiDocument CreateDocWithRecursiveSchemaReference() var relatedSchema = new OpenApiSchema() { Type = "integer", - UnresolvedReference = false, - Reference = new OpenApiReference - { - Id = "related", - Type = ReferenceType.Schema - } }; thingSchema.Properties["related"] = relatedSchema; @@ -587,6 +583,7 @@ private static OpenApiDocument CreateDocWithRecursiveSchemaReference() ["thing"] = thingSchema} } }; + thingSchema.Reference.HostDocument = doc; return doc; } @@ -623,9 +620,7 @@ public void WriteInlineRecursiveSchemav2() children: $ref: '#/definitions/thing' related: - $ref: '#/definitions/related' - related: - type: integer"; + type: integer"; // Component schemas that are there due to cycles are still inlined because the items they reference may not exist in the components because they don't have cycles. var outputString = new StringWriter(CultureInfo.InvariantCulture); From d41cf71d7c65c3adae3486003a73e43c79644a84 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 19 Feb 2022 15:01:59 -0500 Subject: [PATCH 007/855] Missed these files --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 103 +------------------ src/Microsoft.OpenApi.Hidi/Program.cs | 22 ---- 2 files changed, 4 insertions(+), 121 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 7f51960d3..632042f38 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -34,14 +34,6 @@ public static async void ProcessOpenApiDocument( FileInfo output, OpenApiSpecVersion? version, OpenApiFormat? format, -<<<<<<< HEAD - bool inlineExternal, - bool inlineLocal, - string filterByOperationIds, - string filterByTags, - string filterByCollection - ) -======= LogLevel loglevel, bool inline, bool resolveexternal, @@ -49,7 +41,6 @@ string filterByCollection string filterbytags, string filterbycollection ) ->>>>>>> origin/vnext { var logger = ConfigureLoggerInstance(loglevel); @@ -95,18 +86,6 @@ string filterbycollection OpenApiFormat openApiFormat; var stopwatch = new Stopwatch(); -<<<<<<< HEAD - var inputUrl = GetInputUrl(input); - var stream = GetStream(inputUrl); - - OpenApiDocument document; - - var result = new OpenApiStreamReader(new OpenApiReaderSettings - { - LoadExternalRefs = inlineExternal, - RuleSet = ValidationRuleSet.GetDefaultRuleSet(), - BaseUrl = new Uri(inputUrl.AbsoluteUri) -======= if (!string.IsNullOrEmpty(csdl)) { // Default to yaml and OpenApiVersion 3 during csdl to OpenApi conversion @@ -151,13 +130,8 @@ string filterbycollection openApiFormat = format ?? GetOpenApiFormat(openapi, logger); version ??= result.OpenApiDiagnostic.SpecificationVersion; ->>>>>>> origin/vnext } -<<<<<<< HEAD - document = result.OpenApiDocument; -======= ->>>>>>> origin/vnext Func predicate; // Check if filter options are provided, then slice the OpenAPI document @@ -178,15 +152,7 @@ string filterbycollection logger.LogTrace("Creating predicate based on the tags supplied."); predicate = OpenApiFilterService.CreatePredicate(tags: filterbytags); -<<<<<<< HEAD - if (!string.IsNullOrEmpty(filterByCollection)) - { - var fileStream = GetStream(GetInputUrl(filterByCollection)); - var requestUrls = ParseJsonCollectionFile(fileStream); - predicate = OpenApiFilterService.CreatePredicate(requestUrls: requestUrls, source:document); -======= logger.LogTrace("Creating subset OpenApi document."); ->>>>>>> origin/vnext document = OpenApiFilterService.CreateFilteredDocument(document, predicate); } if (!string.IsNullOrEmpty(filterbycollection)) @@ -229,26 +195,6 @@ string filterbycollection textWriter.Flush(); } -<<<<<<< HEAD - private static Uri GetInputUrl(string input) - { - if (input.StartsWith("http")) - { - return new Uri(input); - } - else - { - return new Uri("file://" + Path.GetFullPath(input)); - } - } - - private static Stream GetStream(Uri input) - { - Stream stream; - if (input.Scheme == "http" || input.Scheme == "https") - { - var httpClient = new HttpClient(new HttpClientHandler() -======= /// /// Converts CSDL to OpenAPI /// @@ -303,10 +249,9 @@ private static async Task GetStream(string input, ILogger logger) stopwatch.Start(); Stream stream; - if (input.StartsWith("http")) + if (input.Scheme == "http" || input.Scheme == "https") { try ->>>>>>> origin/vnext { var httpClientHandler = new HttpClientHandler() { @@ -326,14 +271,6 @@ private static async Task GetStream(string input, ILogger logger) } else if (input.Scheme == "file") { -<<<<<<< HEAD - var fileInput = new FileInfo(input.AbsolutePath); - stream = fileInput.OpenRead(); - } - else - { - throw new ArgumentException("Unrecognized exception"); -======= try { var fileInput = new FileInfo(input); @@ -350,7 +287,6 @@ ex is SecurityException || logger.LogError($"Could not open the file at {input}, reason: {ex.Message}"); return null; } ->>>>>>> origin/vnext } stopwatch.Stop(); logger.LogTrace("{timestamp}ms: Read file {input}", stopwatch.ElapsedMilliseconds, input); @@ -389,31 +325,18 @@ public static Dictionary> ParseJsonCollectionFile(Stream st return requestUrls; } -<<<<<<< HEAD - internal static async Task ValidateOpenApiDocument(string input, bool resolveExternal) -======= internal static async Task ValidateOpenApiDocument(string openapi, LogLevel loglevel) ->>>>>>> origin/vnext { if (string.IsNullOrEmpty(openapi)) { throw new ArgumentNullException(nameof(openapi)); } -<<<<<<< HEAD - var inputUrl = GetInputUrl(input); - var stream = GetStream(GetInputUrl(input)); - - OpenApiDocument document; - - var result = await new OpenApiStreamReader(new OpenApiReaderSettings -======= var logger = ConfigureLoggerInstance(loglevel); var stream = await GetStream(openapi, logger); OpenApiDocument document; logger.LogTrace("Parsing the OpenApi file"); document = new OpenApiStreamReader(new OpenApiReaderSettings ->>>>>>> origin/vnext { ReferenceResolution = resolveExternal == true ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, RuleSet = ValidationRuleSet.GetDefaultRuleSet(), @@ -432,30 +355,12 @@ internal static async Task ValidateOpenApiDocument(string openapi, LogLevel logl } } - if (document.Workspace == null) { - var statsVisitor = new StatsVisitor(); - var walker = new OpenApiWalker(statsVisitor); - walker.Walk(document); - Console.WriteLine(statsVisitor.GetStatisticsReport()); - } - else - { - foreach (var memberDocument in document.Workspace.Documents) - { - Console.WriteLine("Stats for " + memberDocument.Info.Title); - var statsVisitor = new StatsVisitor(); - var walker = new OpenApiWalker(statsVisitor); - walker.Walk(memberDocument); - Console.WriteLine(statsVisitor.GetStatisticsReport()); - } - } + var statsVisitor = new StatsVisitor(); + var walker = new OpenApiWalker(statsVisitor); + walker.Walk(document); -<<<<<<< HEAD - -======= logger.LogTrace("Finished walking through the OpenApi document. Generating a statistics report.."); Console.WriteLine(statsVisitor.GetStatisticsReport()); ->>>>>>> origin/vnext } private static OpenApiFormat GetOpenApiFormat(string input, ILogger logger) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index c078d7ba6..95e6f63f2 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -51,27 +51,6 @@ static async Task Main(string[] args) var validateCommand = new Command("validate") { -<<<<<<< HEAD - new Option("--input", "Input OpenAPI description file path or URL", typeof(string) ), - new Option("--resolveExternal","Resolve external $refs", typeof(bool)) - }; - validateCommand.Handler = CommandHandler.Create(OpenApiService.ValidateOpenApiDocument); - - var transformCommand = new Command("transform") - { - new Option("--input", "Input OpenAPI description file path or URL", typeof(string) ), - new Option("--output","Output OpenAPI description file", typeof(FileInfo), arity: ArgumentArity.ZeroOrOne), - new Option("--version", "OpenAPI specification version", typeof(OpenApiSpecVersion)), - new Option("--format", "File format",typeof(OpenApiFormat) ), - new Option("--inlineExternal", "Inline external $ref instances", typeof(bool) ), - new Option("--inlineLocal", "Inline local $ref instances", typeof(bool) ), - new Option("--filterByOperationIds", "Filters OpenApiDocument by OperationId(s) provided", typeof(string)), - new Option("--filterByTags", "Filters OpenApiDocument by Tag(s) provided", typeof(string)), - new Option("--filterByCollection", "Filters OpenApiDocument by Postman collection provided", typeof(string)) - }; - transformCommand.Handler = CommandHandler.Create( - OpenApiService.ProcessOpenApiDocument); -======= descriptionOption, logLevelOption }; @@ -95,7 +74,6 @@ static async Task Main(string[] args) transformCommand.SetHandler ( OpenApiService.ProcessOpenApiDocument, descriptionOption, csdlOption, outputOption, versionOption, formatOption, logLevelOption, inlineOption, resolveExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption); ->>>>>>> origin/vnext rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); From 403fdbc6ab8bbd0352e07067853e1e6ca085d8cb Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 21 Feb 2022 17:45:43 -0500 Subject: [PATCH 008/855] Updated referencable items to use GetEffective when inlining --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 20 +++--- src/Microsoft.OpenApi.Hidi/Program.cs | 14 ++--- .../Models/OpenApiCallback.cs | 34 ++++++++-- .../Models/OpenApiExample.cs | 33 ++++++++-- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 53 +++++++++++++--- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 35 +++++++++-- .../Models/OpenApiParameter.cs | 62 +++++++++++++------ .../Models/OpenApiPathItem.cs | 50 ++++++++++++--- .../Models/OpenApiRequestBody.cs | 31 +++++++++- .../Models/OpenApiResponse.cs | 51 ++++++++++++--- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 18 +++++- 11 files changed, 321 insertions(+), 80 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 632042f38..e813e72a4 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -28,15 +28,15 @@ namespace Microsoft.OpenApi.Hidi { public class OpenApiService { - public static async void ProcessOpenApiDocument( + public static async Task ProcessOpenApiDocument( string openapi, string csdl, FileInfo output, OpenApiSpecVersion? version, OpenApiFormat? format, LogLevel loglevel, - bool inline, - bool resolveexternal, + bool inlineLocal, + bool inlineExternal, string filterbyoperationids, string filterbytags, string filterbycollection @@ -104,8 +104,9 @@ string filterbycollection logger.LogTrace("Parsing OpenApi file"); var result = new OpenApiStreamReader(new OpenApiReaderSettings { - ReferenceResolution = resolveexternal ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, - RuleSet = ValidationRuleSet.GetDefaultRuleSet() + RuleSet = ValidationRuleSet.GetDefaultRuleSet(), + LoadExternalRefs = inlineExternal, + BaseUrl = openapi.StartsWith("http") ? new Uri(openapi) : new Uri("file:" + new FileInfo(openapi).DirectoryName + "\\") } ).ReadAsync(stream).GetAwaiter().GetResult(); @@ -249,7 +250,7 @@ private static async Task GetStream(string input, ILogger logger) stopwatch.Start(); Stream stream; - if (input.Scheme == "http" || input.Scheme == "https") + if (input.StartsWith("http")) { try { @@ -269,7 +270,7 @@ private static async Task GetStream(string input, ILogger logger) return null; } } - else if (input.Scheme == "file") + else { try { @@ -336,11 +337,10 @@ internal static async Task ValidateOpenApiDocument(string openapi, LogLevel logl OpenApiDocument document; logger.LogTrace("Parsing the OpenApi file"); - document = new OpenApiStreamReader(new OpenApiReaderSettings + var result = await new OpenApiStreamReader(new OpenApiReaderSettings { - ReferenceResolution = resolveExternal == true ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences, RuleSet = ValidationRuleSet.GetDefaultRuleSet(), - BaseUrl = new Uri(inputUrl.AbsoluteUri) + BaseUrl = new Uri(openapi) } ).ReadAsync(stream); diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 95e6f63f2..309fa5360 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -43,11 +43,11 @@ static async Task Main(string[] args) var filterByCollectionOption = new Option("--filter-by-collection", "Filters OpenApiDocument by Postman collection provided"); filterByCollectionOption.AddAlias("-c"); - var inlineOption = new Option("--inline", "Inline $ref instances"); - inlineOption.AddAlias("-i"); + var inlineLocalOption = new Option("--inlineLocal", "Inline local $ref instances"); + inlineLocalOption.AddAlias("-il"); - var resolveExternalOption = new Option("--resolve-external", "Resolve external $refs"); - resolveExternalOption.AddAlias("-ex"); + var inlineExternalOption = new Option("--inlineExternal", "Inline external $ref instances"); + inlineExternalOption.AddAlias("-ie"); var validateCommand = new Command("validate") { @@ -68,12 +68,12 @@ static async Task Main(string[] args) filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption, - inlineOption, - resolveExternalOption, + inlineLocalOption, + inlineExternalOption }; transformCommand.SetHandler ( - OpenApiService.ProcessOpenApiDocument, descriptionOption, csdlOption, outputOption, versionOption, formatOption, logLevelOption, inlineOption, resolveExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption); + OpenApiService.ProcessOpenApiDocument, descriptionOption, csdlOption, outputOption, versionOption, formatOption, logLevelOption, inlineLocalOption, inlineExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption); rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index 644334ab4..bd8bfce76 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -70,15 +70,41 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV3(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } + target.SerializeAsV3WithoutReference(writer); + } - SerializeAsV3WithoutReference(writer); + /// + /// Returns an effective OpenApiCallback object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiCallback + public OpenApiCallback GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } } + /// /// Serialize to OpenAPI V3 document without using reference. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 787c2972e..f7371f55c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -64,13 +64,38 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV3(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } + target.SerializeAsV3WithoutReference(writer); + } - SerializeAsV3WithoutReference(writer); + /// + /// Returns an effective OpenApiExample object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiExample + public OpenApiExample GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index d94681a1c..791af1d70 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -96,15 +96,42 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV3(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } + target.SerializeAsV3WithoutReference(writer); - SerializeAsV3WithoutReference(writer); } + /// + /// Returns an effective OpenApiHeader object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiHeader + public OpenApiHeader GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } + } + + /// /// Serialize to OpenAPI V3 document without using reference. /// @@ -161,13 +188,21 @@ public void SerializeAsV2(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV2(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } - - SerializeAsV2WithoutReference(writer); + target.SerializeAsV2WithoutReference(writer); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index 82502f14a..1d1488ca6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -71,15 +71,42 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV3(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } + target.SerializeAsV3WithoutReference(writer); - SerializeAsV3WithoutReference(writer); } + /// + /// Returns an effective OpenApiLink object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiLink + public OpenApiLink GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } + } + + /// /// Serialize to OpenAPI V3 document without using reference. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index ebc70465a..12f37f61a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.Collections.Generic; +using System.Runtime; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; @@ -145,13 +146,39 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV3(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = this.GetEffective(Reference.HostDocument); + } } - SerializeAsV3WithoutReference(writer); + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiParameter object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiParameter + public OpenApiParameter GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } } /// @@ -216,13 +243,21 @@ public void SerializeAsV2(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + if (Reference != null) { - Reference.SerializeAsV2(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + target = this.GetEffective(Reference.HostDocument); + } } - SerializeAsV2WithoutReference(writer); + target.SerializeAsV2WithoutReference(writer); } /// @@ -333,17 +368,6 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) writer.WriteEndObject(); } - public OpenApiParameter GetEffective(OpenApiDocument doc) - { - if (this.Reference != null) - { - return doc.ResolveReferenceTo(this.Reference); - } - else - { - return this; - } - } } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index 78e97ec18..a8fc27c27 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -74,15 +74,38 @@ public void SerializeAsV3(IOpenApiWriter writer) { throw Error.ArgumentNull(nameof(writer)); } + var target = this; - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + if (Reference != null) { - Reference.SerializeAsV3(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } + target.SerializeAsV3WithoutReference(writer); + } - SerializeAsV3WithoutReference(writer); - + /// + /// Returns an effective OpenApiPathItem object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiPathItem + public OpenApiPathItem GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } } /// @@ -95,13 +118,22 @@ public void SerializeAsV2(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV2(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + target = this.GetEffective(Reference.HostDocument); + } } - SerializeAsV2WithoutReference(writer); + target.SerializeAsV2WithoutReference(writer); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index d6308efcf..353e294f2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -55,13 +55,38 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } + var target = this; + if (Reference != null) { - Reference.SerializeAsV3(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } + target.SerializeAsV3WithoutReference(writer); + } - SerializeAsV3WithoutReference(writer); + /// + /// Returns an effective OpenApiRequestBody object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiRequestBody + public OpenApiRequestBody GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index ef30602b9..faf279013 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -61,13 +61,38 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV3(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } + target.SerializeAsV3WithoutReference(writer); + } - SerializeAsV3WithoutReference(writer); + /// + /// Returns an effective OpenApiRequestBody object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiResponse + public OpenApiResponse GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } } /// @@ -105,13 +130,21 @@ public void SerializeAsV2(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - if (Reference != null && !writer.GetSettings().ShouldInlineReference(Reference)) + var target = this; + + if (Reference != null) { - Reference.SerializeAsV2(writer); - return; + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } } - - SerializeAsV2WithoutReference(writer); + target.SerializeAsV2WithoutReference(writer); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index c98c32c17..74aed7da1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -451,14 +451,23 @@ internal void SerializeAsV2( throw Error.ArgumentNull(nameof(writer)); } + var settings = writer.GetSettings(); + var target = this; + if (Reference != null) { - var settings = writer.GetSettings(); if (!settings.ShouldInlineReference(Reference)) { Reference.SerializeAsV2(writer); return; } + else + { + if (Reference.IsExternal) // Temporary until v2 + { + target = this.GetEffective(Reference.HostDocument); + } + } // If Loop is detected then just Serialize as a reference. if (!settings.LoopDetector.PushLoop(this)) @@ -475,7 +484,7 @@ internal void SerializeAsV2( parentRequiredProperties = new HashSet(); } - SerializeAsV2WithoutReference(writer, parentRequiredProperties, propertyName); + target.SerializeAsV2WithoutReference(writer, parentRequiredProperties, propertyName); } /// @@ -676,6 +685,11 @@ internal void WriteAsSchemaProperties( writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); } + /// + /// Returns an effective OpenApiSchema object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiSchema public OpenApiSchema GetEffective(OpenApiDocument doc) { if (this.Reference != null) From d7616ee3f5dc44f1dc5957748a96d52ebd6de836 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 21 Feb 2022 22:27:15 -0500 Subject: [PATCH 009/855] Added IEffective interfaces to models that have references --- .../Models/OpenApiCallback.cs | 2 +- .../Models/OpenApiExample.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 2 +- .../Models/OpenApiPathItem.cs | 2 +- .../Models/OpenApiRequestBody.cs | 2 +- .../Models/OpenApiResponse.cs | 2 +- .../PublicApi/PublicApi.approved.txt | 39 ++++++++++++------- 8 files changed, 33 insertions(+), 20 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index bd8bfce76..57aa3c888 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -12,7 +12,7 @@ namespace Microsoft.OpenApi.Models /// /// Callback Object: A map of possible out-of band callbacks related to the parent operation. /// - public class OpenApiCallback : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible + public class OpenApiCallback : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible, IEffective { /// /// A Path Item Object used to define a callback request and expected responses. diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index f7371f55c..d4c268584 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Models /// /// Example Object. /// - public class OpenApiExample : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible + public class OpenApiExample : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible, IEffective { /// /// Short description for the example. diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index 791af1d70..e8576a0ca 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Models /// Header Object. /// The Header Object follows the structure of the Parameter Object. /// - public class OpenApiHeader : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible + public class OpenApiHeader : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible, IEffective { /// /// Indicates if object is populated with data or is just a reference to the data diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index 1d1488ca6..f5acb0d3f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Models /// /// Link Object. /// - public class OpenApiLink : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible + public class OpenApiLink : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible, IEffective { /// /// A relative or absolute reference to an OAS operation. diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index a8fc27c27..375f1f034 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Models /// /// Path Item Object: to describe the operations available on a single path. /// - public class OpenApiPathItem : IOpenApiSerializable, IOpenApiExtensible, IOpenApiReferenceable + public class OpenApiPathItem : IOpenApiSerializable, IOpenApiExtensible, IOpenApiReferenceable, IEffective { /// /// An optional, string summary, intended to apply to all operations in this path. diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 353e294f2..8a65f1fde 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Models /// /// Request Body Object /// - public class OpenApiRequestBody : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible + public class OpenApiRequestBody : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible, IEffective { /// /// Indicates if object is populated with data or is just a reference to the data diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index faf279013..0a31ca0a4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Models /// /// Response object. /// - public class OpenApiResponse : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible + public class OpenApiResponse : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible, IEffective { /// /// REQUIRED. A short description of the response. diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 484d64dba..43900109b 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -271,6 +271,11 @@ namespace Microsoft.OpenApi.Extensions } namespace Microsoft.OpenApi.Interfaces { + public interface IEffective + where T : class, Microsoft.OpenApi.Interfaces.IOpenApiElement + { + T GetEffective(Microsoft.OpenApi.Models.OpenApiDocument document); + } public interface IOpenApiElement { } public interface IOpenApiExtensible : Microsoft.OpenApi.Interfaces.IOpenApiElement { @@ -315,7 +320,7 @@ namespace Microsoft.OpenApi } namespace Microsoft.OpenApi.Models { - public class OpenApiCallback : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiCallback : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiCallback() { } public System.Collections.Generic.IDictionary Extensions { get; set; } @@ -323,6 +328,7 @@ namespace Microsoft.OpenApi.Models public Microsoft.OpenApi.Models.OpenApiReference Reference { get; set; } public bool UnresolvedReference { get; set; } public void AddPathItem(Microsoft.OpenApi.Expressions.RuntimeExpression expression, Microsoft.OpenApi.Models.OpenApiPathItem pathItem) { } + public Microsoft.OpenApi.Models.OpenApiCallback GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -500,9 +506,7 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IList Servers { get; set; } public System.Collections.Generic.IList Tags { get; set; } public Microsoft.OpenApi.Services.OpenApiWorkspace Workspace { get; set; } - public Microsoft.OpenApi.Interfaces.IOpenApiReferenceable ResolveReference(Microsoft.OpenApi.Models.OpenApiReference reference) { } - public Microsoft.OpenApi.Interfaces.IOpenApiReferenceable ResolveReference(Microsoft.OpenApi.Models.OpenApiReference reference, bool useExternal) { } - public System.Collections.Generic.IEnumerable ResolveReferences(bool useExternal = false) { } + public System.Collections.Generic.IEnumerable ResolveReferences() { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } } @@ -526,7 +530,7 @@ namespace Microsoft.OpenApi.Models public string Pointer { get; set; } public override string ToString() { } } - public class OpenApiExample : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiExample : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiExample() { } public string Description { get; set; } @@ -536,6 +540,7 @@ namespace Microsoft.OpenApi.Models public string Summary { get; set; } public bool UnresolvedReference { get; set; } public Microsoft.OpenApi.Any.IOpenApiAny Value { get; set; } + public Microsoft.OpenApi.Models.OpenApiExample GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -558,7 +563,7 @@ namespace Microsoft.OpenApi.Models public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } } - public class OpenApiHeader : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiHeader : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiHeader() { } public bool AllowEmptyValue { get; set; } @@ -575,6 +580,7 @@ namespace Microsoft.OpenApi.Models public Microsoft.OpenApi.Models.OpenApiSchema Schema { get; set; } public Microsoft.OpenApi.Models.ParameterStyle? Style { get; set; } public bool UnresolvedReference { get; set; } + public Microsoft.OpenApi.Models.OpenApiHeader GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -602,7 +608,7 @@ namespace Microsoft.OpenApi.Models public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } } - public class OpenApiLink : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiLink : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiLink() { } public string Description { get; set; } @@ -614,6 +620,7 @@ namespace Microsoft.OpenApi.Models public Microsoft.OpenApi.Models.RuntimeExpressionAnyWrapper RequestBody { get; set; } public Microsoft.OpenApi.Models.OpenApiServer Server { get; set; } public bool UnresolvedReference { get; set; } + public Microsoft.OpenApi.Models.OpenApiLink GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -672,7 +679,7 @@ namespace Microsoft.OpenApi.Models public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } } - public class OpenApiParameter : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiParameter : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiParameter() { } public bool AllowEmptyValue { get; set; } @@ -691,12 +698,13 @@ namespace Microsoft.OpenApi.Models public Microsoft.OpenApi.Models.OpenApiSchema Schema { get; set; } public Microsoft.OpenApi.Models.ParameterStyle? Style { get; set; } public bool UnresolvedReference { get; set; } + public Microsoft.OpenApi.Models.OpenApiParameter GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } } - public class OpenApiPathItem : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiPathItem : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiPathItem() { } public string Description { get; set; } @@ -708,6 +716,7 @@ namespace Microsoft.OpenApi.Models public string Summary { get; set; } public bool UnresolvedReference { get; set; } public void AddOperation(Microsoft.OpenApi.Models.OperationType operationType, Microsoft.OpenApi.Models.OpenApiOperation operation) { } + public Microsoft.OpenApi.Models.OpenApiPathItem GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -721,6 +730,7 @@ namespace Microsoft.OpenApi.Models { public OpenApiReference() { } public string ExternalResource { get; set; } + public Microsoft.OpenApi.Models.OpenApiDocument HostDocument { get; set; } public string Id { get; set; } public bool IsExternal { get; } public bool IsLocal { get; } @@ -730,7 +740,7 @@ namespace Microsoft.OpenApi.Models public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } } - public class OpenApiRequestBody : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiRequestBody : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiRequestBody() { } public System.Collections.Generic.IDictionary Content { get; set; } @@ -739,12 +749,13 @@ namespace Microsoft.OpenApi.Models public Microsoft.OpenApi.Models.OpenApiReference Reference { get; set; } public bool Required { get; set; } public bool UnresolvedReference { get; set; } + public Microsoft.OpenApi.Models.OpenApiRequestBody GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } } - public class OpenApiResponse : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiResponse : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiResponse() { } public System.Collections.Generic.IDictionary Content { get; set; } @@ -754,6 +765,7 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IDictionary Links { get; set; } public Microsoft.OpenApi.Models.OpenApiReference Reference { get; set; } public bool UnresolvedReference { get; set; } + public Microsoft.OpenApi.Models.OpenApiResponse GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -763,7 +775,7 @@ namespace Microsoft.OpenApi.Models { public OpenApiResponses() { } } - public class OpenApiSchema : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable + public class OpenApiSchema : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiSchema() { } public Microsoft.OpenApi.Models.OpenApiSchema AdditionalProperties { get; set; } @@ -805,6 +817,7 @@ namespace Microsoft.OpenApi.Models public bool UnresolvedReference { get; set; } public bool WriteOnly { get; set; } public Microsoft.OpenApi.Models.OpenApiXml Xml { get; set; } + public Microsoft.OpenApi.Models.OpenApiSchema GetEffective(Microsoft.OpenApi.Models.OpenApiDocument doc) { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV2WithoutReference(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -1206,7 +1219,7 @@ namespace Microsoft.OpenApi.Validations.Rules public static Microsoft.OpenApi.Validations.ValidationRule ResponsesMustBeIdentifiedByDefaultOrStatusCode { get; } public static Microsoft.OpenApi.Validations.ValidationRule ResponsesMustContainAtLeastOneResponse { get; } } - [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.All, AllowMultiple=false, Inherited=false)] + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public class OpenApiRuleAttribute : System.Attribute { public OpenApiRuleAttribute() { } From e34a4f9851b0fdc6bd049d600a20ff5a15ebe30b Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 21 Feb 2022 22:34:19 -0500 Subject: [PATCH 010/855] Removed redundant using --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index e813e72a4..fb785f9e1 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -12,7 +12,6 @@ using System.Text; using System.Threading.Tasks; using System.Text.Json; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using System.Xml.Linq; using Microsoft.OData.Edm.Csdl; From 194576e7e3df29fb387b51fd51aa4c9bd33d99ae Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 10 Mar 2022 22:37:35 +0300 Subject: [PATCH 011/855] Fix exception thrown when OpenSpecVersion is null --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index ba8b84e0e..357152343 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.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; @@ -113,7 +113,7 @@ CancellationToken cancellationToken } openApiFormat = format ?? GetOpenApiFormat(openapi, logger); - openApiVersion = version == null ? TryParseOpenApiSpecVersion(version) : result.OpenApiDiagnostic.SpecificationVersion; + openApiVersion = version == null ? result.OpenApiDiagnostic.SpecificationVersion : TryParseOpenApiSpecVersion(version); } Func predicate; From af25fe44d1bcffc8a6e544d8d9c30017a0de3cc5 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 10 Mar 2022 22:38:24 +0300 Subject: [PATCH 012/855] Add recursive solution for nested collection item object --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 41 ++++++++++++++------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 357152343..129dfa54b 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.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; @@ -301,24 +301,41 @@ public static Dictionary> ParseJsonCollectionFile(Stream st logger.LogTrace("Parsing the json collection file into a JsonDocument"); using var document = JsonDocument.Parse(stream); var root = document.RootElement; - var itemElement = root.GetProperty("item"); - foreach (var requestObject in itemElement.EnumerateArray().Select(item => item.GetProperty("request"))) - { - // Fetch list of methods and urls from collection, store them in a dictionary - var path = requestObject.GetProperty("url").GetProperty("raw").ToString(); - var method = requestObject.GetProperty("method").ToString(); - if (!requestUrls.ContainsKey(path)) + requestUrls = Enumerate(root, requestUrls); + + logger.LogTrace("Finished fetching the list of paths and Http methods defined in the Postman collection."); + return requestUrls; + } + + private static Dictionary> Enumerate(JsonElement itemElement, Dictionary> paths) + { + var itemsArray = itemElement.GetProperty("item"); + + foreach (var item in itemsArray.EnumerateArray()) + { + if (item.TryGetProperty("request", out var request)) { - requestUrls.Add(path, new List { method }); + // Fetch list of methods and urls from collection, store them in a dictionary + var path = request.GetProperty("url").GetProperty("raw").ToString(); + var method = request.GetProperty("method").ToString(); + + if (!paths.ContainsKey(path)) + { + paths.Add(path, new List { method }); + } + else + { + paths[path].Add(method); + } } else { - requestUrls[path].Add(method); + Enumerate(item, paths); } } - logger.LogTrace("Finished fetching the list of paths and Http methods defined in the Postman collection."); - return requestUrls; + + return paths; } internal static async Task ValidateOpenApiDocument(string openapi, LogLevel loglevel, CancellationToken cancellationToken) From bc87d1ef003040168fb104c1344886df6aa5ebbc Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 10 Mar 2022 23:23:15 +0300 Subject: [PATCH 013/855] Code refactoring --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 32 ++++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 129dfa54b..eebc5b5dd 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -314,20 +314,26 @@ private static Dictionary> Enumerate(JsonElement itemElemen foreach (var item in itemsArray.EnumerateArray()) { - if (item.TryGetProperty("request", out var request)) + if(item.ValueKind == JsonValueKind.Object) { - // Fetch list of methods and urls from collection, store them in a dictionary - var path = request.GetProperty("url").GetProperty("raw").ToString(); - var method = request.GetProperty("method").ToString(); - - if (!paths.ContainsKey(path)) - { - paths.Add(path, new List { method }); - } - else - { - paths[path].Add(method); - } + if(item.TryGetProperty("request", out var request)) + { + // Fetch list of methods and urls from collection, store them in a dictionary + var path = request.GetProperty("url").GetProperty("raw").ToString(); + var method = request.GetProperty("method").ToString(); + if (!paths.ContainsKey(path)) + { + paths.Add(path, new List { method }); + } + else + { + paths[path].Add(method); + } + } + else + { + Enumerate(item, paths); + } } else { From c666c4ae4b1034b73ef602152bbcb87263bd2099 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 10 Mar 2022 23:23:51 +0300 Subject: [PATCH 014/855] Add nested sample collection file and copy it to output directory --- .../Microsoft.OpenApi.Tests.csproj | 3 + .../UtilityFiles/postmanCollection_ver3.json | 1382 +++++++++++++++++ 2 files changed, 1385 insertions(+) create mode 100644 test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver3.json diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 360eeea92..eea157d2e 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -44,6 +44,9 @@ Always + + Always + Always diff --git a/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver3.json b/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver3.json new file mode 100644 index 000000000..2c7637ed7 --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver3.json @@ -0,0 +1,1382 @@ +{ + "info": { + "_postman_id": "6281bdba-62b8-2276-a5d6-268e87f48c89", + "name": "Graph-Collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "admin", + "item": [ + { + "name": "/admin", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin" + ] + } + } + }, + { + "name": "/admin", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}", + "issues" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}", + "issues" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues/{serviceHealthIssue-id}", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues/{serviceHealthIssue-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}", + "issues", + "{serviceHealthIssue-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues/{serviceHealthIssue-id}", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues/{serviceHealthIssue-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}", + "issues", + "{serviceHealthIssue-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues/{serviceHealthIssue-id}", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues/{serviceHealthIssue-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}", + "issues", + "{serviceHealthIssue-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues/{serviceHealthIssue-id}/microsoft.graph.incidentReport()", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/healthOverviews/{serviceHealth-id}/issues/{serviceHealthIssue-id}/microsoft.graph.incidentReport()", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "healthOverviews", + "{serviceHealth-id}", + "issues", + "{serviceHealthIssue-id}", + "microsoft.graph.incidentReport()" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/issues", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/issues", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "issues" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/issues", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/issues", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "issues" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/issues/{serviceHealthIssue-id}", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/issues/{serviceHealthIssue-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "issues", + "{serviceHealthIssue-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/issues/{serviceHealthIssue-id}", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/issues/{serviceHealthIssue-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "issues", + "{serviceHealthIssue-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/issues/{serviceHealthIssue-id}", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/issues/{serviceHealthIssue-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "issues", + "{serviceHealthIssue-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/issues/{serviceHealthIssue-id}/microsoft.graph.incidentReport()", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/issues/{serviceHealthIssue-id}/microsoft.graph.incidentReport()", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "issues", + "{serviceHealthIssue-id}", + "microsoft.graph.incidentReport()" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/microsoft.graph.archive", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/microsoft.graph.archive", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "microsoft.graph.archive" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/microsoft.graph.favorite", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/microsoft.graph.favorite", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "microsoft.graph.favorite" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/microsoft.graph.markRead", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/microsoft.graph.markRead", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "microsoft.graph.markRead" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/microsoft.graph.markUnread", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/microsoft.graph.markUnread", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "microsoft.graph.markUnread" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/microsoft.graph.unarchive", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/microsoft.graph.unarchive", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "microsoft.graph.unarchive" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/microsoft.graph.unfavorite", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/microsoft.graph.unfavorite", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "microsoft.graph.unfavorite" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachments" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachments" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachments", + "{serviceAnnouncementAttachment-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachments", + "{serviceAnnouncementAttachment-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachments", + "{serviceAnnouncementAttachment-id}" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}/content", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}/content", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachments", + "{serviceAnnouncementAttachment-id}", + "content" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}/content", + "request": { + "method": "PUT", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachments/{serviceAnnouncementAttachment-id}/content", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachments", + "{serviceAnnouncementAttachment-id}", + "content" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachmentsArchive", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachmentsArchive", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachmentsArchive" + ] + } + } + }, + { + "name": "/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachmentsArchive", + "request": { + "method": "PUT", + "url": { + "raw": "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/{serviceUpdateMessage-id}/attachmentsArchive", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "admin", + "serviceAnnouncement", + "messages", + "{serviceUpdateMessage-id}", + "attachmentsArchive" + ] + } + } + } + ] + }, + { + "name": "agreementAcceptances", + "item": [ + { + "name": "/agreementAcceptances", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/agreementAcceptances", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "agreementAcceptances" + ] + } + } + }, + { + "name": "/agreementAcceptances", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/agreementAcceptances", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "agreementAcceptances" + ] + } + } + }, + { + "name": "/agreementAcceptances/{agreementAcceptance-id}", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/agreementAcceptances/{agreementAcceptance-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "agreementAcceptances", + "{agreementAcceptance-id}" + ] + } + } + }, + { + "name": "/agreementAcceptances/{agreementAcceptance-id}", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/agreementAcceptances/{agreementAcceptance-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "agreementAcceptances", + "{agreementAcceptance-id}" + ] + } + } + }, + { + "name": "/agreementAcceptances/{agreementAcceptance-id}", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/agreementAcceptances/{agreementAcceptance-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "agreementAcceptances", + "{agreementAcceptance-id}" + ] + } + } + } + ] + }, + { + "name": "appCatalogs", + "item": [ + { + "name": "/appCatalogs", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs" + ] + } + } + }, + { + "name": "/appCatalogs", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}", + "appDefinitions" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}", + "appDefinitions" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}", + "appDefinitions", + "{teamsAppDefinition-id}" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}", + "appDefinitions", + "{teamsAppDefinition-id}" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}", + "appDefinitions", + "{teamsAppDefinition-id}" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}/bot", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}/bot", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}", + "appDefinitions", + "{teamsAppDefinition-id}", + "bot" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}/bot", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}/bot", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}", + "appDefinitions", + "{teamsAppDefinition-id}", + "bot" + ] + } + } + }, + { + "name": "/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}/bot", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsApp-id}/appDefinitions/{teamsAppDefinition-id}/bot", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs", + "teamsApps", + "{teamsApp-id}", + "appDefinitions", + "{teamsAppDefinition-id}", + "bot" + ] + } + } + } + ] + } + ] +} \ No newline at end of file From 2a8996d414e3f546c5c885441174dc1a6b223e4f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 10 Mar 2022 23:24:01 +0300 Subject: [PATCH 015/855] Add unit test --- .../Services/OpenApiFilterServiceTests.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs index 78f8ec048..28c259fc6 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs @@ -69,6 +69,23 @@ public void ReturnFilteredOpenApiDocumentBasedOnPostmanCollection() Assert.Equal(3, subsetOpenApiDocument.Paths.Count); } + [Fact] + public void ShouldParseNestedPostmanCollection() + { + // Arrange + var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UtilityFiles\\postmanCollection_ver3.json"); + var fileInput = new FileInfo(filePath); + var stream = fileInput.OpenRead(); + + // Act + var requestUrls = OpenApiService.ParseJsonCollectionFile(stream, _logger); + var pathCount = requestUrls.Count; + + // Assert + Assert.NotNull(requestUrls); + Assert.Equal(30, pathCount); + } + [Fact] public void ThrowsExceptionWhenUrlsInCollectionAreMissingFromSourceDocument() { From 3350d86bab72a22bd84372ea2ccfbe82a2575f7d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 14 Mar 2022 09:37:54 +0300 Subject: [PATCH 016/855] Rename method --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index eebc5b5dd..d68daea80 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -302,13 +302,13 @@ public static Dictionary> ParseJsonCollectionFile(Stream st using var document = JsonDocument.Parse(stream); var root = document.RootElement; - requestUrls = Enumerate(root, requestUrls); - + requestUrls = EnumerateJsonDocument(root, requestUrls); logger.LogTrace("Finished fetching the list of paths and Http methods defined in the Postman collection."); + return requestUrls; } - private static Dictionary> Enumerate(JsonElement itemElement, Dictionary> paths) + private static Dictionary> EnumerateJsonDocument(JsonElement itemElement, Dictionary> paths) { var itemsArray = itemElement.GetProperty("item"); @@ -332,12 +332,12 @@ private static Dictionary> Enumerate(JsonElement itemElemen } else { - Enumerate(item, paths); + EnumerateJsonDocument(item, paths); } } else { - Enumerate(item, paths); + EnumerateJsonDocument(item, paths); } } From 3445c1d3199ebd8dc598d8d08a05f27904b4faca Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 15 Mar 2022 11:32:05 +0300 Subject: [PATCH 017/855] Log warning to console if url in collection isn't in the input OpenApi doc and continue processing the rest of the urls and add unit test --- .../Services/OpenApiFilterService.cs | 1 + .../Microsoft.OpenApi.Tests.csproj | 3 + .../Services/OpenApiFilterServiceTests.cs | 22 +++ .../UtilityFiles/postmanCollection_ver4.json | 145 ++++++++++++++++++ 4 files changed, 171 insertions(+) create mode 100644 test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver4.json diff --git a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs index 7b9111e4d..57c5fef09 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs @@ -81,6 +81,7 @@ public static class OpenApiFilterService var openApiOperations = GetOpenApiOperations(rootNode, url, apiVersion); if (openApiOperations == null) { + Console.WriteLine($"The url {url} could not be found in the OpenApi description"); continue; } diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index eea157d2e..a187a2887 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -47,6 +47,9 @@ Always + + Always + Always diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs index 28c259fc6..29cb684d2 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs @@ -103,6 +103,28 @@ public void ThrowsExceptionWhenUrlsInCollectionAreMissingFromSourceDocument() Assert.Equal("The urls in the Postman collection supplied could not be found.", message); } + [Fact] + public void ContinueProcessingWhenUrlsInCollectionAreMissingFromSourceDocument() + { + // Arrange + var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UtilityFiles\\postmanCollection_ver4.json"); + var fileInput = new FileInfo(filePath); + var stream = fileInput.OpenRead(); + + // Act + var requestUrls = OpenApiService.ParseJsonCollectionFile(stream, _logger); + var pathCount = requestUrls.Count; + var predicate = OpenApiFilterService.CreatePredicate(requestUrls: requestUrls, source: _openApiDocumentMock); + var subsetOpenApiDocument = OpenApiFilterService.CreateFilteredDocument(_openApiDocumentMock, predicate); + var subsetPathCount = subsetOpenApiDocument.Paths.Count; + + // Assert + Assert.NotNull(subsetOpenApiDocument); + Assert.NotEmpty(subsetOpenApiDocument.Paths); + Assert.Equal(2, subsetPathCount); + Assert.NotEqual(pathCount, subsetPathCount); + } + [Fact] public void ThrowsInvalidOperationExceptionInCreatePredicateWhenInvalidArgumentsArePassed() { diff --git a/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver4.json b/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver4.json new file mode 100644 index 000000000..edafeb0bd --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver4.json @@ -0,0 +1,145 @@ +{ + "info": { + "_postman_id": "43402ca3-f018-7c9b-2315-f176d9b171a3", + "name": "Graph-Collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "users-GET", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/users", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "users" + ] + } + } + }, + { + "name": "users-POST", + "request": { + "method": "POST", + "url": { + "raw": "https://graph.microsoft.com/v1.0/users", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "users" + ] + } + } + }, + { + "name": "/appCatalogs", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/appCatalogs", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "appCatalogs" + ] + } + } + }, + { + "name": "/agreementAcceptances", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/agreementAcceptances", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "agreementAcceptances" + ] + } + } + }, + { + "name": "{user-id}-GET", + "request": { + "method": "GET", + "url": { + "raw": "https://graph.microsoft.com/v1.0/users/{user-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "users", + "{user-id}" + ] + } + } + }, + { + "name": "{user-id}-PATCH", + "request": { + "method": "PATCH", + "url": { + "raw": "https://graph.microsoft.com/v1.0/users/{user-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "users", + "{user-id}" + ] + } + } + }, + { + "name": "{user-id}-DELETE", + "request": { + "method": "DELETE", + "url": { + "raw": "https://graph.microsoft.com/v1.0/users/{user-id}", + "protocol": "https", + "host": [ + "graph", + "microsoft", + "com" + ], + "path": [ + "v1.0", + "users", + "{user-id}" + ] + } + } + } + ] +} \ No newline at end of file From 19a9c73da2abc13d237d00fa09e7f82656336e84 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 16 Mar 2022 18:24:41 +0300 Subject: [PATCH 018/855] Update powershell script to fetch Hidi version number and use the output variables in the release notes --- .azure-pipelines/ci-build.yml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index a4af01161..3d21b83ee 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -270,11 +270,11 @@ stages: inputs: source: current - pwsh: | - $artifactMainDirectory = Get-ChildItem -Filter Microsoft.OpenApi.Hidi-* -Directory -Recurse | select -First 1 - $artifactName = $artifactMainDirectory.Name -replace "Microsoft.OpenApi.Hidi-", "" - #Set Variable $artifactName - Write-Host "##vso[task.setvariable variable=artifactName; isSecret=false; isOutput=true;]$artifactName" - Write-Host "##vso[task.setvariable variable=artifactMainDirectory; isSecret=false; isOutput=true;]$artifactMainDirectory" + $artifactName = Get-ChildItem -Path $(Pipeline.Workspace) -Filter Microsoft.OpenApi.Hidi-* -recurse | select -First 1 + $artifactVersion= $artifactName -replace "Microsoft.OpenApi.Hidi-", "" + #Set Variable $artifactName and $artifactVersion + Write-Host "##vso[task.setvariable variable=artifactVersion; isSecret=false; isOutput=true]$artifactVersion" + Write-Host "##vso[task.setvariable variable=artifactName; isSecret=false; isOutput=true]$artifactName.FullName" displayName: 'Fetch Artifact Name' - task: NuGetCommand@2 @@ -289,10 +289,10 @@ stages: inputs: gitHubConnection: 'Github-MaggieKimani1' tagSource: userSpecifiedTag - tag: '$(artifactName)' + tag: '$(artifactVersion)' title: '$(artifactName)' releaseNotesSource: inline - assets: '$(artifactMainDirectory)\**\*.exe' + assets: '$(Pipeline.Workspace)\**\*.exe' changeLogType: issueBased - deployment: deploy_lib From 74b8b4beb31634e5752def9c9394faef2f2ba7b2 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 16 Mar 2022 18:35:41 +0300 Subject: [PATCH 019/855] Remove whitespace --- .azure-pipelines/ci-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 3d21b83ee..31af5bd24 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -271,7 +271,7 @@ stages: source: current - pwsh: | $artifactName = Get-ChildItem -Path $(Pipeline.Workspace) -Filter Microsoft.OpenApi.Hidi-* -recurse | select -First 1 - $artifactVersion= $artifactName -replace "Microsoft.OpenApi.Hidi-", "" + $artifactVersion= $artifactName -replace "Microsoft.OpenApi.Hidi-", "" #Set Variable $artifactName and $artifactVersion Write-Host "##vso[task.setvariable variable=artifactVersion; isSecret=false; isOutput=true]$artifactVersion" Write-Host "##vso[task.setvariable variable=artifactName; isSecret=false; isOutput=true]$artifactName.FullName" From 13812b153a355faa230292f443a5eb432c6eecfd Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Wed, 23 Mar 2022 13:31:56 -0400 Subject: [PATCH 020/855] Added CSDL filter for entitysets and singletons --- src/Microsoft.OpenApi.Hidi/CsdlFilter.xslt | 22 ++++++++++ .../Microsoft.OpenApi.Hidi.csproj | 8 ++++ src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 41 ++++++++++++++++++- src/Microsoft.OpenApi.Hidi/Program.cs | 8 +++- .../Services/OpenApiServiceTests.cs | 2 +- 5 files changed, 76 insertions(+), 5 deletions(-) create mode 100644 src/Microsoft.OpenApi.Hidi/CsdlFilter.xslt diff --git a/src/Microsoft.OpenApi.Hidi/CsdlFilter.xslt b/src/Microsoft.OpenApi.Hidi/CsdlFilter.xslt new file mode 100644 index 000000000..ee3bf0d40 --- /dev/null +++ b/src/Microsoft.OpenApi.Hidi/CsdlFilter.xslt @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index d9a958db9..98def8818 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -31,6 +31,14 @@ true + + + + + + + + diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index c15f77d6f..4b73c13d4 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -24,6 +24,10 @@ using Microsoft.OpenApi.Writers; using static Microsoft.OpenApi.Hidi.OpenApiSpecVersionHelper; using System.Threading; +using System.Xml.Xsl; +using System.Xml; +using System.Runtime.CompilerServices; +using System.Reflection; namespace Microsoft.OpenApi.Hidi { @@ -35,6 +39,7 @@ public class OpenApiService public static async Task TransformOpenApiDocument( string openapi, string csdl, + string csdlFilter, FileInfo output, bool cleanoutput, string? version, @@ -85,6 +90,13 @@ CancellationToken cancellationToken openApiVersion = version != null ? TryParseOpenApiSpecVersion(version) : OpenApiSpecVersion.OpenApi3_0; stream = await GetStream(csdl, logger, cancellationToken); + + if (!string.IsNullOrEmpty(csdlFilter)) + { + XslCompiledTransform transform = GetFilterTransform(); + stream = ApplyFilter(csdl, csdlFilter, transform); + stream.Position = 0; + } document = await ConvertCsdlToOpenApi(stream); stopwatch.Stop(); logger.LogTrace("{timestamp}ms: Generated OpenAPI with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); @@ -210,6 +222,31 @@ CancellationToken cancellationToken } } + private static XslCompiledTransform GetFilterTransform() + { + XslCompiledTransform transform = new(); + Assembly assembly = typeof(OpenApiService).GetTypeInfo().Assembly; + Stream xslt = assembly.GetManifestResourceStream("Microsoft.OpenApi.Hidi.CsdlFilter.xslt"); + transform.Load(new XmlTextReader(new StreamReader(xslt))); + return transform; + } + + private static Stream ApplyFilter(string csdl, string entitySetOrSingleton, XslCompiledTransform transform) + { + Stream stream; + StreamReader inputReader = new(csdl); + XmlReader inputXmlReader = XmlReader.Create(inputReader); + MemoryStream filteredStream = new(); + StreamWriter writer = new(filteredStream); + XsltArgumentList args = new(); + args.AddParam("entitySetOrSingleton", "", entitySetOrSingleton); + transform.Transform(inputXmlReader, args, writer); + stream = filteredStream; + return stream; + } + + + /// /// Implementation of the validate command /// @@ -306,8 +343,8 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl) EnableDiscriminatorValue = false, EnableDerivedTypesReferencesForRequestBody = false, EnableDerivedTypesReferencesForResponses = false, - ShowRootPath = true, - ShowLinks = true + ShowRootPath = false, + ShowLinks = false }; OpenApiDocument document = edmModel.ConvertToOpenApi(settings); diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index ac39aaad4..5a2a808dd 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -24,6 +24,9 @@ static async Task Main(string[] args) var csdlOption = new Option("--csdl", "Input CSDL file path or URL"); csdlOption.AddAlias("-cs"); + var csdlFilterOption = new Option("--csdlFilter", "Name of EntitySet or Singleton to filter CSDL on"); + csdlOption.AddAlias("-csf"); + var outputOption = new Option("--output", () => new FileInfo("./output"), "The output directory path for the generated file.") { Arity = ArgumentArity.ZeroOrOne }; outputOption.AddAlias("-o"); @@ -66,6 +69,7 @@ static async Task Main(string[] args) { descriptionOption, csdlOption, + csdlFilterOption, outputOption, cleanOutputOption, versionOption, @@ -78,8 +82,8 @@ static async Task Main(string[] args) resolveExternalOption, }; - transformCommand.SetHandler ( - OpenApiService.TransformOpenApiDocument, descriptionOption, csdlOption, outputOption, cleanOutputOption, versionOption, formatOption, logLevelOption, inlineOption, resolveExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption); + transformCommand.SetHandler ( + OpenApiService.TransformOpenApiDocument, descriptionOption, csdlOption, csdlFilterOption, outputOption, cleanOutputOption, versionOption, formatOption, logLevelOption, inlineOption, resolveExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption); rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiServiceTests.cs index 1c9fd003b..af5437aa1 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiServiceTests.cs @@ -22,7 +22,7 @@ public async Task ReturnConvertedCSDLFile() // Act var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream); - var expectedPathCount = 6; + var expectedPathCount = 5; // Assert Assert.NotNull(openApiDoc); From 7aae53be9813a0b12478dbaf8f1e4c18a9c6a4dd Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 27 Mar 2022 09:07:50 -0400 Subject: [PATCH 021/855] Fixed issue with v2 external references --- .../Microsoft.OpenApi.Hidi.csproj | 4 +- .../Microsoft.OpenApi.Readers.csproj | 2 +- .../V2/OpenApiV2VersionService.cs | 48 ++++++++++++++++++- .../V3/OpenApiV3VersionService.cs | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../ConvertToOpenApiReferenceV2Tests.cs | 22 ++++++++- .../Microsoft.OpenApi.Tests.csproj | 8 ++-- 7 files changed, 76 insertions(+), 12 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index cd8d14132..add38e832 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -33,10 +33,10 @@ - + - + diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 1b4542073..4241daf6a 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -40,7 +40,7 @@ - + diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index fbd4dbb85..c4d765734 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -130,6 +130,30 @@ private static string GetReferenceTypeV2Name(ReferenceType referenceType) } } + private static ReferenceType GetReferenceTypeV2FromName(string referenceType) + { + switch (referenceType) + { + case "definitions": + return ReferenceType.Schema; + + case "parameters": + return ReferenceType.Parameter; + + case "responses": + return ReferenceType.Response; + + case "tags": + return ReferenceType.Tag; + + case "securityDefinitions": + return ReferenceType.SecurityScheme; + + default: + throw new ArgumentException(); + } + } + /// /// Parse the string to a object. /// @@ -176,12 +200,34 @@ public OpenApiReference ConvertToOpenApiReference(string reference, ReferenceTyp } } + // Where fragments point into a non-OpenAPI document, the id will be the complete fragment identifier + string id = segments[1]; + // $ref: externalSource.yaml#/Pet + if (id.StartsWith("/definitions/")) + { + var localSegments = id.Split('/'); + var referencedType = GetReferenceTypeV2FromName(localSegments[1]); + if (type == null) + { + type = referencedType; + } + else + { + if (type != referencedType) + { + throw new OpenApiException("Referenced type mismatch"); + } + } + id = localSegments[2]; + } + + // $ref: externalSource.yaml#/Pet return new OpenApiReference { ExternalResource = segments[0], Type = type, - Id = segments[1].Substring(1) + Id = id }; } } diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 3ee8b8d4e..65acbc4e0 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.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; diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 086d80d75..7d346009e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -247,7 +247,7 @@ - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs index ff6641f88..bd9600e4f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs @@ -17,14 +17,32 @@ public ConvertToOpenApiReferenceV2Tests() Diagnostic = new OpenApiDiagnostic(); } + [Fact] + public void ParseExternalReferenceToV2OpenApi() + { + // Arrange + var versionService = new OpenApiV2VersionService(Diagnostic); + var externalResource = "externalSchema.json"; + var id = "mySchema"; + var input = $"{externalResource}#/definitions/{id}"; + + // Act + var reference = versionService.ConvertToOpenApiReference(input, null); + + // Assert + reference.ExternalResource.Should().Be(externalResource); + reference.Type.Should().NotBeNull(); + reference.Id.Should().Be(id); + } + [Fact] public void ParseExternalReference() { // Arrange var versionService = new OpenApiV2VersionService(Diagnostic); var externalResource = "externalSchema.json"; - var id = "externalPathSegment1/externalPathSegment2/externalPathSegment3"; - var input = $"{externalResource}#/{id}"; + var id = "/externalPathSegment1/externalPathSegment2/externalPathSegment3"; + var input = $"{externalResource}#{id}"; // Act var reference = versionService.ConvertToOpenApiReference(input, null); diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index de827c62f..df3c736e2 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -17,11 +17,11 @@ - + - - - + + + all From caa87da7a117071f0038d9b7bff780ee2e8d8ebd Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 27 Mar 2022 14:33:59 -0400 Subject: [PATCH 022/855] Fixed reporting collections with urls not in OpenAPI --- filteredGraph.yaml | 478 ++++++++++++++++++ .../Services/OpenApiFilterService.cs | 18 +- 2 files changed, 487 insertions(+), 9 deletions(-) create mode 100644 filteredGraph.yaml diff --git a/filteredGraph.yaml b/filteredGraph.yaml new file mode 100644 index 000000000..4dea96ea8 --- /dev/null +++ b/filteredGraph.yaml @@ -0,0 +1,478 @@ +openapi: 3.0.1 +info: + title: OData Service for namespace microsoft.graph - Subset + description: This OData service is located at https://graph.microsoft.com/v1.0 + version: 1.0.1 +servers: + - url: https://graph.microsoft.com/v1.0 +paths: + /admin/serviceAnnouncement: + get: + tags: + - admin.serviceAnnouncement + summary: Get serviceAnnouncement from admin + description: A container for service communications resources. Read-only. + operationId: admin.GetServiceAnnouncement + parameters: + - name: $select + in: query + description: Select properties to be returned + style: form + explode: false + schema: + uniqueItems: true + type: array + items: + enum: + - id + - healthOverviews + - issues + - messages + type: string + - name: $expand + in: query + description: Expand related entities + style: form + explode: false + schema: + uniqueItems: true + type: array + items: + enum: + - '*' + - healthOverviews + - issues + - messages + type: string + responses: + '200': + description: Retrieved navigation property + content: + application/json: + schema: + $ref: '#/components/schemas/microsoft.graph.serviceAnnouncement' + links: + healthOverviews: + operationId: admin.ServiceAnnouncement.ListHealthOverviews + issues: + operationId: admin.ServiceAnnouncement.ListIssues + messages: + operationId: admin.ServiceAnnouncement.ListMessages + 4XX: + $ref: '#/components/responses/error' + 5XX: + $ref: '#/components/responses/error' + x-ms-docs-operation-type: operation + patch: + tags: + - admin.serviceAnnouncement + summary: Update the navigation property serviceAnnouncement in admin + operationId: admin.UpdateServiceAnnouncement + requestBody: + description: New navigation property values + content: + application/json: + schema: + $ref: '#/components/schemas/microsoft.graph.serviceAnnouncement' + required: true + responses: + '204': + description: Success + 4XX: + $ref: '#/components/responses/error' + 5XX: + $ref: '#/components/responses/error' + x-ms-docs-operation-type: operation +components: + schemas: + microsoft.graph.serviceAnnouncement: + allOf: + - $ref: '#/components/schemas/microsoft.graph.entity' + - title: serviceAnnouncement + type: object + properties: + healthOverviews: + type: array + items: + $ref: '#/components/schemas/microsoft.graph.serviceHealth' + description: 'A collection of service health information for tenant. This property is a contained navigation property, it is nullable and readonly.' + issues: + type: array + items: + $ref: '#/components/schemas/microsoft.graph.serviceHealthIssue' + description: 'A collection of service issues for tenant. This property is a contained navigation property, it is nullable and readonly.' + messages: + type: array + items: + $ref: '#/components/schemas/microsoft.graph.serviceUpdateMessage' + description: 'A collection of service messages for tenant. This property is a contained navigation property, it is nullable and readonly.' + microsoft.graph.entity: + title: entity + type: object + properties: + id: + type: string + description: Read-only. + microsoft.graph.serviceHealth: + allOf: + - $ref: '#/components/schemas/microsoft.graph.entity' + - title: serviceHealth + type: object + properties: + service: + type: string + description: The service name. Use the list healthOverviews operation to get exact string names for services subscribed by the tenant. + status: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.serviceHealthStatus' + description: 'Show the overral service health status. Possible values are: serviceOperational, investigating, restoringService, verifyingService, serviceRestored, postIncidentReviewPublished, serviceDegradation, serviceInterruption, extendedRecovery, falsePositive, investigationSuspended, resolved, mitigatedExternal, mitigated, resolvedExternal, confirmed, reported, unknownFutureValue. For more details, see serviceHealthStatus values.' + issues: + type: array + items: + $ref: '#/components/schemas/microsoft.graph.serviceHealthIssue' + description: 'A collection of issues that happened on the service, with detailed information for each issue.' + microsoft.graph.serviceHealthIssue: + allOf: + - $ref: '#/components/schemas/microsoft.graph.serviceAnnouncementBase' + - title: serviceHealthIssue + type: object + properties: + classification: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.serviceHealthClassificationType' + description: 'The type of service health issue. Possible values are: advisory, incident, unknownFutureValue.' + feature: + type: string + description: The feature name of the service issue. + nullable: true + featureGroup: + type: string + description: The feature group name of the service issue. + nullable: true + impactDescription: + type: string + description: The description of the service issue impact. + isResolved: + type: boolean + description: Indicates whether the issue is resolved. + origin: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.serviceHealthOrigin' + description: 'Indicates the origin of the service issue. Possible values are: microsoft, thirdParty, customer, unknownFutureValue.' + posts: + type: array + items: + $ref: '#/components/schemas/microsoft.graph.serviceHealthIssuePost' + description: Collection of historical posts for the service issue. + service: + type: string + description: Indicates the service affected by the issue. + status: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.serviceHealthStatus' + description: 'The status of the service issue. Possible values are: serviceOperational, investigating, restoringService, verifyingService, serviceRestored, postIncidentReviewPublished, serviceDegradation, serviceInterruption, extendedRecovery, falsePositive, investigationSuspended, resolved, mitigatedExternal, mitigated, resolvedExternal, confirmed, reported, unknownFutureValue. See more in the table below.' + microsoft.graph.serviceUpdateMessage: + allOf: + - $ref: '#/components/schemas/microsoft.graph.serviceAnnouncementBase' + - title: serviceUpdateMessage + type: object + properties: + actionRequiredByDateTime: + pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' + type: string + description: The expected deadline of the action for the message. + format: date-time + nullable: true + attachmentsArchive: + type: string + description: The zip file that contains all attachments for a message. + format: base64url + nullable: true + body: + $ref: '#/components/schemas/microsoft.graph.itemBody' + category: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.serviceUpdateCategory' + description: 'The service message category. Possible values are: preventOrFixIssue, planForChange, stayInformed, unknownFutureValue.' + hasAttachments: + type: boolean + description: Indicates whether the message has any attachment. + isMajorChange: + type: boolean + description: Indicates whether the message describes a major update for the service. + nullable: true + services: + type: array + items: + type: string + nullable: true + description: The affected services by the service message. + severity: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.serviceUpdateSeverity' + description: 'The severity of the service message. Possible values are: normal, high, critical, unknownFutureValue.' + tags: + type: array + items: + type: string + nullable: true + description: 'A collection of tags for the service message. Tags are provided by the service team/support team who post the message to tell whether this message contains privacy data, or whether this message is for a service new feature update, and so on.' + viewPoint: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.serviceUpdateMessageViewpoint' + description: 'Represents user viewpoints data of the service message. This data includes message status such as whether the user has archived, read, or marked the message as favorite. This property is null when accessed with application permissions.' + nullable: true + attachments: + type: array + items: + $ref: '#/components/schemas/microsoft.graph.serviceAnnouncementAttachment' + description: A collection of serviceAnnouncementAttachments. + microsoft.graph.ODataErrors.ODataError: + required: + - error + type: object + properties: + error: + $ref: '#/components/schemas/microsoft.graph.ODataErrors.MainError' + microsoft.graph.serviceHealthStatus: + title: serviceHealthStatus + enum: + - serviceOperational + - investigating + - restoringService + - verifyingService + - serviceRestored + - postIncidentReviewPublished + - serviceDegradation + - serviceInterruption + - extendedRecovery + - falsePositive + - investigationSuspended + - resolved + - mitigatedExternal + - mitigated + - resolvedExternal + - confirmed + - reported + - unknownFutureValue + type: string + microsoft.graph.serviceAnnouncementBase: + allOf: + - $ref: '#/components/schemas/microsoft.graph.entity' + - title: serviceAnnouncementBase + type: object + properties: + details: + type: array + items: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.keyValuePair' + nullable: true + description: Additional details about service event. This property doesn't support filters. + endDateTime: + pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' + type: string + description: The end time of the service event. + format: date-time + nullable: true + lastModifiedDateTime: + pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' + type: string + description: The last modified time of the service event. + format: date-time + startDateTime: + pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' + type: string + description: The start time of the service event. + format: date-time + title: + type: string + description: The title of the service event. + microsoft.graph.serviceHealthClassificationType: + title: serviceHealthClassificationType + enum: + - advisory + - incident + - unknownFutureValue + type: string + microsoft.graph.serviceHealthOrigin: + title: serviceHealthOrigin + enum: + - microsoft + - thirdParty + - customer + - unknownFutureValue + type: string + microsoft.graph.serviceHealthIssuePost: + title: serviceHealthIssuePost + type: object + properties: + createdDateTime: + pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' + type: string + description: The published time of the post. + format: date-time + description: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.itemBody' + description: The content of the service issue post. + nullable: true + postType: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.postType' + description: 'The post type of the service issue historical post. Possible values are: regular, quick, strategic, unknownFutureValue.' + nullable: true + microsoft.graph.itemBody: + title: itemBody + type: object + properties: + content: + type: string + description: The content of the item. + nullable: true + contentType: + anyOf: + - $ref: '#/components/schemas/microsoft.graph.bodyType' + description: The type of the content. Possible values are text and html. + nullable: true + microsoft.graph.serviceUpdateCategory: + title: serviceUpdateCategory + enum: + - preventOrFixIssue + - planForChange + - stayInformed + - unknownFutureValue + type: string + microsoft.graph.serviceUpdateSeverity: + title: serviceUpdateSeverity + enum: + - normal + - high + - critical + - unknownFutureValue + type: string + microsoft.graph.serviceUpdateMessageViewpoint: + title: serviceUpdateMessageViewpoint + type: object + properties: + isArchived: + type: boolean + description: Indicates whether the user archived the message. + nullable: true + isFavorited: + type: boolean + description: Indicates whether the user marked the message as favorite. + nullable: true + isRead: + type: boolean + description: Indicates whether the user read the message. + nullable: true + microsoft.graph.serviceAnnouncementAttachment: + allOf: + - $ref: '#/components/schemas/microsoft.graph.entity' + - title: serviceAnnouncementAttachment + type: object + properties: + content: + type: string + description: The attachment content. + format: base64url + nullable: true + contentType: + type: string + nullable: true + lastModifiedDateTime: + pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' + type: string + format: date-time + nullable: true + name: + type: string + nullable: true + size: + maximum: 2147483647 + minimum: -2147483648 + type: integer + format: int32 + microsoft.graph.ODataErrors.MainError: + required: + - code + - message + type: object + properties: + code: + type: string + message: + type: string + target: + type: string + nullable: true + details: + type: array + items: + $ref: '#/components/schemas/microsoft.graph.ODataErrors.ErrorDetails' + innererror: + $ref: '#/components/schemas/microsoft.graph.ODataErrors.InnerError' + microsoft.graph.keyValuePair: + title: keyValuePair + type: object + properties: + name: + type: string + description: Name for this key-value pair + value: + type: string + description: Value for this key-value pair + nullable: true + microsoft.graph.postType: + title: postType + enum: + - regular + - quick + - strategic + - unknownFutureValue + type: string + microsoft.graph.bodyType: + title: bodyType + enum: + - text + - html + type: string + microsoft.graph.ODataErrors.ErrorDetails: + required: + - code + - message + type: object + properties: + code: + type: string + message: + type: string + target: + type: string + nullable: true + microsoft.graph.ODataErrors.InnerError: + title: InnerError + type: object + properties: + request-id: + type: string + description: Request Id as tracked internally by the service + nullable: true + client-request-id: + type: string + description: Client request Id as sent by the client application. + nullable: true + Date: + pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' + type: string + description: Date when the error occured. + format: date-time + nullable: true + responses: + error: + description: error + content: + application/json: + schema: + $ref: '#/components/schemas/microsoft.graph.ODataErrors.ODataError' \ No newline at end of file diff --git a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs index 57c5fef09..11dcaec14 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs @@ -73,24 +73,24 @@ public static class OpenApiFilterService var rootNode = CreateOpenApiUrlTreeNode(sources); // Iterate through urls dictionary and fetch operations for each url - foreach (var path in requestUrls) + foreach (var url in requestUrls) { var serverList = source.Servers; - var url = FormatUrlString(path.Key, serverList); + var path = ExtractPath(url.Key, serverList); - var openApiOperations = GetOpenApiOperations(rootNode, url, apiVersion); + var openApiOperations = GetOpenApiOperations(rootNode, path, apiVersion); if (openApiOperations == null) { - Console.WriteLine($"The url {url} could not be found in the OpenApi description"); + Console.WriteLine($"The url {url.Key} could not be found in the OpenApi description"); continue; } // Add the available ops if they are in the postman collection. See path.Value foreach (var ops in openApiOperations) { - if (path.Value.Contains(ops.Key.ToString().ToUpper())) + if (url.Value.Contains(ops.Key.ToString().ToUpper())) { - operationTypes.Add(ops.Key + url); + operationTypes.Add(ops.Key + path); } } } @@ -323,7 +323,7 @@ private static bool AddReferences(OpenApiComponents newComponents, OpenApiCompon return moreStuff; } - private static string FormatUrlString(string url, IList serverList) + private static string ExtractPath(string url, IList serverList) { var queryPath = string.Empty; foreach (var server in serverList) @@ -334,8 +334,8 @@ private static string FormatUrlString(string url, IList serverLis continue; } - var querySegments = url.Split(new[]{ serverUrl }, StringSplitOptions.None); - queryPath = querySegments[1]; + var urlComponents = url.Split(new[]{ serverUrl }, StringSplitOptions.None); + queryPath = urlComponents[1]; } return queryPath; From 53c56f7dc2cfa3824c738d9ca133a05c9ceb544e Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 27 Mar 2022 14:37:00 -0400 Subject: [PATCH 023/855] Removed openapi file that snook in. --- filteredGraph.yaml | 478 --------------------------------------------- 1 file changed, 478 deletions(-) delete mode 100644 filteredGraph.yaml diff --git a/filteredGraph.yaml b/filteredGraph.yaml deleted file mode 100644 index 4dea96ea8..000000000 --- a/filteredGraph.yaml +++ /dev/null @@ -1,478 +0,0 @@ -openapi: 3.0.1 -info: - title: OData Service for namespace microsoft.graph - Subset - description: This OData service is located at https://graph.microsoft.com/v1.0 - version: 1.0.1 -servers: - - url: https://graph.microsoft.com/v1.0 -paths: - /admin/serviceAnnouncement: - get: - tags: - - admin.serviceAnnouncement - summary: Get serviceAnnouncement from admin - description: A container for service communications resources. Read-only. - operationId: admin.GetServiceAnnouncement - parameters: - - name: $select - in: query - description: Select properties to be returned - style: form - explode: false - schema: - uniqueItems: true - type: array - items: - enum: - - id - - healthOverviews - - issues - - messages - type: string - - name: $expand - in: query - description: Expand related entities - style: form - explode: false - schema: - uniqueItems: true - type: array - items: - enum: - - '*' - - healthOverviews - - issues - - messages - type: string - responses: - '200': - description: Retrieved navigation property - content: - application/json: - schema: - $ref: '#/components/schemas/microsoft.graph.serviceAnnouncement' - links: - healthOverviews: - operationId: admin.ServiceAnnouncement.ListHealthOverviews - issues: - operationId: admin.ServiceAnnouncement.ListIssues - messages: - operationId: admin.ServiceAnnouncement.ListMessages - 4XX: - $ref: '#/components/responses/error' - 5XX: - $ref: '#/components/responses/error' - x-ms-docs-operation-type: operation - patch: - tags: - - admin.serviceAnnouncement - summary: Update the navigation property serviceAnnouncement in admin - operationId: admin.UpdateServiceAnnouncement - requestBody: - description: New navigation property values - content: - application/json: - schema: - $ref: '#/components/schemas/microsoft.graph.serviceAnnouncement' - required: true - responses: - '204': - description: Success - 4XX: - $ref: '#/components/responses/error' - 5XX: - $ref: '#/components/responses/error' - x-ms-docs-operation-type: operation -components: - schemas: - microsoft.graph.serviceAnnouncement: - allOf: - - $ref: '#/components/schemas/microsoft.graph.entity' - - title: serviceAnnouncement - type: object - properties: - healthOverviews: - type: array - items: - $ref: '#/components/schemas/microsoft.graph.serviceHealth' - description: 'A collection of service health information for tenant. This property is a contained navigation property, it is nullable and readonly.' - issues: - type: array - items: - $ref: '#/components/schemas/microsoft.graph.serviceHealthIssue' - description: 'A collection of service issues for tenant. This property is a contained navigation property, it is nullable and readonly.' - messages: - type: array - items: - $ref: '#/components/schemas/microsoft.graph.serviceUpdateMessage' - description: 'A collection of service messages for tenant. This property is a contained navigation property, it is nullable and readonly.' - microsoft.graph.entity: - title: entity - type: object - properties: - id: - type: string - description: Read-only. - microsoft.graph.serviceHealth: - allOf: - - $ref: '#/components/schemas/microsoft.graph.entity' - - title: serviceHealth - type: object - properties: - service: - type: string - description: The service name. Use the list healthOverviews operation to get exact string names for services subscribed by the tenant. - status: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.serviceHealthStatus' - description: 'Show the overral service health status. Possible values are: serviceOperational, investigating, restoringService, verifyingService, serviceRestored, postIncidentReviewPublished, serviceDegradation, serviceInterruption, extendedRecovery, falsePositive, investigationSuspended, resolved, mitigatedExternal, mitigated, resolvedExternal, confirmed, reported, unknownFutureValue. For more details, see serviceHealthStatus values.' - issues: - type: array - items: - $ref: '#/components/schemas/microsoft.graph.serviceHealthIssue' - description: 'A collection of issues that happened on the service, with detailed information for each issue.' - microsoft.graph.serviceHealthIssue: - allOf: - - $ref: '#/components/schemas/microsoft.graph.serviceAnnouncementBase' - - title: serviceHealthIssue - type: object - properties: - classification: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.serviceHealthClassificationType' - description: 'The type of service health issue. Possible values are: advisory, incident, unknownFutureValue.' - feature: - type: string - description: The feature name of the service issue. - nullable: true - featureGroup: - type: string - description: The feature group name of the service issue. - nullable: true - impactDescription: - type: string - description: The description of the service issue impact. - isResolved: - type: boolean - description: Indicates whether the issue is resolved. - origin: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.serviceHealthOrigin' - description: 'Indicates the origin of the service issue. Possible values are: microsoft, thirdParty, customer, unknownFutureValue.' - posts: - type: array - items: - $ref: '#/components/schemas/microsoft.graph.serviceHealthIssuePost' - description: Collection of historical posts for the service issue. - service: - type: string - description: Indicates the service affected by the issue. - status: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.serviceHealthStatus' - description: 'The status of the service issue. Possible values are: serviceOperational, investigating, restoringService, verifyingService, serviceRestored, postIncidentReviewPublished, serviceDegradation, serviceInterruption, extendedRecovery, falsePositive, investigationSuspended, resolved, mitigatedExternal, mitigated, resolvedExternal, confirmed, reported, unknownFutureValue. See more in the table below.' - microsoft.graph.serviceUpdateMessage: - allOf: - - $ref: '#/components/schemas/microsoft.graph.serviceAnnouncementBase' - - title: serviceUpdateMessage - type: object - properties: - actionRequiredByDateTime: - pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' - type: string - description: The expected deadline of the action for the message. - format: date-time - nullable: true - attachmentsArchive: - type: string - description: The zip file that contains all attachments for a message. - format: base64url - nullable: true - body: - $ref: '#/components/schemas/microsoft.graph.itemBody' - category: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.serviceUpdateCategory' - description: 'The service message category. Possible values are: preventOrFixIssue, planForChange, stayInformed, unknownFutureValue.' - hasAttachments: - type: boolean - description: Indicates whether the message has any attachment. - isMajorChange: - type: boolean - description: Indicates whether the message describes a major update for the service. - nullable: true - services: - type: array - items: - type: string - nullable: true - description: The affected services by the service message. - severity: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.serviceUpdateSeverity' - description: 'The severity of the service message. Possible values are: normal, high, critical, unknownFutureValue.' - tags: - type: array - items: - type: string - nullable: true - description: 'A collection of tags for the service message. Tags are provided by the service team/support team who post the message to tell whether this message contains privacy data, or whether this message is for a service new feature update, and so on.' - viewPoint: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.serviceUpdateMessageViewpoint' - description: 'Represents user viewpoints data of the service message. This data includes message status such as whether the user has archived, read, or marked the message as favorite. This property is null when accessed with application permissions.' - nullable: true - attachments: - type: array - items: - $ref: '#/components/schemas/microsoft.graph.serviceAnnouncementAttachment' - description: A collection of serviceAnnouncementAttachments. - microsoft.graph.ODataErrors.ODataError: - required: - - error - type: object - properties: - error: - $ref: '#/components/schemas/microsoft.graph.ODataErrors.MainError' - microsoft.graph.serviceHealthStatus: - title: serviceHealthStatus - enum: - - serviceOperational - - investigating - - restoringService - - verifyingService - - serviceRestored - - postIncidentReviewPublished - - serviceDegradation - - serviceInterruption - - extendedRecovery - - falsePositive - - investigationSuspended - - resolved - - mitigatedExternal - - mitigated - - resolvedExternal - - confirmed - - reported - - unknownFutureValue - type: string - microsoft.graph.serviceAnnouncementBase: - allOf: - - $ref: '#/components/schemas/microsoft.graph.entity' - - title: serviceAnnouncementBase - type: object - properties: - details: - type: array - items: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.keyValuePair' - nullable: true - description: Additional details about service event. This property doesn't support filters. - endDateTime: - pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' - type: string - description: The end time of the service event. - format: date-time - nullable: true - lastModifiedDateTime: - pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' - type: string - description: The last modified time of the service event. - format: date-time - startDateTime: - pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' - type: string - description: The start time of the service event. - format: date-time - title: - type: string - description: The title of the service event. - microsoft.graph.serviceHealthClassificationType: - title: serviceHealthClassificationType - enum: - - advisory - - incident - - unknownFutureValue - type: string - microsoft.graph.serviceHealthOrigin: - title: serviceHealthOrigin - enum: - - microsoft - - thirdParty - - customer - - unknownFutureValue - type: string - microsoft.graph.serviceHealthIssuePost: - title: serviceHealthIssuePost - type: object - properties: - createdDateTime: - pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' - type: string - description: The published time of the post. - format: date-time - description: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.itemBody' - description: The content of the service issue post. - nullable: true - postType: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.postType' - description: 'The post type of the service issue historical post. Possible values are: regular, quick, strategic, unknownFutureValue.' - nullable: true - microsoft.graph.itemBody: - title: itemBody - type: object - properties: - content: - type: string - description: The content of the item. - nullable: true - contentType: - anyOf: - - $ref: '#/components/schemas/microsoft.graph.bodyType' - description: The type of the content. Possible values are text and html. - nullable: true - microsoft.graph.serviceUpdateCategory: - title: serviceUpdateCategory - enum: - - preventOrFixIssue - - planForChange - - stayInformed - - unknownFutureValue - type: string - microsoft.graph.serviceUpdateSeverity: - title: serviceUpdateSeverity - enum: - - normal - - high - - critical - - unknownFutureValue - type: string - microsoft.graph.serviceUpdateMessageViewpoint: - title: serviceUpdateMessageViewpoint - type: object - properties: - isArchived: - type: boolean - description: Indicates whether the user archived the message. - nullable: true - isFavorited: - type: boolean - description: Indicates whether the user marked the message as favorite. - nullable: true - isRead: - type: boolean - description: Indicates whether the user read the message. - nullable: true - microsoft.graph.serviceAnnouncementAttachment: - allOf: - - $ref: '#/components/schemas/microsoft.graph.entity' - - title: serviceAnnouncementAttachment - type: object - properties: - content: - type: string - description: The attachment content. - format: base64url - nullable: true - contentType: - type: string - nullable: true - lastModifiedDateTime: - pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' - type: string - format: date-time - nullable: true - name: - type: string - nullable: true - size: - maximum: 2147483647 - minimum: -2147483648 - type: integer - format: int32 - microsoft.graph.ODataErrors.MainError: - required: - - code - - message - type: object - properties: - code: - type: string - message: - type: string - target: - type: string - nullable: true - details: - type: array - items: - $ref: '#/components/schemas/microsoft.graph.ODataErrors.ErrorDetails' - innererror: - $ref: '#/components/schemas/microsoft.graph.ODataErrors.InnerError' - microsoft.graph.keyValuePair: - title: keyValuePair - type: object - properties: - name: - type: string - description: Name for this key-value pair - value: - type: string - description: Value for this key-value pair - nullable: true - microsoft.graph.postType: - title: postType - enum: - - regular - - quick - - strategic - - unknownFutureValue - type: string - microsoft.graph.bodyType: - title: bodyType - enum: - - text - - html - type: string - microsoft.graph.ODataErrors.ErrorDetails: - required: - - code - - message - type: object - properties: - code: - type: string - message: - type: string - target: - type: string - nullable: true - microsoft.graph.ODataErrors.InnerError: - title: InnerError - type: object - properties: - request-id: - type: string - description: Request Id as tracked internally by the service - nullable: true - client-request-id: - type: string - description: Client request Id as sent by the client application. - nullable: true - Date: - pattern: '^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$' - type: string - description: Date when the error occured. - format: date-time - nullable: true - responses: - error: - description: error - content: - application/json: - schema: - $ref: '#/components/schemas/microsoft.graph.ODataErrors.ODataError' \ No newline at end of file From 988496a0ea0266cd400f985ef9aa161168e2e47e Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 27 Mar 2022 16:49:34 -0400 Subject: [PATCH 024/855] Fixed command alias and some descriptions --- src/Microsoft.OpenApi.Hidi/Program.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 0eab5a693..8b466913c 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -24,8 +24,8 @@ static async Task Main(string[] args) var csdlOption = new Option("--csdl", "Input CSDL file path or URL"); csdlOption.AddAlias("-cs"); - var csdlFilterOption = new Option("--csdlFilter", "Name of EntitySet or Singleton to filter CSDL on"); - csdlOption.AddAlias("-csf"); + var csdlFilterOption = new Option("--csdl-filter", "Comma delimited list of EntitySets or Singletons to filter CSDL on. e.g. tasks,accounts"); + csdlFilterOption.AddAlias("-csf"); var outputOption = new Option("--output", () => new FileInfo("./output"), "The output directory path for the generated file.") { Arity = ArgumentArity.ZeroOrOne }; outputOption.AddAlias("-o"); @@ -42,13 +42,13 @@ static async Task Main(string[] args) var logLevelOption = new Option("--loglevel", () => LogLevel.Information, "The log level to use when logging messages to the main output."); logLevelOption.AddAlias("-ll"); - var filterByOperationIdsOption = new Option("--filter-by-operationids", "Filters OpenApiDocument by OperationId(s) provided"); + var filterByOperationIdsOption = new Option("--filter-by-operationids", "Filters OpenApiDocument by comma delimited list of OperationId(s) provided"); filterByOperationIdsOption.AddAlias("-op"); - var filterByTagsOption = new Option("--filter-by-tags", "Filters OpenApiDocument by Tag(s) provided"); + var filterByTagsOption = new Option("--filter-by-tags", "Filters OpenApiDocument by comma delimited list of Tag(s) provided. Also accepts a single regex."); filterByTagsOption.AddAlias("-t"); - var filterByCollectionOption = new Option("--filter-by-collection", "Filters OpenApiDocument by Postman collection provided"); + var filterByCollectionOption = new Option("--filter-by-collection", "Filters OpenApiDocument by Postman collection provided. Provide path to collection file."); filterByCollectionOption.AddAlias("-c"); var inlineLocalOption = new Option("--inlineLocal", "Inline local $ref instances"); From 17e738691844fee2f35c5475b64899452a84d566 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 27 Mar 2022 17:09:34 -0400 Subject: [PATCH 025/855] Updated Verify nupkg --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 066d20658..5ae43a371 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,8 +20,8 @@ - - + + all From 271e1aa66af24548f93b999a91b609d80bc2c90a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 29 Mar 2022 21:13:35 +0000 Subject: [PATCH 026/855] Bump Microsoft.OpenApi.OData from 1.0.10-preview2 to 1.0.10-preview3 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.0.10-preview2 to 1.0.10-preview3. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 98def8818..128521424 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -46,7 +46,7 @@ - + From 0ecaed80638ebf6de212e0324895873191b6ee3e Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 3 Apr 2022 20:40:05 -0400 Subject: [PATCH 027/855] Convert anyOf/oneOf to allOf with first schema when writing v2 --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 74aed7da1..036222261 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.Collections.Generic; +using System.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -260,7 +261,7 @@ public void SerializeAsV3(IOpenApiWriter writer) { Reference.SerializeAsV3(writer); return; - } + } else { if (Reference.IsExternal) // Temporary until v2 @@ -644,6 +645,20 @@ 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 + // schema in the list as an attempt to guess at a graceful downgrade situation. + if (AllOf == null || AllOf.Count == 0) + { + // anyOf (Not Supported in V2) - Write the first schema only as an allOf. + writer.WriteOptionalCollection(OpenApiConstants.AllOf, AnyOf.Take(1), (w, s) => s.SerializeAsV2(w)); + + if (AnyOf == null || AnyOf.Count == 0) + { + // oneOf (Not Supported in V2) - Write the first schema only as an allOf. + writer.WriteOptionalCollection(OpenApiConstants.AllOf, OneOf.Take(1), (w, s) => s.SerializeAsV2(w)); + } + } + // properties writer.WriteOptionalMap(OpenApiConstants.Properties, Properties, (w, key, s) => s.SerializeAsV2(w, Required, key)); From 172c4538e2a8e35192de2a95f005a443c678448f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 4 Apr 2022 21:10:39 +0000 Subject: [PATCH 028/855] Bump Verify from 16.4.4 to 16.5.4 Bumps [Verify](https://github.com/VerifyTests/Verify) from 16.4.4 to 16.5.4. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 5ae43a371..d67a655cc 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + From c3e898038367b6f1662d7f94249a0faa37ebc322 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 4 Apr 2022 21:10:44 +0000 Subject: [PATCH 029/855] Bump FluentAssertions from 6.5.1 to 6.6.0 Bumps [FluentAssertions](https://github.com/fluentassertions/fluentassertions) from 6.5.1 to 6.6.0. - [Release notes](https://github.com/fluentassertions/fluentassertions/releases) - [Changelog](https://github.com/fluentassertions/fluentassertions/blob/develop/AcceptApiChanges.ps1) - [Commits](https://github.com/fluentassertions/fluentassertions/compare/6.5.1...6.6.0) --- updated-dependencies: - dependency-name: FluentAssertions dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 7d346009e..bfcba0163 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -243,7 +243,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 5ae43a371..9ba4c4501 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,7 +15,7 @@ - + From d0f41afa89031a0093b8ea1ab4c40e330574eb8c Mon Sep 17 00:00:00 2001 From: Dmitrii Korolev Date: Fri, 8 Apr 2022 20:00:43 +0200 Subject: [PATCH 030/855] resolve local file reference with Schema type properly --- .../V3/OpenApiV3VersionService.cs | 20 ++++++++----------- .../ConvertToOpenApiReferenceV3Tests.cs | 16 +++++++++++++++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 65acbc4e0..c967cde55 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -75,18 +75,6 @@ public OpenApiReference ConvertToOpenApiReference( var segments = reference.Split('#'); if (segments.Length == 1) { - // Either this is an external reference as an entire file - // or a simple string-style reference for tag and security scheme. - if (type == null) - { - // "$ref": "Pet.json" - return new OpenApiReference - { - Type = type, - ExternalResource = segments[0] - }; - } - if (type == ReferenceType.Tag || type == ReferenceType.SecurityScheme) { return new OpenApiReference @@ -95,6 +83,14 @@ public OpenApiReference ConvertToOpenApiReference( Id = reference }; } + + // Either this is an external reference as an entire file + // or a simple string-style reference for tag and security scheme. + return new OpenApiReference + { + Type = type, + ExternalResource = segments[0] + }; } else if (segments.Length == 2) { diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs index c4e88998e..f7368b09b 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs @@ -108,5 +108,21 @@ public void ParseSecuritySchemeReference() reference.ExternalResource.Should().BeNull(); reference.Id.Should().Be(id); } + + [Fact] + public void ParseLocalFileReference() + { + // Arrange + var versionService = new OpenApiV3VersionService(Diagnostic); + var referenceType = ReferenceType.Schema; + var input = $"../schemas/collection.json"; + + // Act + var reference = versionService.ConvertToOpenApiReference(input, referenceType); + + // Assert + reference.Type.Should().Be(referenceType); + reference.ExternalResource.Should().Be(input); + } } } From decde9db830ecd5ddc5d0d7c49cd2d626c324fd0 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 9 Apr 2022 14:57:09 -0400 Subject: [PATCH 031/855] Added support for Validation to produce warnings as well as errors --- .../OpenApiDiagnostic.cs | 5 +++ .../OpenApiYamlDocumentReader.cs | 11 ++++- .../Extensions/OpenApiElementExtensions.cs | 3 +- .../Validations/IValidationContext.cs | 6 +++ .../Validations/OpenApiValidatiorWarning.cs | 28 +++++++++++++ .../Validations/OpenApiValidator.cs | 25 ++++++++++++ .../Validations/Rules/OpenApiHeaderRules.cs | 1 + .../Rules/OpenApiMediaTypeRules.cs | 2 +- .../Validations/Rules/OpenApiSchemaRules.cs | 1 + .../Validations/Rules/RuleHelpers.cs | 28 ++++++------- .../Validations/ValidationExtensions.cs | 10 +++++ .../PublicApi/PublicApi.approved.txt | 10 +++++ .../OpenApiHeaderValidationTests.cs | 17 ++++---- .../OpenApiMediaTypeValidationTests.cs | 22 +++++----- .../OpenApiParameterValidationTests.cs | 20 +++++----- .../OpenApiSchemaValidationTests.cs | 40 +++++++++---------- .../Validations/ValidationRuleSetTests.cs | 2 +- 17 files changed, 162 insertions(+), 69 deletions(-) create mode 100644 src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs diff --git a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs index ea11c7939..c3178ccfb 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs @@ -17,6 +17,11 @@ public class OpenApiDiagnostic : IDiagnostic /// public IList Errors { get; set; } = new List(); + /// + /// List of all warnings + /// + public IList Warnings { get; set; } = new List(); + /// /// Open API specification version of the document parsed. /// diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 6cf64a5bb..aae09ec86 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading.Tasks; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Extensions; @@ -12,6 +13,7 @@ using Microsoft.OpenApi.Readers.Interface; using Microsoft.OpenApi.Readers.Services; using Microsoft.OpenApi.Services; +using Microsoft.OpenApi.Validations; using SharpYaml.Serialization; namespace Microsoft.OpenApi.Readers @@ -68,11 +70,16 @@ public OpenApiDocument Read(YamlDocument input, out OpenApiDiagnostic diagnostic // Validate the document if (_settings.RuleSet != null && _settings.RuleSet.Rules.Count > 0) { - var errors = document.Validate(_settings.RuleSet); - foreach (var item in errors) + var openApiErrors = document.Validate(_settings.RuleSet); + foreach (var item in openApiErrors.Where(e => e is OpenApiValidatorError)) { diagnostic.Errors.Add(item); } + foreach (var item in openApiErrors.Where(e => e is OpenApiValidatorWarning)) + { + diagnostic.Warnings.Add(item); + } + } return document; diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiElementExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiElementExtensions.cs index 81893a3b2..a047c066d 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiElementExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiElementExtensions.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.Collections.Generic; +using System.Linq; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Services; @@ -25,7 +26,7 @@ public static IEnumerable Validate(this IOpenApiElement element, V var validator = new OpenApiValidator(ruleSet); var walker = new OpenApiWalker(validator); walker.Walk(element); - return validator.Errors; + return validator.Errors.Cast().Union(validator.Warnings); } } } diff --git a/src/Microsoft.OpenApi/Validations/IValidationContext.cs b/src/Microsoft.OpenApi/Validations/IValidationContext.cs index 58f324bab..7ab4d08e7 100644 --- a/src/Microsoft.OpenApi/Validations/IValidationContext.cs +++ b/src/Microsoft.OpenApi/Validations/IValidationContext.cs @@ -14,6 +14,12 @@ public interface IValidationContext /// Error to register. void AddError(OpenApiValidatorError error); + /// + /// Register a warning with the validation context. + /// + /// Warning to register. + void AddWarning(OpenApiValidatorWarning warning); + /// /// Allow Rule to indicate validation error occured at a deeper context level. /// diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs new file mode 100644 index 000000000..77480584d --- /dev/null +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.OpenApi.Exceptions; +using Microsoft.OpenApi.Models; + +namespace Microsoft.OpenApi.Validations +{ + /// + /// Warnings detected when validating an OpenAPI Element + /// + public class OpenApiValidatorWarning : OpenApiError + { + /// + /// Initializes the class. + /// + public OpenApiValidatorWarning(string ruleName, string pointer, string message) : base(pointer, message) + { + RuleName = ruleName; + } + + /// + /// Name of rule that detected the error. + /// + public string RuleName { get; set; } + } + +} diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index 69bcda93d..ba2ed4129 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -17,6 +17,7 @@ public class OpenApiValidator : OpenApiVisitorBase, IValidationContext { private readonly ValidationRuleSet _ruleSet; private readonly IList _errors = new List(); + private readonly IList _warnings = new List(); /// /// Create a vistor that will validate an OpenAPIDocument @@ -38,6 +39,17 @@ public IEnumerable Errors } } + /// + /// Gets the validation warnings. + /// + public IEnumerable Warnings + { + get + { + return _warnings; + } + } + /// /// Register an error with the validation context. /// @@ -52,6 +64,19 @@ public void AddError(OpenApiValidatorError error) _errors.Add(error); } + /// + /// Register an error with the validation context. + /// + /// Error to register. + public void AddWarning(OpenApiValidatorWarning warning) + { + if (warning == null) + { + throw Error.ArgumentNull(nameof(warning)); + } + + _warnings.Add(warning); + } /// /// Execute validation rules against an diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs index f2b036457..9ffbc38f4 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs @@ -10,6 +10,7 @@ namespace Microsoft.OpenApi.Validations.Rules /// /// The validation rules for . /// + //Removed from Default Rules as this is not a MUST in OpenAPI [OpenApiRule] public static class OpenApiHeaderRules { diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs index c86b5e79e..21ad4ef72 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs @@ -17,7 +17,7 @@ namespace Microsoft.OpenApi.Validations.Rules /// Future versions of the example parsers should not try an infer types. /// Example validation should be done as a separate post reading step so all schemas can be fully available. /// - //[OpenApiRule] + [OpenApiRule] public static class OpenApiMediaTypeRules { /// diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index 8c45c8ff9..1639e6248 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -11,6 +11,7 @@ namespace Microsoft.OpenApi.Validations.Rules /// /// The validation rules for . /// + [OpenApiRule] public static class OpenApiSchemaRules { diff --git a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs index 05cce7fbc..630dc8e65 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs @@ -77,7 +77,7 @@ public static void ValidateDataTypeMismatch( // If value is not a string and also not an object, there is a data mismatch. if (!(value is OpenApiObject)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); return; @@ -117,7 +117,7 @@ public static void ValidateDataTypeMismatch( // If value is not a string and also not an array, there is a data mismatch. if (!(value is OpenApiArray)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); return; @@ -141,7 +141,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiInteger)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -153,7 +153,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiLong)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -165,7 +165,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiInteger)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -177,7 +177,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiFloat)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -189,7 +189,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiDouble)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -201,7 +201,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiDouble)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -213,7 +213,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiByte)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -225,7 +225,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiDate)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -237,7 +237,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiDateTime)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -249,7 +249,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiPassword)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -261,7 +261,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiString)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } @@ -273,7 +273,7 @@ public static void ValidateDataTypeMismatch( { if (!(value is OpenApiBoolean)) { - context.CreateError( + context.CreateWarning( ruleName, DataTypeMismatchedErrorMessage); } diff --git a/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs b/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs index a66d085c3..195df89cd 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs @@ -23,5 +23,15 @@ public static void CreateError(this IValidationContext context, string ruleName, OpenApiValidatorError error = new OpenApiValidatorError(ruleName, context.PathString, message); context.AddError(error); } + + /// + /// Helper method to simplify validation rules + /// + public static void CreateWarning(this IValidationContext context, string ruleName, string message) + { + OpenApiValidatorWarning warning = new OpenApiValidatorWarning(ruleName, context.PathString, message); + context.AddWarning(warning); + } + } } diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 0b1dc1a11..a6299a644 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1085,6 +1085,7 @@ namespace Microsoft.OpenApi.Validations { string PathString { get; } void AddError(Microsoft.OpenApi.Validations.OpenApiValidatorError error); + void AddWarning(Microsoft.OpenApi.Validations.OpenApiValidatorWarning warning); void Enter(string segment); void Exit(); } @@ -1092,7 +1093,9 @@ namespace Microsoft.OpenApi.Validations { public OpenApiValidator(Microsoft.OpenApi.Validations.ValidationRuleSet ruleSet) { } public System.Collections.Generic.IEnumerable Errors { get; } + public System.Collections.Generic.IEnumerable Warnings { get; } public void AddError(Microsoft.OpenApi.Validations.OpenApiValidatorError error) { } + public void AddWarning(Microsoft.OpenApi.Validations.OpenApiValidatorWarning warning) { } public override void Visit(Microsoft.OpenApi.Interfaces.IOpenApiExtensible item) { } public override void Visit(Microsoft.OpenApi.Interfaces.IOpenApiExtension item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiCallback item) { } @@ -1119,9 +1122,15 @@ namespace Microsoft.OpenApi.Validations public OpenApiValidatorError(string ruleName, string pointer, string message) { } public string RuleName { get; set; } } + public class OpenApiValidatorWarning : Microsoft.OpenApi.Models.OpenApiError + { + public OpenApiValidatorWarning(string ruleName, string pointer, string message) { } + public string RuleName { get; set; } + } public static class ValidationContextExtensions { public static void CreateError(this Microsoft.OpenApi.Validations.IValidationContext context, string ruleName, string message) { } + public static void CreateWarning(this Microsoft.OpenApi.Validations.IValidationContext context, string ruleName, string message) { } } public abstract class ValidationRule { @@ -1188,6 +1197,7 @@ namespace Microsoft.OpenApi.Validations.Rules { public static Microsoft.OpenApi.Validations.ValidationRule LicenseRequiredFields { get; } } + [Microsoft.OpenApi.Validations.Rules.OpenApiRule] public static class OpenApiMediaTypeRules { public static Microsoft.OpenApi.Validations.ValidationRule MediaTypeMismatchedDataType { get; } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs index 62fc2d1ce..6a082ec0f 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs @@ -38,15 +38,16 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() walker.Walk(header); errors = validator.Errors; - bool result = !errors.Any(); + var warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { "#/example", }); @@ -56,7 +57,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var header = new OpenApiHeader() { @@ -108,18 +109,18 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() var walker = new OpenApiWalker(validator); walker.Walk(header); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { // #enum/0 is not an error since the spec allows // representing an object using a string. diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs index fe36bb8c2..bdffaff28 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs @@ -21,7 +21,7 @@ public class OpenApiMediaTypeValidationTests public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var mediaType = new OpenApiMediaType() { Example = new OpenApiInteger(55), @@ -33,21 +33,20 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() // Act var ruleset = ValidationRuleSet.GetDefaultRuleSet(); - ruleset.Add(OpenApiMediaTypeRules.MediaTypeMismatchedDataType); var validator = new OpenApiValidator(ruleset); var walker = new OpenApiWalker(validator); walker.Walk(mediaType); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { "#/example", }); @@ -57,7 +56,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var mediaType = new OpenApiMediaType() { @@ -105,23 +104,22 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() // Act var ruleset = ValidationRuleSet.GetDefaultRuleSet(); - ruleset.Add(OpenApiMediaTypeRules.MediaTypeMismatchedDataType); var validator = new OpenApiValidator(ruleset); var walker = new OpenApiWalker(validator); walker.Walk(mediaType); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { // #enum/0 is not an error since the spec allows // representing an object using a string. diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs index a7abfd9d8..89be676c5 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs @@ -65,7 +65,7 @@ public void ValidateRequiredIsTrueWhenInIsPathInParameter() public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var parameter = new OpenApiParameter() { Name = "parameter1", @@ -84,16 +84,16 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() var walker = new OpenApiWalker(validator); walker.Walk(parameter); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { "#/{parameter1}/example", }); @@ -103,7 +103,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var parameter = new OpenApiParameter() { @@ -158,18 +158,18 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() var walker = new OpenApiWalker(validator); walker.Walk(parameter); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { // #enum/0 is not an error since the spec allows // representing an object using a string. diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs index 91b1643fa..d239e15a1 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs @@ -21,7 +21,7 @@ public class OpenApiSchemaValidationTests public void ValidateDefaultShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var schema = new OpenApiSchema() { Default = new OpenApiInteger(55), @@ -33,16 +33,16 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForSimpleSchema() var walker = new OpenApiWalker(validator); walker.Walk(schema); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { "#/default", }); @@ -52,7 +52,7 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForSimpleSchema() public void ValidateExampleAndDefaultShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var schema = new OpenApiSchema() { Example = new OpenApiLong(55), @@ -65,17 +65,17 @@ public void ValidateExampleAndDefaultShouldNotHaveDataTypeMismatchForSimpleSchem var walker = new OpenApiWalker(validator); walker.Walk(schema); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { "#/default", "#/example", @@ -86,7 +86,7 @@ public void ValidateExampleAndDefaultShouldNotHaveDataTypeMismatchForSimpleSchem public void ValidateEnumShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var schema = new OpenApiSchema() { Enum = @@ -120,18 +120,18 @@ public void ValidateEnumShouldNotHaveDataTypeMismatchForSimpleSchema() var walker = new OpenApiWalker(validator); walker.Walk(schema); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { // #enum/0 is not an error since the spec allows // representing an object using a string. @@ -145,7 +145,7 @@ public void ValidateEnumShouldNotHaveDataTypeMismatchForSimpleSchema() public void ValidateDefaultShouldNotHaveDataTypeMismatchForComplexSchema() { // Arrange - IEnumerable errors; + IEnumerable warnings; var schema = new OpenApiSchema() { Type = "object", @@ -210,12 +210,12 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForComplexSchema() var walker = new OpenApiWalker(validator); walker.Walk(schema); - errors = validator.Errors; - bool result = !errors.Any(); + warnings = validator.Warnings; + bool result = !warnings.Any(); // Assert result.Should().BeFalse(); - errors.Select(e => e.Message).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Message).Should().BeEquivalentTo(new[] { RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, @@ -223,7 +223,7 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForComplexSchema() RuleHelpers.DataTypeMismatchedErrorMessage, RuleHelpers.DataTypeMismatchedErrorMessage, }); - errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[] + warnings.Select(e => e.Pointer).Should().BeEquivalentTo(new[] { "#/default/property1/0", "#/default/property1/2", diff --git a/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs b/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs index af259cf1b..8153e6054 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs @@ -43,7 +43,7 @@ public void DefaultRuleSetPropertyReturnsTheCorrectRules() Assert.NotEmpty(rules); // Update the number if you add new default rule(s). - Assert.Equal(21, rules.Count); + Assert.Equal(22, rules.Count); } } } From f1b1be1e739091bee88b9619df3c84b621adc155 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 9 Apr 2022 19:19:16 +0000 Subject: [PATCH 032/855] Bump Verify.Xunit from 16.4.4 to 16.5.4 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 16.4.4 to 16.5.4. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 2766de246..39026a9f7 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -21,7 +21,7 @@ - + all From c9835c243a07703e2e4b3e47332da0781975cab4 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 9 Apr 2022 16:57:03 -0400 Subject: [PATCH 033/855] Updated package version to preview6 --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 128521424..72ec16c0b 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 0.5.0-preview5 + 0.5.0-preview6 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 77b9cad26..62da19f40 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.3.1-preview5 + 1.3.1-preview6 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 7f3671942..b6f960daa 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.3.1-preview5 + 1.3.1-preview6 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From e990ca537b0da1547841b407a09fb369a54dc75f Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 10 Apr 2022 16:55:19 -0400 Subject: [PATCH 034/855] Made ResolveReference public again as it is used by Swashbuckle --- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 2 +- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 6ffc260d1..317cdab25 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -351,7 +351,7 @@ internal T ResolveReferenceTo(OpenApiReference reference) where T : class, IO /// /// Load the referenced object from a object /// - internal IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) + public IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) { if (reference == null) { diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 0b1dc1a11..90e9d8f1a 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -508,6 +508,7 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IList Servers { get; set; } public System.Collections.Generic.IList Tags { get; set; } public Microsoft.OpenApi.Services.OpenApiWorkspace Workspace { get; set; } + public Microsoft.OpenApi.Interfaces.IOpenApiReferenceable ResolveReference(Microsoft.OpenApi.Models.OpenApiReference reference, bool useExternal) { } public System.Collections.Generic.IEnumerable ResolveReferences() { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } From eb2189d08502574741dd997be06a09c8033a63fa Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 10 Apr 2022 16:58:25 -0400 Subject: [PATCH 035/855] Made ResolveReference public again as it is used by Swashbuckle --- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 2 +- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 6ffc260d1..317cdab25 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -351,7 +351,7 @@ internal T ResolveReferenceTo(OpenApiReference reference) where T : class, IO /// /// Load the referenced object from a object /// - internal IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) + public IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) { if (reference == null) { diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 0b1dc1a11..90e9d8f1a 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -508,6 +508,7 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IList Servers { get; set; } public System.Collections.Generic.IList Tags { get; set; } public Microsoft.OpenApi.Services.OpenApiWorkspace Workspace { get; set; } + public Microsoft.OpenApi.Interfaces.IOpenApiReferenceable ResolveReference(Microsoft.OpenApi.Models.OpenApiReference reference, bool useExternal) { } public System.Collections.Generic.IEnumerable ResolveReferences() { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } From 3f19293f23bee4c2c2c674f5314e42b8eb8866f6 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 10 Apr 2022 17:03:38 -0400 Subject: [PATCH 036/855] Revert "Made ResolveReference public again as it is used by Swashbuckle" This reverts commit e990ca537b0da1547841b407a09fb369a54dc75f. --- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 2 +- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 317cdab25..6ffc260d1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -351,7 +351,7 @@ internal T ResolveReferenceTo(OpenApiReference reference) where T : class, IO /// /// Load the referenced object from a object /// - public IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) + internal IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) { if (reference == null) { diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 90e9d8f1a..0b1dc1a11 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -508,7 +508,6 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IList Servers { get; set; } public System.Collections.Generic.IList Tags { get; set; } public Microsoft.OpenApi.Services.OpenApiWorkspace Workspace { get; set; } - public Microsoft.OpenApi.Interfaces.IOpenApiReferenceable ResolveReference(Microsoft.OpenApi.Models.OpenApiReference reference, bool useExternal) { } public System.Collections.Generic.IEnumerable ResolveReferences() { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } From 7e99738c2417f8af6957afebd414e57175408d2b Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 10 Apr 2022 18:17:26 -0400 Subject: [PATCH 037/855] Remove unnecessary reference that made netcoreapp2.1 incompatible --- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 7f3671942..4f7775d87 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -38,7 +38,6 @@ - From 85367f539870658015110f8d42f6f52a66a51d40 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 10 Apr 2022 20:12:20 -0400 Subject: [PATCH 038/855] Fixed resolveReference properly this time --- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 10 +++++++++- .../PublicApi/PublicApi.approved.txt | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 317cdab25..59b8da16c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -351,7 +351,15 @@ internal T ResolveReferenceTo(OpenApiReference reference) where T : class, IO /// /// Load the referenced object from a object /// - public IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) + public IOpenApiReferenceable ResolveReference(OpenApiReference reference) + { + return ResolveReference(reference, false); + } + + /// + /// Load the referenced object from a object + /// + internal IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) { if (reference == null) { diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 90e9d8f1a..e7ba33dca 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -508,7 +508,7 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IList Servers { get; set; } public System.Collections.Generic.IList Tags { get; set; } public Microsoft.OpenApi.Services.OpenApiWorkspace Workspace { get; set; } - public Microsoft.OpenApi.Interfaces.IOpenApiReferenceable ResolveReference(Microsoft.OpenApi.Models.OpenApiReference reference, bool useExternal) { } + public Microsoft.OpenApi.Interfaces.IOpenApiReferenceable ResolveReference(Microsoft.OpenApi.Models.OpenApiReference reference) { } public System.Collections.Generic.IEnumerable ResolveReferences() { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } From fce10efa2efa1917aeeeb7425c7588ef0c36fef4 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 11 Apr 2022 15:19:49 +0300 Subject: [PATCH 039/855] Update ci-build.yml for Azure Pipelines --- .azure-pipelines/ci-build.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 31af5bd24..1cb35abe1 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -270,11 +270,13 @@ stages: inputs: source: current - pwsh: | - $artifactName = Get-ChildItem -Path $(Pipeline.Workspace) -Filter Microsoft.OpenApi.Hidi-* -recurse | select -First 1 - $artifactVersion= $artifactName -replace "Microsoft.OpenApi.Hidi-", "" + $artifactName = Get-ChildItem -Path $(Pipeline.Workspace)\Nugets -Filter Microsoft.OpenApi.*.nupkg -recurse | select -First 1 + $artifactVersion= $artifactName -replace "Microsoft.OpenApi.", "" -replace ".nupkg", "" #Set Variable $artifactName and $artifactVersion Write-Host "##vso[task.setvariable variable=artifactVersion; isSecret=false; isOutput=true]$artifactVersion" Write-Host "##vso[task.setvariable variable=artifactName; isSecret=false; isOutput=true]$artifactName.FullName" + echo $artifactName + echo $artifactVersion displayName: 'Fetch Artifact Name' - task: NuGetCommand@2 @@ -290,7 +292,7 @@ stages: gitHubConnection: 'Github-MaggieKimani1' tagSource: userSpecifiedTag tag: '$(artifactVersion)' - title: '$(artifactName)' + title: '$(artifactVersion)' releaseNotesSource: inline assets: '$(Pipeline.Workspace)\**\*.exe' changeLogType: issueBased From 2fa91a81bc01bfeac0e66e3fa0b76f2852f6ffbf Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 11 Apr 2022 15:50:23 +0300 Subject: [PATCH 040/855] Update ci-build.yml for Azure Pipelines --- .azure-pipelines/ci-build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 1cb35abe1..9c163ea17 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -275,8 +275,8 @@ stages: #Set Variable $artifactName and $artifactVersion Write-Host "##vso[task.setvariable variable=artifactVersion; isSecret=false; isOutput=true]$artifactVersion" Write-Host "##vso[task.setvariable variable=artifactName; isSecret=false; isOutput=true]$artifactName.FullName" - echo $artifactName - echo $artifactVersion + echo "$artifactName" + echo "$artifactVersion" displayName: 'Fetch Artifact Name' - task: NuGetCommand@2 From 27dd1e9b0fcc73ee1bbcd28efbe060a104014967 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 11 Apr 2022 15:59:38 +0300 Subject: [PATCH 041/855] Update ci-build.yml for Azure Pipelines --- .azure-pipelines/ci-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 9c163ea17..616776585 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -271,7 +271,7 @@ stages: source: current - pwsh: | $artifactName = Get-ChildItem -Path $(Pipeline.Workspace)\Nugets -Filter Microsoft.OpenApi.*.nupkg -recurse | select -First 1 - $artifactVersion= $artifactName -replace "Microsoft.OpenApi.", "" -replace ".nupkg", "" + $artifactVersion= $artifactName.Name -replace "Microsoft.OpenApi.", "" -replace ".nupkg", "" #Set Variable $artifactName and $artifactVersion Write-Host "##vso[task.setvariable variable=artifactVersion; isSecret=false; isOutput=true]$artifactVersion" Write-Host "##vso[task.setvariable variable=artifactName; isSecret=false; isOutput=true]$artifactName.FullName" From 274acb583a7d04f90ae66410ef0fdbd967e745d7 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 11 Apr 2022 22:45:23 -0400 Subject: [PATCH 042/855] Updated version numbers --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 72ec16c0b..52d0b3c1e 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 0.5.0-preview6 + 1.0.0-preview1 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 62da19f40..440180d88 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.3.1-preview6 + 1.3.1 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 8c699e023..cbdcde393 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.3.1-preview6 + 1.3.1 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 2c64dad7e22336720bae38a226bc3e4d8510aadf Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 13 Apr 2022 11:45:59 +0300 Subject: [PATCH 043/855] Add an optional --terse output commandline option --- src/Microsoft.OpenApi.Hidi/Program.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 8b466913c..6d06a6986 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -39,6 +39,9 @@ static async Task Main(string[] args) var formatOption = new Option("--format", "File format"); formatOption.AddAlias("-f"); + var terseOutputOption = new Option("--terseOutput", "Produce terse json output"); + terseOutputOption.AddAlias("-to"); + var logLevelOption = new Option("--loglevel", () => LogLevel.Information, "The log level to use when logging messages to the main output."); logLevelOption.AddAlias("-ll"); @@ -74,6 +77,7 @@ static async Task Main(string[] args) cleanOutputOption, versionOption, formatOption, + terseOutputOption, logLevelOption, filterByOperationIdsOption, filterByTagsOption, @@ -82,8 +86,8 @@ static async Task Main(string[] args) inlineExternalOption }; - transformCommand.SetHandler ( - OpenApiService.TransformOpenApiDocument, descriptionOption, csdlOption, csdlFilterOption, outputOption, cleanOutputOption, versionOption, formatOption, logLevelOption, inlineLocalOption, inlineExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption); + transformCommand.SetHandler ( + OpenApiService.TransformOpenApiDocument, descriptionOption, csdlOption, csdlFilterOption, outputOption, cleanOutputOption, versionOption, formatOption, terseOutputOption, logLevelOption, inlineLocalOption, inlineExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption); rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); From 2bf6b366afb4d3eb488bc2ceb6b8ac026ee63824 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 13 Apr 2022 11:46:52 +0300 Subject: [PATCH 044/855] Add a terse object to the OpenApiWriterSettings --- src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs index 458d8f4a3..05237bc47 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs @@ -69,6 +69,11 @@ public ReferenceInlineSetting ReferenceInline { /// public bool InlineExternalReferences { get; set; } = false; + /// + /// Indicates whether or not the produced document will be written in a compact or pretty fashion. + /// + public bool Terse { get; set; } = false; + internal bool ShouldInlineReference(OpenApiReference reference) { From afba9d87050ffd67722f755a0ce2d7b23362a747 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 13 Apr 2022 11:47:57 +0300 Subject: [PATCH 045/855] Pass the terseOutput option provided to the OpenApiWriter settings for serializing JSON in a terse format --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 11 +++++++---- src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs | 1 + 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index feb62042b..3a333b89f 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -44,6 +44,7 @@ public static async Task TransformOpenApiDocument( bool cleanoutput, string? version, OpenApiFormat? format, + bool terseOutput, LogLevel loglevel, bool inlineLocal, bool inlineExternal, @@ -188,11 +189,13 @@ CancellationToken cancellationToken using var outputStream = output?.Create(); var textWriter = outputStream != null ? new StreamWriter(outputStream) : Console.Out; - var settings = new OpenApiWriterSettings() + var settings = new OpenApiWriterSettings(); + if (terseOutput) { - InlineLocalReferences = inlineLocal, - InlineExternalReferences = inlineExternal - }; + settings.Terse = terseOutput; + } + settings.InlineLocalReferences = inlineLocal; + settings.InlineExternalReferences = inlineExternal; IOpenApiWriter writer = openApiFormat switch { diff --git a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs index 5454e8da8..7c786fccb 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs @@ -35,6 +35,7 @@ public OpenApiJsonWriter(TextWriter textWriter, OpenApiJsonWriterSettings settin /// Settings for controlling how the OpenAPI document will be written out. public OpenApiJsonWriter(TextWriter textWriter, OpenApiWriterSettings settings) : base(textWriter, settings) { + _produceTerseOutput = settings.Terse; } /// From de72343b31fb5cd9f4e959ef7f745d5c6bb1710f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 13 Apr 2022 11:49:52 +0300 Subject: [PATCH 046/855] Update the command format to kebab case --- src/Microsoft.OpenApi.Hidi/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 6d06a6986..80a4c2e14 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -39,7 +39,7 @@ static async Task Main(string[] args) var formatOption = new Option("--format", "File format"); formatOption.AddAlias("-f"); - var terseOutputOption = new Option("--terseOutput", "Produce terse json output"); + var terseOutputOption = new Option("--terse-output", "Produce terse json output"); terseOutputOption.AddAlias("-to"); var logLevelOption = new Option("--loglevel", () => LogLevel.Information, "The log level to use when logging messages to the main output."); From 11c346692fff56d10e6ec76536452e60fa494100 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 14 Apr 2022 13:57:27 +0300 Subject: [PATCH 047/855] Add check to prevent null reference exceptions when settings are null --- src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs index 7c786fccb..41712636b 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs @@ -35,7 +35,10 @@ public OpenApiJsonWriter(TextWriter textWriter, OpenApiJsonWriterSettings settin /// Settings for controlling how the OpenAPI document will be written out. public OpenApiJsonWriter(TextWriter textWriter, OpenApiWriterSettings settings) : base(textWriter, settings) { - _produceTerseOutput = settings.Terse; + if (settings != null) + { + _produceTerseOutput = settings.Terse; + } } /// From 41c198338fecfac12eefc50c15c9670df4ce6f44 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 14 Apr 2022 13:57:47 +0300 Subject: [PATCH 048/855] Update public api interface --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index f589fa032..cadd68963 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1297,7 +1297,7 @@ namespace Microsoft.OpenApi.Writers public class OpenApiJsonWriterSettings : Microsoft.OpenApi.Writers.OpenApiWriterSettings { public OpenApiJsonWriterSettings() { } - public bool Terse { get; set; } + public new bool Terse { get; set; } } public static class OpenApiWriterAnyExtensions { @@ -1379,6 +1379,7 @@ namespace Microsoft.OpenApi.Writers public bool InlineLocalReferences { get; set; } [System.Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] public Microsoft.OpenApi.Writers.ReferenceInlineSetting ReferenceInline { get; set; } + public bool Terse { get; set; } } public class OpenApiYamlWriter : Microsoft.OpenApi.Writers.OpenApiWriterBase { From 540b624a8efa0c93052ac0e37307dae739b7a5d0 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 14 Apr 2022 17:52:07 +0300 Subject: [PATCH 049/855] Add a terseOutput parameter to the OpenApiJsonWriter and refactor code --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 12 +++++------- .../OpenApiSerializableExtensions.cs | 18 ++++++------------ .../Writers/OpenApiJsonWriter.cs | 8 +++----- 3 files changed, 14 insertions(+), 24 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 3a333b89f..584087ea7 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -189,17 +189,15 @@ CancellationToken cancellationToken using var outputStream = output?.Create(); var textWriter = outputStream != null ? new StreamWriter(outputStream) : Console.Out; - var settings = new OpenApiWriterSettings(); - if (terseOutput) + var settings = new OpenApiWriterSettings() { - settings.Terse = terseOutput; - } - settings.InlineLocalReferences = inlineLocal; - settings.InlineExternalReferences = inlineExternal; + InlineLocalReferences = inlineLocal, + InlineExternalReferences = inlineExternal + }; IOpenApiWriter writer = openApiFormat switch { - OpenApiFormat.Json => new OpenApiJsonWriter(textWriter, settings), + OpenApiFormat.Json => terseOutput ? new OpenApiJsonWriter(textWriter, settings, terseOutput) : new OpenApiJsonWriter(textWriter, settings, false), OpenApiFormat.Yaml => new OpenApiYamlWriter(textWriter, settings), _ => throw new ArgumentException("Unknown format"), }; diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs index 4694692ad..f60c5483b 100755 --- a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs @@ -83,20 +83,14 @@ public static void Serialize( throw Error.ArgumentNull(nameof(stream)); } - IOpenApiWriter writer; var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); - switch (format) - { - case OpenApiFormat.Json: - writer = new OpenApiJsonWriter(streamWriter,settings); - break; - case OpenApiFormat.Yaml: - writer = new OpenApiYamlWriter(streamWriter, settings); - break; - default: - throw new OpenApiException(string.Format(SRResource.OpenApiFormatNotSupported, format)); - } + IOpenApiWriter writer = format switch + { + OpenApiFormat.Json => new OpenApiJsonWriter(streamWriter, settings, false), + OpenApiFormat.Yaml => new OpenApiYamlWriter(streamWriter, settings), + _ => throw new OpenApiException(string.Format(SRResource.OpenApiFormatNotSupported, format)), + }; element.Serialize(writer, specVersion); } diff --git a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs index 41712636b..10049974b 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs @@ -33,12 +33,10 @@ public OpenApiJsonWriter(TextWriter textWriter, OpenApiJsonWriterSettings settin /// /// The text writer. /// Settings for controlling how the OpenAPI document will be written out. - public OpenApiJsonWriter(TextWriter textWriter, OpenApiWriterSettings settings) : base(textWriter, settings) + /// Setting for allowing the JSON emitted to be in terse format. + public OpenApiJsonWriter(TextWriter textWriter, OpenApiWriterSettings settings, bool terseOutput = false) : base(textWriter, settings) { - if (settings != null) - { - _produceTerseOutput = settings.Terse; - } + _produceTerseOutput = terseOutput; } /// From 13e888881c627e8d512ee6e72a7af54941ade424 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 14 Apr 2022 17:55:06 +0300 Subject: [PATCH 050/855] Clean up --- src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs | 6 ------ .../PublicApi/PublicApi.approved.txt | 5 ++--- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs index 05237bc47..cf00c1339 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs @@ -69,12 +69,6 @@ public ReferenceInlineSetting ReferenceInline { /// public bool InlineExternalReferences { get; set; } = false; - /// - /// Indicates whether or not the produced document will be written in a compact or pretty fashion. - /// - public bool Terse { get; set; } = false; - - internal bool ShouldInlineReference(OpenApiReference reference) { return (reference.IsLocal && InlineLocalReferences) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index cadd68963..02400ddd7 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1281,7 +1281,7 @@ namespace Microsoft.OpenApi.Writers { public OpenApiJsonWriter(System.IO.TextWriter textWriter) { } public OpenApiJsonWriter(System.IO.TextWriter textWriter, Microsoft.OpenApi.Writers.OpenApiJsonWriterSettings settings) { } - public OpenApiJsonWriter(System.IO.TextWriter textWriter, Microsoft.OpenApi.Writers.OpenApiWriterSettings settings) { } + public OpenApiJsonWriter(System.IO.TextWriter textWriter, Microsoft.OpenApi.Writers.OpenApiWriterSettings settings, bool terseOutput = false) { } protected override int BaseIndentation { get; } public override void WriteEndArray() { } public override void WriteEndObject() { } @@ -1297,7 +1297,7 @@ namespace Microsoft.OpenApi.Writers public class OpenApiJsonWriterSettings : Microsoft.OpenApi.Writers.OpenApiWriterSettings { public OpenApiJsonWriterSettings() { } - public new bool Terse { get; set; } + public bool Terse { get; set; } } public static class OpenApiWriterAnyExtensions { @@ -1379,7 +1379,6 @@ namespace Microsoft.OpenApi.Writers public bool InlineLocalReferences { get; set; } [System.Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] public Microsoft.OpenApi.Writers.ReferenceInlineSetting ReferenceInline { get; set; } - public bool Terse { get; set; } } public class OpenApiYamlWriter : Microsoft.OpenApi.Writers.OpenApiWriterBase { From 1a63ab8816e525dc3dee4641c1ebc399e7b2b684 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Apr 2022 21:07:40 +0000 Subject: [PATCH 051/855] Bump github/codeql-action from 1 to 2 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 1 to 2. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/v1...v2) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/codeql-analysis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 0adca3d2d..8b965b442 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -23,7 +23,7 @@ jobs: - name: Initialize CodeQL id: init_codeql - uses: github/codeql-action/init@v1 + uses: github/codeql-action/init@v2 with: queries: security-and-quality @@ -43,6 +43,6 @@ jobs: - name: Perform CodeQL Analysis id: analyze_codeql - uses: github/codeql-action/analyze@v1 + uses: github/codeql-action/analyze@v2 # Built with ❤ by [Pipeline Foundation](https://pipeline.foundation) \ No newline at end of file From 4d256e5bcb32f431b3c86ef018807a1a169441d7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 29 Apr 2022 21:08:34 +0000 Subject: [PATCH 052/855] Bump Verify from 16.5.4 to 16.7.0 Bumps [Verify](https://github.com/VerifyTests/Verify) from 16.5.4 to 16.7.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits/16.7.0) --- updated-dependencies: - dependency-name: Verify dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 39026a9f7..1917b440d 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + From 8f527084b6af5fa44d1b95f346847c7d4a20651a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 May 2022 21:07:33 +0000 Subject: [PATCH 053/855] Bump Microsoft.OpenApi.OData from 1.0.10-preview3 to 1.0.10 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.0.10-preview3 to 1.0.10. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 52d0b3c1e..b03eb46c8 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -46,7 +46,7 @@ - + From b0bf2ae84d9a846bf94e9780e253aa42139feae7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 May 2022 11:15:35 +0300 Subject: [PATCH 054/855] Adds a copy constructor for all models and cleans up code --- .../Models/OpenApiCallback.cs | 16 ++++++ .../Models/OpenApiComponents.cs | 22 ++++++++ .../Models/OpenApiContact.cs | 16 ++++++ .../Models/OpenApiDiscriminator.cs | 14 ++++++ .../Models/OpenApiDocument.cs | 23 ++++++++- .../Models/OpenApiEncoding.cs | 18 +++++++ src/Microsoft.OpenApi/Models/OpenApiError.cs | 9 ++++ .../Models/OpenApiExample.cs | 19 +++++++ .../Models/OpenApiExternalDocs.cs | 15 ++++++ src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 26 ++++++++++ src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 19 +++++++ .../Models/OpenApiLicense.cs | 15 ++++++ src/Microsoft.OpenApi/Models/OpenApiLink.cs | 21 ++++++++ .../Models/OpenApiMediaType.cs | 17 +++++++ .../Models/OpenApiOAuthFlow.cs | 17 +++++++ .../Models/OpenApiOAuthFlows.cs | 18 +++++++ .../Models/OpenApiOperation.cs | 25 ++++++++++ .../Models/OpenApiParameter.cs | 28 +++++++++++ .../Models/OpenApiPathItem.cs | 20 ++++++++ .../Models/OpenApiReference.cs | 16 ++++++ .../Models/OpenApiRequestBody.cs | 18 +++++++ .../Models/OpenApiResponse.cs | 19 +++++++ src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 50 +++++++++++++++++++ .../Models/OpenApiSecurityScheme.cs | 23 +++++++++ src/Microsoft.OpenApi/Models/OpenApiServer.cs | 16 ++++++ .../Models/OpenApiServerVariable.cs | 16 ++++++ src/Microsoft.OpenApi/Models/OpenApiTag.cs | 18 +++++++ src/Microsoft.OpenApi/Models/OpenApiXml.cs | 18 +++++++ .../V2Tests/OpenApiDocumentTests.cs | 9 ---- 29 files changed, 550 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index 57aa3c888..57bdc3b73 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -35,6 +35,22 @@ public class OpenApiCallback : IOpenApiSerializable, IOpenApiReferenceable, IOpe /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiCallback() { } + + /// + /// Initializes a copy of an object + /// + public OpenApiCallback(OpenApiCallback callback) + { + PathItems = callback.PathItems; + UnresolvedReference = callback.UnresolvedReference; + Reference = callback.Reference; + Extensions = callback.Extensions; + } + /// /// Add a into the . /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index cd8cdae74..176f1277f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -68,6 +68,28 @@ public class OpenApiComponents : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiComponents() { } + + /// + /// Initializes a copy of an object + /// + public OpenApiComponents(OpenApiComponents components) + { + Schemas = components.Schemas; + Responses = components.Responses; + Parameters = components.Parameters; + Examples = components.Examples; + RequestBodies = components.RequestBodies; + Headers = components.Headers; + SecuritySchemes = components.SecuritySchemes; + Links = components.Links; + Callbacks = components.Callbacks; + Extensions = components.Extensions; + } + /// /// Serialize to Open Api v3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 848560ead..c26e6512b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -35,6 +35,22 @@ public class OpenApiContact : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiContact() { } + + /// + /// Initializes a copy of an instance + /// + public OpenApiContact(OpenApiContact contact) + { + Name = contact.Name; + Url = contact.Url; + Email = contact.Email; + Extensions = contact.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs index a0739dc25..b8caf54bb 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs @@ -22,6 +22,20 @@ public class OpenApiDiscriminator : IOpenApiSerializable /// public IDictionary Mapping { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiDiscriminator() { } + + /// + /// Initializes a copy of an instance + /// + public OpenApiDiscriminator(OpenApiDiscriminator discriminator) + { + PropertyName = discriminator.PropertyName; + Mapping = discriminator.Mapping; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 59b8da16c..e8ad85c81 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Runtime.CompilerServices; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Services; @@ -64,6 +62,27 @@ public class OpenApiDocument : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiDocument() {} + + /// + /// Initializes a copy of an an object + /// + public OpenApiDocument(OpenApiDocument document) + { + Workspace = document.Workspace; + Info = document.Info; + Servers = document.Servers; + Paths = document.Paths; + Components = document.Components; + SecurityRequirements = document.SecurityRequirements; + Tags = document.Tags; + ExternalDocs = document.ExternalDocs; + Extensions = document.Extensions; + } + /// /// Serialize to the latest patch of OpenAPI object V3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index 0d02c384e..0757c5f8d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -53,6 +53,24 @@ public class OpenApiEncoding : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiEncoding() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiEncoding(OpenApiEncoding encoding) + { + ContentType = encoding.ContentType; + Headers = encoding.Headers; + Style = encoding.Style; + Explode = encoding.Explode; + AllowReserved = encoding.AllowReserved; + Extensions = encoding.Extensions; + } + /// /// Serialize to Open Api v3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiError.cs b/src/Microsoft.OpenApi/Models/OpenApiError.cs index 98bf7ec82..82f2a14df 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiError.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiError.cs @@ -26,6 +26,15 @@ public OpenApiError(string pointer, string message) Message = message; } + /// + /// Initializes a copy of an object + /// + public OpenApiError(OpenApiError error) + { + Pointer = error.Pointer; + Message = error.Message; + } + /// /// Message explaining the error. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index d4c268584..2da67941f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -54,6 +54,25 @@ public class OpenApiExample : IOpenApiSerializable, IOpenApiReferenceable, IOpen /// public bool UnresolvedReference { get; set; } = false; + /// + /// Parameter-less constructor + /// + public OpenApiExample() {} + + /// + /// Initializes a copy of object + /// + public OpenApiExample(OpenApiExample example) + { + Summary = example.Summary; + Description = example.Description; + Value = example.Value; + ExternalValue = example.ExternalValue; + Extensions = example.Extensions; + Reference = example.Reference; + UnresolvedReference = example.UnresolvedReference; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index a47fb9906..412d773bb 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -29,6 +29,21 @@ public class OpenApiExternalDocs : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiExternalDocs() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) + { + Description = externalDocs.Description; + Url = externalDocs.Url; + Extensions = externalDocs.Extensions; + } + /// /// Serialize to Open Api v3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index e8576a0ca..ed782e7fd 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -86,6 +86,32 @@ public class OpenApiHeader : IOpenApiSerializable, IOpenApiReferenceable, IOpenA /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiHeader() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiHeader(OpenApiHeader header) + { + UnresolvedReference = header.UnresolvedReference; + Reference = header.Reference; + Description = header.Description; + Required = header.Required; + Deprecated = header.Deprecated; + AllowEmptyValue = header.AllowEmptyValue; + Style = header.Style; + Explode = header.Explode; + AllowReserved = header.AllowReserved; + Schema = header.Schema; + Example = header.Example; + Examples = header.Examples; + Content = header.Content; + Extensions = header.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index 17364ba3b..84bb63a3e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -49,6 +49,25 @@ public class OpenApiInfo : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiInfo() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiInfo(OpenApiInfo info) + { + Title = info.Title; + Description = info.Description; + Version = info.Version; + TermsOfService = info.TermsOfService; + Contact = info.Contact; + License = info.License; + Extensions = info.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 0de7540c8..eb4ce5e02 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -29,6 +29,21 @@ public class OpenApiLicense : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameterless constructor + /// + public OpenApiLicense() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiLicense(OpenApiLicense license) + { + Name = license.Name; + Url = license.Url; + Extensions = license.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index f5acb0d3f..68a8aa9fd 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -61,6 +61,27 @@ public class OpenApiLink : IOpenApiSerializable, IOpenApiReferenceable, IOpenApi /// public OpenApiReference Reference { get; set; } + /// + /// Parameterless constructor + /// + public OpenApiLink() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiLink(OpenApiLink link) + { + OperationRef = link.OperationRef; + OperationId = link.OperationId; + Parameters = link.Parameters; + RequestBody = link.RequestBody; + Description = link.Description; + Server = link.Server; + Extensions = link.Extensions; + UnresolvedReference = link.UnresolvedReference; + Reference = link.Reference; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 414f46b30..0982800e2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -43,6 +43,23 @@ public class OpenApiMediaType : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameterless constructor + /// + public OpenApiMediaType() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiMediaType(OpenApiMediaType mediaType) + { + Schema = mediaType.Schema; + Example = mediaType.Example; + Examples = mediaType.Examples; + Encoding = mediaType.Encoding; + Extensions = mediaType.Extensions; + } + /// /// Serialize to Open Api v3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index e478944aa..a69562207 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -41,6 +41,23 @@ public class OpenApiOAuthFlow : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameterless constructor + /// + public OpenApiOAuthFlow() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) + { + AuthorizationUrl = oAuthFlow.AuthorizationUrl; + TokenUrl = oAuthFlow.TokenUrl; + RefreshUrl = oAuthFlow.RefreshUrl; + Scopes = oAuthFlow.Scopes; + Extensions = oAuthFlow.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index fa2db10db..f16afa961 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -38,6 +38,24 @@ public class OpenApiOAuthFlows : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameterless constructor + /// + public OpenApiOAuthFlows() {} + + /// + /// Initializes a copy of an object + /// + /// + public OpenApiOAuthFlows(OpenApiOAuthFlows oAuthFlows) + { + Implicit = oAuthFlows.Implicit; + Password = oAuthFlows.Password; + ClientCredentials = oAuthFlows.ClientCredentials; + AuthorizationCode = oAuthFlows.AuthorizationCode; + Extensions = oAuthFlows.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index f17f81328..f56674261 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -106,6 +106,31 @@ public class OpenApiOperation : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameterless constructor + /// + public OpenApiOperation() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiOperation(OpenApiOperation operation) + { + Tags = operation.Tags; + Summary = operation.Summary; + Description = operation.Description; + ExternalDocs = operation.ExternalDocs; + OperationId = operation.OperationId; + Parameters = operation.Parameters; + RequestBody = operation.RequestBody; + Responses = operation.Responses; + Callbacks = operation.Callbacks; + Deprecated = operation.Deprecated; + Security = operation.Security; + Servers = operation.Servers; + Extensions = operation.Extensions; + } + /// /// Serialize to Open Api v3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 12f37f61a..c1946ab35 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -136,6 +136,34 @@ public bool Explode /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// A parameterless constructor + /// + public OpenApiParameter() {} + + /// + /// Initializes a clone instance of object + /// + public OpenApiParameter(OpenApiParameter parameter) + { + UnresolvedReference = parameter.UnresolvedReference; + Reference = parameter.Reference; + Name = parameter.Name; + In = parameter.In; + Description = parameter.Description; + Required = parameter.Required; + Style = parameter.Style; + Explode = parameter.Explode; + AllowReserved = parameter.AllowReserved; + Schema = parameter.Schema; + Examples = parameter.Examples; + Example = parameter.Example; + Content = parameter.Content; + Extensions = parameter.Extensions; + AllowEmptyValue = parameter.AllowEmptyValue; + Deprecated = parameter.Deprecated; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index 375f1f034..cc824b184 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -65,6 +65,26 @@ public void AddOperation(OperationType operationType, OpenApiOperation operation Operations[operationType] = operation; } + /// + /// Parameterless constructor + /// + public OpenApiPathItem() {} + + /// + /// Initializes a clone of an object + /// + public OpenApiPathItem(OpenApiPathItem pathItem) + { + Summary = pathItem.Summary; + Description = pathItem.Description; + Operations = pathItem.Operations; + Servers = pathItem.Servers; + Parameters = pathItem.Parameters; + Extensions = pathItem.Extensions; + UnresolvedReference = pathItem.UnresolvedReference; + Reference = pathItem.Reference; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index 3f1370800..93cc0578f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -112,6 +112,22 @@ public string ReferenceV2 } } + /// + /// Parameterless constructor + /// + public OpenApiReference() {} + + /// + /// Initializes a copy instance of the object + /// + public OpenApiReference(OpenApiReference reference) + { + ExternalResource = reference.ExternalResource; + Type = reference.Type; + Id = reference.Id; + HostDocument = reference.HostDocument; + } + /// /// Serialize to Open Api v3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 8a65f1fde..9ee0d5247 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -45,6 +45,24 @@ public class OpenApiRequestBody : IOpenApiSerializable, IOpenApiReferenceable, I /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameter-less constructor + /// + public OpenApiRequestBody() { } + + /// + /// Initializes a copy instance of an object + /// + public OpenApiRequestBody(OpenApiRequestBody requestBody) + { + UnresolvedReference = requestBody.UnresolvedReference; + Reference = requestBody.Reference; + Description = requestBody.Description; + Required = requestBody.Required; + Content = requestBody.Content; + Extensions = requestBody.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index 0a31ca0a4..637e23835 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -51,6 +51,25 @@ public class OpenApiResponse : IOpenApiSerializable, IOpenApiReferenceable, IOpe /// public OpenApiReference Reference { get; set; } + /// + /// Parameterless constructor + /// + public OpenApiResponse() {} + + /// + /// Initializes a copy of object + /// + public OpenApiResponse(OpenApiResponse response) + { + Description = response.Description; + Headers = response.Headers; + Content = response.Content; + Links = response.Links; + Extensions = response.Extensions; + UnresolvedReference = response.UnresolvedReference; + Reference = response.Reference; + } + /// /// Serialize to Open Api v3.0. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 036222261..6934f2eda 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -242,6 +242,56 @@ public class OpenApiSchema : IOpenApiSerializable, IOpenApiReferenceable, IEffec /// public OpenApiReference Reference { get; set; } + /// + /// Parameterless constructor + /// + public OpenApiSchema() {} + + /// + /// Initializes a copy of object + /// + public OpenApiSchema(OpenApiSchema schema) + { + Title = schema.Title; + Type = schema.Type; + Format = schema.Format; + Description = schema.Description; + Maximum = schema.Maximum; + ExclusiveMaximum = schema.ExclusiveMaximum; + Minimum = schema.Minimum; + ExclusiveMinimum = schema.ExclusiveMinimum; + MaxLength = schema.MaxLength; + MinLength = schema.MinLength; + Pattern = schema.Pattern; + MultipleOf = schema.MultipleOf; + Default = schema.Default; + ReadOnly = schema.ReadOnly; + WriteOnly = schema.WriteOnly; + AllOf = schema.AllOf; + OneOf = schema.OneOf; + AnyOf = schema.AnyOf; + Not = schema.Not; + Required = schema.Required; + Items = schema.Items; + MaxItems = schema.MaxItems; + MinItems = schema.MinItems; + UniqueItems = schema.UniqueItems; + Properties = schema.Properties; + MaxProperties = schema.MaxProperties; + MinProperties = schema.MinProperties; + AdditionalPropertiesAllowed = schema.AdditionalPropertiesAllowed; + AdditionalProperties = schema.AdditionalProperties; + Discriminator = schema.Discriminator; + Example = schema.Example; + Enum = schema.Enum; + Nullable = schema.Nullable; + ExternalDocs = schema.ExternalDocs; + Deprecated = schema.Deprecated; + Xml = schema.Xml; + UnresolvedReference = schema.UnresolvedReference; + Reference = schema.Reference; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 902ce19bc..eaba8b40d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -74,6 +74,29 @@ public class OpenApiSecurityScheme : IOpenApiSerializable, IOpenApiReferenceable /// public OpenApiReference Reference { get; set; } + /// + /// Parameterless constructor + /// + public OpenApiSecurityScheme() {} + + /// + /// Initializes a copy of object + /// + public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) + { + Type = securityScheme.Type; + Description = securityScheme.Description; + Name = securityScheme.Name; + In = securityScheme.In; + Scheme = securityScheme.Scheme; + BearerFormat = securityScheme.BearerFormat; + Flows = securityScheme.Flows; + OpenIdConnectUrl = securityScheme.OpenIdConnectUrl; + Extensions = securityScheme.Extensions; + UnresolvedReference = securityScheme.UnresolvedReference; + Reference = securityScheme.Reference; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index ea988ec13..0ae3f83e9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -36,6 +36,22 @@ public class OpenApiServer : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameterless constructor + /// + public OpenApiServer() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiServer(OpenApiServer server) + { + Description = server.Description; + Url = server.Url; + Variables = server.Variables; + Extensions = server.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index 8ae39a04c..8813ab69b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -34,6 +34,22 @@ public class OpenApiServerVariable : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameterless constructor + /// + public OpenApiServerVariable() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiServerVariable(OpenApiServerVariable serverVariable) + { + Description = serverVariable.Description; + Default = serverVariable.Default; + Enum = serverVariable.Enum; + Extensions = serverVariable.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index 4d743a13a..ed6f916b5 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -43,6 +43,24 @@ public class OpenApiTag : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiE /// public OpenApiReference Reference { get; set; } + /// + /// Parameterless constructor + /// + public OpenApiTag() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiTag(OpenApiTag tag) + { + Name = tag.Name; + Description = tag.Description; + ExternalDocs = tag.ExternalDocs; + Extensions = tag.Extensions; + UnresolvedReference = tag.UnresolvedReference; + Reference = tag.Reference; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index 59218970f..70e438b1c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -46,6 +46,24 @@ public class OpenApiXml : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// Parameterless constructor + /// + public OpenApiXml() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiXml(OpenApiXml xml) + { + Name = xml.Name; + Namespace = xml.Namespace; + Prefix = xml.Prefix; + Attribute = xml.Attribute; + Wrapped = xml.Wrapped; + Extensions = xml.Extensions; + } + /// /// Serialize to Open Api v3.0 /// diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index 57593a79e..39bc0db80 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -174,15 +174,6 @@ public void ShouldParseProducesInAnyOrder() }, Items = new OpenApiSchema() { - //Properties = new Dictionary() - // { - // { "id", new OpenApiSchema() - // { - // Type = "string", - // Description = "Item identifier." - // } - // } - // }, Reference = new OpenApiReference() { Type = ReferenceType.Schema, From c61e1cbf8cb8315c3901d56eb2bf090b87a12209 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 May 2022 12:39:52 +0300 Subject: [PATCH 055/855] Update public Api interface --- .../PublicApi/PublicApi.approved.txt | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 02400ddd7..f753292e1 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -323,6 +323,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiCallback : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiCallback() { } + public OpenApiCallback(Microsoft.OpenApi.Models.OpenApiCallback callback) { } public System.Collections.Generic.IDictionary Extensions { get; set; } public System.Collections.Generic.Dictionary PathItems { get; set; } public Microsoft.OpenApi.Models.OpenApiReference Reference { get; set; } @@ -337,6 +338,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiComponents : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiComponents() { } + public OpenApiComponents(Microsoft.OpenApi.Models.OpenApiComponents components) { } public System.Collections.Generic.IDictionary Callbacks { get; set; } public System.Collections.Generic.IDictionary Examples { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } @@ -481,6 +483,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiContact : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiContact() { } + public OpenApiContact(Microsoft.OpenApi.Models.OpenApiContact contact) { } public string Email { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public string Name { get; set; } @@ -491,6 +494,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiDiscriminator : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiDiscriminator() { } + public OpenApiDiscriminator(Microsoft.OpenApi.Models.OpenApiDiscriminator discriminator) { } public System.Collections.Generic.IDictionary Mapping { get; set; } public string PropertyName { get; set; } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -499,6 +503,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiDocument : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiDocument() { } + public OpenApiDocument(Microsoft.OpenApi.Models.OpenApiDocument document) { } public Microsoft.OpenApi.Models.OpenApiComponents Components { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public Microsoft.OpenApi.Models.OpenApiExternalDocs ExternalDocs { get; set; } @@ -516,6 +521,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiEncoding : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiEncoding() { } + public OpenApiEncoding(Microsoft.OpenApi.Models.OpenApiEncoding encoding) { } public bool? AllowReserved { get; set; } public string ContentType { get; set; } public bool? Explode { get; set; } @@ -528,6 +534,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiError { public OpenApiError(Microsoft.OpenApi.Exceptions.OpenApiException exception) { } + public OpenApiError(Microsoft.OpenApi.Models.OpenApiError error) { } public OpenApiError(string pointer, string message) { } public string Message { get; set; } public string Pointer { get; set; } @@ -536,6 +543,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiExample : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiExample() { } + public OpenApiExample(Microsoft.OpenApi.Models.OpenApiExample example) { } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public string ExternalValue { get; set; } @@ -560,6 +568,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiExternalDocs : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiExternalDocs() { } + public OpenApiExternalDocs(Microsoft.OpenApi.Models.OpenApiExternalDocs externalDocs) { } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public System.Uri Url { get; set; } @@ -569,6 +578,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiHeader : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiHeader() { } + public OpenApiHeader(Microsoft.OpenApi.Models.OpenApiHeader header) { } public bool AllowEmptyValue { get; set; } public bool AllowReserved { get; set; } public System.Collections.Generic.IDictionary Content { get; set; } @@ -592,6 +602,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiInfo : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiInfo() { } + public OpenApiInfo(Microsoft.OpenApi.Models.OpenApiInfo info) { } public Microsoft.OpenApi.Models.OpenApiContact Contact { get; set; } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } @@ -605,6 +616,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiLicense : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiLicense() { } + public OpenApiLicense(Microsoft.OpenApi.Models.OpenApiLicense license) { } public System.Collections.Generic.IDictionary Extensions { get; set; } public string Name { get; set; } public System.Uri Url { get; set; } @@ -614,6 +626,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiLink : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiLink() { } + public OpenApiLink(Microsoft.OpenApi.Models.OpenApiLink link) { } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public string OperationId { get; set; } @@ -632,6 +645,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiMediaType : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiMediaType() { } + public OpenApiMediaType(Microsoft.OpenApi.Models.OpenApiMediaType mediaType) { } public System.Collections.Generic.IDictionary Encoding { get; set; } public Microsoft.OpenApi.Any.IOpenApiAny Example { get; set; } public System.Collections.Generic.IDictionary Examples { get; set; } @@ -643,6 +657,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiOAuthFlow : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiOAuthFlow() { } + public OpenApiOAuthFlow(Microsoft.OpenApi.Models.OpenApiOAuthFlow oAuthFlow) { } public System.Uri AuthorizationUrl { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public System.Uri RefreshUrl { get; set; } @@ -654,6 +669,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiOAuthFlows : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiOAuthFlows() { } + public OpenApiOAuthFlows(Microsoft.OpenApi.Models.OpenApiOAuthFlows oAuthFlows) { } public Microsoft.OpenApi.Models.OpenApiOAuthFlow AuthorizationCode { get; set; } public Microsoft.OpenApi.Models.OpenApiOAuthFlow ClientCredentials { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } @@ -666,6 +682,7 @@ namespace Microsoft.OpenApi.Models { public const bool DeprecatedDefault = false; public OpenApiOperation() { } + public OpenApiOperation(Microsoft.OpenApi.Models.OpenApiOperation operation) { } public System.Collections.Generic.IDictionary Callbacks { get; set; } public bool Deprecated { get; set; } public string Description { get; set; } @@ -685,6 +702,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiParameter : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiParameter() { } + public OpenApiParameter(Microsoft.OpenApi.Models.OpenApiParameter parameter) { } public bool AllowEmptyValue { get; set; } public bool AllowReserved { get; set; } public System.Collections.Generic.IDictionary Content { get; set; } @@ -710,6 +728,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiPathItem : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiPathItem() { } + public OpenApiPathItem(Microsoft.OpenApi.Models.OpenApiPathItem pathItem) { } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public System.Collections.Generic.IDictionary Operations { get; set; } @@ -732,6 +751,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiReference : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiReference() { } + public OpenApiReference(Microsoft.OpenApi.Models.OpenApiReference reference) { } public string ExternalResource { get; set; } public Microsoft.OpenApi.Models.OpenApiDocument HostDocument { get; set; } public string Id { get; set; } @@ -746,6 +766,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiRequestBody : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiRequestBody() { } + public OpenApiRequestBody(Microsoft.OpenApi.Models.OpenApiRequestBody requestBody) { } public System.Collections.Generic.IDictionary Content { get; set; } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } @@ -761,6 +782,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiResponse : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiResponse() { } + public OpenApiResponse(Microsoft.OpenApi.Models.OpenApiResponse response) { } public System.Collections.Generic.IDictionary Content { get; set; } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } @@ -781,6 +803,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiSchema : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiSchema() { } + public OpenApiSchema(Microsoft.OpenApi.Models.OpenApiSchema schema) { } public Microsoft.OpenApi.Models.OpenApiSchema AdditionalProperties { get; set; } public bool AdditionalPropertiesAllowed { get; set; } public System.Collections.Generic.IList AllOf { get; set; } @@ -835,6 +858,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiSecurityScheme : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiSecurityScheme() { } + public OpenApiSecurityScheme(Microsoft.OpenApi.Models.OpenApiSecurityScheme securityScheme) { } public string BearerFormat { get; set; } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } @@ -854,6 +878,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiServer : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiServer() { } + public OpenApiServer(Microsoft.OpenApi.Models.OpenApiServer server) { } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public string Url { get; set; } @@ -864,6 +889,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiServerVariable : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiServerVariable() { } + public OpenApiServerVariable(Microsoft.OpenApi.Models.OpenApiServerVariable serverVariable) { } public string Default { get; set; } public string Description { get; set; } public System.Collections.Generic.List Enum { get; set; } @@ -874,6 +900,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiTag : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiTag() { } + public OpenApiTag(Microsoft.OpenApi.Models.OpenApiTag tag) { } public string Description { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public Microsoft.OpenApi.Models.OpenApiExternalDocs ExternalDocs { get; set; } @@ -888,6 +915,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiXml : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { public OpenApiXml() { } + public OpenApiXml(Microsoft.OpenApi.Models.OpenApiXml xml) { } public bool Attribute { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public string Name { get; set; } From 1fd8b8ec8109ce0655d9860c8fb036d29584c457 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 11 May 2022 13:58:44 +0000 Subject: [PATCH 056/855] Bump Microsoft.OData.Edm from 7.10.0 to 7.11.0 Bumps Microsoft.OData.Edm from 7.10.0 to 7.11.0. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index b03eb46c8..a5f3daf6c 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -45,7 +45,7 @@ - + From 731a2f43a9eaf481d9746ff38311a14516a135f1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 11 May 2022 13:59:59 +0000 Subject: [PATCH 057/855] Bump Verify.Xunit from 16.5.4 to 16.7.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 16.5.4 to 16.7.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits/16.7.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 1917b440d..16d26e1bd 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -21,7 +21,7 @@ - + all From 7ce406fb1ac8cd70cec074f7a47593821a204a17 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 11 May 2022 14:00:02 +0000 Subject: [PATCH 058/855] Bump xunit.runner.visualstudio from 2.4.3 to 2.4.5 Bumps [xunit.runner.visualstudio](https://github.com/xunit/visualstudio.xunit) from 2.4.3 to 2.4.5. - [Release notes](https://github.com/xunit/visualstudio.xunit/releases) - [Commits](https://github.com/xunit/visualstudio.xunit/commits) --- updated-dependencies: - dependency-name: xunit.runner.visualstudio dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index bfcba0163..eccb5f75a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -251,7 +251,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index aadfb919d..e56628d7c 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -11,7 +11,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 1917b440d..3f3092265 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -23,7 +23,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive From 3ce1566327481c64d7a6a0f2a392faf2c8651a70 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 11 May 2022 14:00:04 +0000 Subject: [PATCH 059/855] Bump SharpYaml from 1.9.0 to 1.9.1 Bumps [SharpYaml](https://github.com/xoofx/SharpYaml) from 1.9.0 to 1.9.1. - [Release notes](https://github.com/xoofx/SharpYaml/releases) - [Changelog](https://github.com/xoofx/SharpYaml/blob/master/changelog.md) - [Commits](https://github.com/xoofx/SharpYaml/compare/1.9.0...1.9.1) --- updated-dependencies: - dependency-name: SharpYaml dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 440180d88..b6d43cf4c 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -40,7 +40,7 @@ - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index bfcba0163..5f296636e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -247,7 +247,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 1917b440d..16fa8cd76 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -19,7 +19,7 @@ - + From 3b66e24e6034c097f5abc22323d13e49e856d605 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 11 May 2022 10:03:13 -0400 Subject: [PATCH 060/855] - bumps hidi version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index b03eb46c8..7fde25f88 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,14 +15,14 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview1 + 1.0.0-preview2 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET -- Upgrades Microsoft.OpenApi.OData to 1.0.10-preview1 -- Fixes an issue where hidi would not process async operations +- Upgrades Microsoft.OpenApi.OData to 1.0.10 +- Upgrades Microsoft.OData.Edm to 7.11.0 Microsoft.OpenApi.Hidi Microsoft.OpenApi.Hidi From 9ffaf1dbd61b0e41829996ae0f49e2eab513957c Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 May 2022 18:41:06 +0300 Subject: [PATCH 061/855] Update ci-build.yml for Azure Pipelines --- .azure-pipelines/ci-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 616776585..345d50af9 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -287,7 +287,7 @@ stages: nuGetFeedType: external publishFeedCredentials: 'OpenAPI Nuget Connection' - task: GitHubRelease@1 - displayName: 'GitHub release (create)' + displayName: 'GitHub release (edit)' inputs: gitHubConnection: 'Github-MaggieKimani1' tagSource: userSpecifiedTag From 2a22cd16b348440639463ac0a337eb80bbf50e5d Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Wed, 11 May 2022 16:38:18 -0400 Subject: [PATCH 062/855] Configure CSDL via settings --- .../Microsoft.OpenApi.Hidi.csproj | 1 + src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 47 ++++++++++++------- src/Microsoft.OpenApi.Hidi/Program.cs | 17 +++++++ 3 files changed, 49 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 52d0b3c1e..aaa081c05 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -47,6 +47,7 @@ + diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 584087ea7..4c24c0b4c 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -28,6 +28,7 @@ using System.Xml; using System.Runtime.CompilerServices; using System.Reflection; +using Microsoft.Extensions.Configuration; namespace Microsoft.OpenApi.Hidi { @@ -98,6 +99,7 @@ CancellationToken cancellationToken stream = ApplyFilter(csdl, csdlFilter, transform); stream.Position = 0; } + document = await ConvertCsdlToOpenApi(stream); stopwatch.Stop(); logger.LogTrace("{timestamp}ms: Generated OpenAPI with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); @@ -321,6 +323,14 @@ public static async Task ValidateOpenApiDocument( } + internal static IConfiguration GetConfiguration() + { + IConfiguration config = new ConfigurationBuilder() + .AddJsonFile("appsettings.json",true) + .Build(); + return config; + } + /// /// Converts CSDL to OpenAPI /// @@ -332,23 +342,28 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl) var csdlText = await reader.ReadToEndAsync(); var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader()); - var settings = new OpenApiConvertSettings() + var config = GetConfiguration(); + OpenApiConvertSettings settings = config.GetSection("OpenApiConvertSettings").Get(); + if (settings == null) { - AddSingleQuotesForStringParameters = true, - AddEnumDescriptionExtension = true, - DeclarePathParametersOnPathItem = true, - EnableKeyAsSegment = true, - EnableOperationId = true, - ErrorResponsesAsDefault = false, - PrefixEntityTypeNameBeforeKey = true, - TagDepth = 2, - EnablePagination = true, - EnableDiscriminatorValue = false, - EnableDerivedTypesReferencesForRequestBody = false, - EnableDerivedTypesReferencesForResponses = false, - ShowRootPath = false, - ShowLinks = false - }; + settings = new OpenApiConvertSettings() + { + AddSingleQuotesForStringParameters = true, + AddEnumDescriptionExtension = true, + DeclarePathParametersOnPathItem = true, + EnableKeyAsSegment = true, + EnableOperationId = true, + ErrorResponsesAsDefault = false, + PrefixEntityTypeNameBeforeKey = true, + TagDepth = 2, + EnablePagination = true, + EnableDiscriminatorValue = false, + EnableDerivedTypesReferencesForRequestBody = false, + EnableDerivedTypesReferencesForResponses = false, + ShowRootPath = false, + ShowLinks = false + }; + } OpenApiDocument document = edmModel.ConvertToOpenApi(settings); document = FixReferences(document); diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 80a4c2e14..09a9061ac 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -3,9 +3,15 @@ using System; using System.CommandLine; +using System.CommandLine.Builder; +using System.CommandLine.Hosting; +using System.CommandLine.Parsing; + using System.IO; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Microsoft.OpenApi.Hidi @@ -92,9 +98,20 @@ static async Task Main(string[] args) rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); + // Parse the incoming args and invoke the handler await rootCommand.InvokeAsync(args); + + //await new CommandLineBuilder(rootCommand) + // .UseHost(_ => Host.CreateDefaultBuilder(), + // host => { + // var config = host.Services.GetRequiredService(); + // }) + // .UseDefaults() + // .Build() + // .InvokeAsync(args); + //// Wait for logger to write messages to the console before exiting await Task.Delay(10); } From 4f7f41a500281279320b95790a72b8ff44fbd7c9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 12 May 2022 21:09:56 +0000 Subject: [PATCH 063/855] Bump Moq from 4.17.2 to 4.18.0 Bumps [Moq](https://github.com/moq/moq4) from 4.17.2 to 4.18.0. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/main/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/compare/v4.17.2...v4.18.0) --- updated-dependencies: - dependency-name: Moq dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 16eddaa45..652db4aaa 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -17,7 +17,7 @@ - + From eb882ed0170524851ebdc8cdb51cba622e8f4278 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 May 2022 21:11:03 +0000 Subject: [PATCH 064/855] Bump Verify from 16.7.0 to 16.7.1 Bumps [Verify](https://github.com/VerifyTests/Verify) from 16.7.0 to 16.7.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 16eddaa45..023b72062 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + From e4a819a919fcdea1c5aac95d7b631f35d71c9e39 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 May 2022 12:26:40 +0000 Subject: [PATCH 065/855] Bump Moq from 4.18.0 to 4.18.1 Bumps [Moq](https://github.com/moq/moq4) from 4.18.0 to 4.18.1. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/main/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/compare/v4.18.0...v4.18.1) --- updated-dependencies: - dependency-name: Moq dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 3267a1c18..4ce6d3f02 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -17,7 +17,7 @@ - + From b43bccdb46a2cdcd73f75abb6742717b70a4fec5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 May 2022 12:27:06 +0000 Subject: [PATCH 066/855] Bump Verify.Xunit from 16.7.0 to 16.8.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 16.7.0 to 16.8.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/16.7.0...16.8.1) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 3267a1c18..025a41ee8 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -21,7 +21,7 @@ - + all From c33914e321ba047e8adac0365f5a3c516d3d804e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 May 2022 12:45:10 +0000 Subject: [PATCH 067/855] Bump Microsoft.NET.Test.Sdk from 17.1.0 to 17.2.0 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.1.0 to 17.2.0. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v17.1.0...v17.2.0) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index d8b16668f..7bdb38a4b 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -242,7 +242,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index e56628d7c..58ecdc95a 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -8,7 +8,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 4ce6d3f02..f3f0384f3 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -16,7 +16,7 @@ - + From 81fea5e918f7ebbfa679c9624d64f118e3a7f348 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 16 May 2022 08:46:45 -0400 Subject: [PATCH 068/855] - enables discriminator for conversion in hidi --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 5 ++--- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 71674e395..cf0c69bc2 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,14 +15,13 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview2 + 1.0.0-preview3 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET -- Upgrades Microsoft.OpenApi.OData to 1.0.10 -- Upgrades Microsoft.OData.Edm to 7.11.0 +- Enables discriminator values Microsoft.OpenApi.Hidi Microsoft.OpenApi.Hidi diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 584087ea7..887f5326b 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -343,7 +343,7 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl) PrefixEntityTypeNameBeforeKey = true, TagDepth = 2, EnablePagination = true, - EnableDiscriminatorValue = false, + EnableDiscriminatorValue = true, EnableDerivedTypesReferencesForRequestBody = false, EnableDerivedTypesReferencesForResponses = false, ShowRootPath = false, From 738a855528dc6a97aed2af121d9c0237d42fdd16 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 16 May 2022 08:48:53 -0400 Subject: [PATCH 069/855] - upgrades verify version to match --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 025a41ee8..70a4620ba 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + From 6e24f44efa1db92df94e4fe074860843bddd4d66 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 May 2022 21:12:39 +0000 Subject: [PATCH 070/855] Bump Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers Bumps [Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers](https://github.com/dotnet/upgrade-assistant) from 0.3.310801 to 0.3.326103. - [Release notes](https://github.com/dotnet/upgrade-assistant/releases) - [Changelog](https://github.com/dotnet/upgrade-assistant/blob/main/CHANGELOG.md) - [Commits](https://github.com/dotnet/upgrade-assistant/commits) --- updated-dependencies: - dependency-name: Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index d56e31ec5..5cb2f25c6 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -8,7 +8,7 @@ - + all From acd12855802a98a4d136e30860a7a9c30aa1552f Mon Sep 17 00:00:00 2001 From: Irvine Sunday Date: Tue, 17 May 2022 20:28:15 +0300 Subject: [PATCH 071/855] Add new OpenAPI convert setting --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 887f5326b..0adfca1e7 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -347,7 +347,8 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl) EnableDerivedTypesReferencesForRequestBody = false, EnableDerivedTypesReferencesForResponses = false, ShowRootPath = false, - ShowLinks = false + ShowLinks = false, + ExpandDerivedTypesNavigationProperties = false }; OpenApiDocument document = edmModel.ConvertToOpenApi(settings); From a137f2d693503e1055b3a7402426488e282dac19 Mon Sep 17 00:00:00 2001 From: Irvine Sunday Date: Tue, 17 May 2022 21:23:01 +0300 Subject: [PATCH 072/855] Bump lib. version and update release note --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index cf0c69bc2..4d2dc417d 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,13 +15,14 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview3 + 1.0.0-preview4 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET - Enables discriminator values +- Adds new OpenAPI convert setting, ExpandDerivedTypesNavigationProperties and sets it to false Microsoft.OpenApi.Hidi Microsoft.OpenApi.Hidi From bf8446e8181b974a5e813b6bb6f7a499cd02b265 Mon Sep 17 00:00:00 2001 From: "microsoft-github-policy-service[bot]" <77245923+microsoft-github-policy-service[bot]@users.noreply.github.com> Date: Tue, 17 May 2022 19:33:38 +0000 Subject: [PATCH 073/855] Microsoft mandatory file --- SECURITY.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..766e6f887 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/msrc/pgp-key-msrc). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/msrc/cvd). + + From 9aefe4c63ca6f775b4039be3dcb9eff1cca315b9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 18 May 2022 21:09:57 +0000 Subject: [PATCH 074/855] Bump FluentAssertions from 6.6.0 to 6.7.0 Bumps [FluentAssertions](https://github.com/fluentassertions/fluentassertions) from 6.6.0 to 6.7.0. - [Release notes](https://github.com/fluentassertions/fluentassertions/releases) - [Changelog](https://github.com/fluentassertions/fluentassertions/blob/develop/AcceptApiChanges.ps1) - [Commits](https://github.com/fluentassertions/fluentassertions/compare/6.6.0...6.7.0) --- updated-dependencies: - dependency-name: FluentAssertions dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 7bdb38a4b..73fa9f239 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -243,7 +243,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index e032e036e..b2d6f9a29 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,7 +15,7 @@ - + From 11d35b7a78c3d48285289d99c6dfaa9340f5eb55 Mon Sep 17 00:00:00 2001 From: Carol Kigoonya Date: Thu, 19 May 2022 08:51:24 +0300 Subject: [PATCH 075/855] Add files via upload --- src/Microsoft.OpenApi.Hidi/readme.md | 88 ++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/Microsoft.OpenApi.Hidi/readme.md diff --git a/src/Microsoft.OpenApi.Hidi/readme.md b/src/Microsoft.OpenApi.Hidi/readme.md new file mode 100644 index 000000000..1bc3187fd --- /dev/null +++ b/src/Microsoft.OpenApi.Hidi/readme.md @@ -0,0 +1,88 @@ +# Overview + +Hidi is a command line tool that makes it easy to work with and transform OpenAPI documents. The tool enables you validate and apply transformations to and from different file formats using various commands to do different actions on the files. + +## Capabilities +Hidi has these key capabilities that enable you to build different scenarios off the tool + • Validation of OpenAPI files + • Conversion of OpenAPI files into different file formats: convert files from JSON to YAML, YAML to JSON + • Slice or filter OpenAPI documents to smaller subsets using operationIDs and tags + + +## Installation + +Install [Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenApi.Hidi/1.0.0-preview4) package from NuGet by running the following command: + +### .NET CLI(Global) + 1. dotnet tool install --global Microsoft.OpenApi.Hidi --version 0.5.0-preview4 + +### .NET CLI(local) + + 1. dotnet new tool-manifest #if you are setting up the OpenAPI.NET repo + 2. dotnet tool install --local Microsoft.OpenApi.Hidi --version 0.5.0-preview4 + + + +## How to use Hidi +Once you've installed the package locally, you can invoke the Hidi by running: hidi [command]. +You can access the list of command options we have by running hidi -h +The tool avails the following commands: + + • Validate + • Transform + +### Validate +This command option accepts an OpenAPI document as an input parameter, visits multiple OpenAPI elements within the document and returns statistics count report on the following elements: + + • Path Items + • Operations + • Parameters + • Request bodies + • Responses + • Links + • Callbacks + • Schemas + +It accepts the following command: + + • --openapi(-d) - OpenAPI description file path or URL + • --loglevel(-ll) - The log level to use when logging messages to the main output + + +**Example:** hidi.exe validate --openapi C:\OpenApidocs\Mail.yml --loglevel trace +Run validate -h to see the options available. + +### Transform +Used to convert file formats from JSON to YAML and vice versa and performs slicing of OpenAPI documents. + +This command accepts the following parameters: + + • --openapi(-d) - OpenAPI description file path in the local filesystem or a valid URL hosted on a HTTPS server + • --csdl(-cs) - CSDL file path in the local filesystem or a valid URL hosted on a HTTPS server + • --csdlfilter(-csf) - a filter parameter that a user can use to select a subset of a large CSDL file. They do so by providing a comma delimited list of EntitySet and Singleton names that appear in the EntityContainer. + • --output(-o) - Output directory path for the transformed document + • --clean-ouput(-co) - an optional param that allows a user to overwrite an existing file. + • --version(-v) - OpenAPI specification version + • --format(-f) - File format + • --loglevel(-ll) - The log level to use when logging messages to the main output + • --inline(-i) - Inline $ref instances + • --resolveExternal(-ex) - Resolve external $refs + • --filterByOperationIds(-op) - Slice document based on OperationId(s) provided. Accepts a comma delimited list of operation ids. + • --filterByTags(-t) - Slice document based on tag(s) provided. Accepts a comma delimited list of tags. + • --filterByCollection(-c) - Slices the OpenAPI document based on the Postman Collection file generated by Resource Explorer + + **Examples:** + + 1. Filtering by OperationIds + hidi transform -d files\People.yml -f yaml -o files\People.yml -v OpenApi3_0 -op users_UpdateInsights -co + + 2. Filtering by Postman collection + hidi transform --openapi files\People.yml --format yaml --output files\People2.yml --version OpenApi3_0 --filterByCollection Graph-Collection-0017059134807617005.postman_collection.json + + 3. CSDL--->OpenAPI conversion and filtering + hidi transform --input Files/Todo.xml --output Files/Todo-subset.yml --format yaml --version OpenApi3_0 --filterByOperationIds Todos.Todo.UpdateTodo + + 4. CSDL Filtering by EntitySets and Singletons + hidi transform -cs dataverse.csdl --csdlFilter "appointments,opportunities" -o appointmentsAndOpportunities.yaml -ll trace + +Run transform -h to see all the available usage options. \ No newline at end of file From c1a0bfdea4a0b58308a754716b9e6aabb099eea4 Mon Sep 17 00:00:00 2001 From: Darrel Date: Thu, 19 May 2022 09:46:04 -0400 Subject: [PATCH 076/855] Changed explicit version parameter to --prerelease --- src/Microsoft.OpenApi.Hidi/readme.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/readme.md b/src/Microsoft.OpenApi.Hidi/readme.md index 1bc3187fd..71c32cb1c 100644 --- a/src/Microsoft.OpenApi.Hidi/readme.md +++ b/src/Microsoft.OpenApi.Hidi/readme.md @@ -14,12 +14,14 @@ Hidi has these key capabilities that enable you to build different scenarios off Install [Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenApi.Hidi/1.0.0-preview4) package from NuGet by running the following command: ### .NET CLI(Global) - 1. dotnet tool install --global Microsoft.OpenApi.Hidi --version 0.5.0-preview4 + 1. dotnet tool install --global Microsoft.OpenApi.Hidi --prerelease + ### .NET CLI(local) 1. dotnet new tool-manifest #if you are setting up the OpenAPI.NET repo - 2. dotnet tool install --local Microsoft.OpenApi.Hidi --version 0.5.0-preview4 + 2. dotnet tool install --local Microsoft.OpenApi.Hidi --prerelease + @@ -49,7 +51,8 @@ It accepts the following command: • --loglevel(-ll) - The log level to use when logging messages to the main output -**Example:** hidi.exe validate --openapi C:\OpenApidocs\Mail.yml --loglevel trace +**Example:** `hidi.exe validate --openapi C:\OpenApidocs\Mail.yml --loglevel trace` + Run validate -h to see the options available. ### Transform From bcc34a10f2c1a467a06dff5892d5aeed96ce0b04 Mon Sep 17 00:00:00 2001 From: Darrel Date: Thu, 19 May 2022 10:07:00 -0400 Subject: [PATCH 077/855] Update readme.md --- src/Microsoft.OpenApi.Hidi/readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/readme.md b/src/Microsoft.OpenApi.Hidi/readme.md index 71c32cb1c..6295c5c99 100644 --- a/src/Microsoft.OpenApi.Hidi/readme.md +++ b/src/Microsoft.OpenApi.Hidi/readme.md @@ -4,6 +4,7 @@ Hidi is a command line tool that makes it easy to work with and transform OpenAP ## Capabilities Hidi has these key capabilities that enable you to build different scenarios off the tool + • Validation of OpenAPI files • Conversion of OpenAPI files into different file formats: convert files from JSON to YAML, YAML to JSON • Slice or filter OpenAPI documents to smaller subsets using operationIDs and tags @@ -88,4 +89,4 @@ This command accepts the following parameters: 4. CSDL Filtering by EntitySets and Singletons hidi transform -cs dataverse.csdl --csdlFilter "appointments,opportunities" -o appointmentsAndOpportunities.yaml -ll trace -Run transform -h to see all the available usage options. \ No newline at end of file +Run transform -h to see all the available usage options. From 375f263f41badb99200ab5991af299b062d17365 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Fri, 20 May 2022 10:19:23 -0400 Subject: [PATCH 078/855] - normalizes inlining parameters to kebab case --- src/Microsoft.OpenApi.Hidi/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 80a4c2e14..e9d44c41d 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -54,10 +54,10 @@ static async Task Main(string[] args) var filterByCollectionOption = new Option("--filter-by-collection", "Filters OpenApiDocument by Postman collection provided. Provide path to collection file."); filterByCollectionOption.AddAlias("-c"); - var inlineLocalOption = new Option("--inlineLocal", "Inline local $ref instances"); + var inlineLocalOption = new Option("--inline-local", "Inline local $ref instances"); inlineLocalOption.AddAlias("-il"); - var inlineExternalOption = new Option("--inlineExternal", "Inline external $ref instances"); + var inlineExternalOption = new Option("--inline-external", "Inline external $ref instances"); inlineExternalOption.AddAlias("-ie"); var validateCommand = new Command("validate") From d98b895eeedc8baec3e313991ee599fd73e351fb Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Fri, 20 May 2022 10:22:14 -0400 Subject: [PATCH 079/855] - aligns on two dashes for more than one character shorthands --- src/Microsoft.OpenApi.Hidi/Program.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index e9d44c41d..97fa776cc 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -22,16 +22,16 @@ static async Task Main(string[] args) descriptionOption.AddAlias("-d"); var csdlOption = new Option("--csdl", "Input CSDL file path or URL"); - csdlOption.AddAlias("-cs"); + csdlOption.AddAlias("--cs"); var csdlFilterOption = new Option("--csdl-filter", "Comma delimited list of EntitySets or Singletons to filter CSDL on. e.g. tasks,accounts"); - csdlFilterOption.AddAlias("-csf"); + csdlFilterOption.AddAlias("--csf"); var outputOption = new Option("--output", () => new FileInfo("./output"), "The output directory path for the generated file.") { Arity = ArgumentArity.ZeroOrOne }; outputOption.AddAlias("-o"); var cleanOutputOption = new Option("--clean-output", "Overwrite an existing file"); - cleanOutputOption.AddAlias("-co"); + cleanOutputOption.AddAlias("--co"); var versionOption = new Option("--version", "OpenAPI specification version"); versionOption.AddAlias("-v"); @@ -40,25 +40,25 @@ static async Task Main(string[] args) formatOption.AddAlias("-f"); var terseOutputOption = new Option("--terse-output", "Produce terse json output"); - terseOutputOption.AddAlias("-to"); + terseOutputOption.AddAlias("--to"); var logLevelOption = new Option("--loglevel", () => LogLevel.Information, "The log level to use when logging messages to the main output."); - logLevelOption.AddAlias("-ll"); + logLevelOption.AddAlias("--ll"); var filterByOperationIdsOption = new Option("--filter-by-operationids", "Filters OpenApiDocument by comma delimited list of OperationId(s) provided"); - filterByOperationIdsOption.AddAlias("-op"); + filterByOperationIdsOption.AddAlias("--op"); var filterByTagsOption = new Option("--filter-by-tags", "Filters OpenApiDocument by comma delimited list of Tag(s) provided. Also accepts a single regex."); - filterByTagsOption.AddAlias("-t"); + filterByTagsOption.AddAlias("--t"); var filterByCollectionOption = new Option("--filter-by-collection", "Filters OpenApiDocument by Postman collection provided. Provide path to collection file."); filterByCollectionOption.AddAlias("-c"); var inlineLocalOption = new Option("--inline-local", "Inline local $ref instances"); - inlineLocalOption.AddAlias("-il"); + inlineLocalOption.AddAlias("--il"); var inlineExternalOption = new Option("--inline-external", "Inline external $ref instances"); - inlineExternalOption.AddAlias("-ie"); + inlineExternalOption.AddAlias("--ie"); var validateCommand = new Command("validate") { From 6294631bc7b4241cd105deb2c6b4bd01882ad912 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Fri, 20 May 2022 10:23:33 -0400 Subject: [PATCH 080/855] - aligns log level on kebab casing convention --- src/Microsoft.OpenApi.Hidi/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 97fa776cc..c8ba8fdcd 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -42,7 +42,7 @@ static async Task Main(string[] args) var terseOutputOption = new Option("--terse-output", "Produce terse json output"); terseOutputOption.AddAlias("--to"); - var logLevelOption = new Option("--loglevel", () => LogLevel.Information, "The log level to use when logging messages to the main output."); + var logLevelOption = new Option("--log-level", () => LogLevel.Information, "The log level to use when logging messages to the main output."); logLevelOption.AddAlias("--ll"); var filterByOperationIdsOption = new Option("--filter-by-operationids", "Filters OpenApiDocument by comma delimited list of OperationId(s) provided"); From e54e0c35ab967122891da0303466dc3c7903c454 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Fri, 27 May 2022 10:03:40 -0400 Subject: [PATCH 081/855] - fixes an issue where log entries would be missing Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 0adfca1e7..8e1838d95 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -54,7 +54,8 @@ public static async Task TransformOpenApiDocument( CancellationToken cancellationToken ) { - var logger = ConfigureLoggerInstance(loglevel); + using var loggerFactory = ConfigureLoggerInstance(loglevel); + var logger = loggerFactory.CreateLogger(); try { @@ -258,7 +259,8 @@ public static async Task ValidateOpenApiDocument( LogLevel loglevel, CancellationToken cancellationToken) { - var logger = ConfigureLoggerInstance(loglevel); + using var loggerFactory = ConfigureLoggerInstance(loglevel); + var logger = loggerFactory.CreateLogger(); try { @@ -573,14 +575,14 @@ private static OpenApiFormat GetOpenApiFormat(string input, ILogger logger) return !input.StartsWith("http") && Path.GetExtension(input) == ".json" ? OpenApiFormat.Json : OpenApiFormat.Yaml; } - private static ILogger ConfigureLoggerInstance(LogLevel loglevel) + private static ILoggerFactory ConfigureLoggerInstance(LogLevel loglevel) { // Configure logger options #if DEBUG loglevel = loglevel > LogLevel.Debug ? LogLevel.Debug : loglevel; #endif - var logger = LoggerFactory.Create((builder) => { + return LoggerFactory.Create((builder) => { builder .AddSimpleConsole(c => { c.IncludeScopes = true; @@ -589,9 +591,7 @@ private static ILogger ConfigureLoggerInstance(LogLevel loglevel) .AddDebug() #endif .SetMinimumLevel(loglevel); - }).CreateLogger(); - - return logger; + }); } } } From a955bb134b0edd67a8c83c63b41db6bfbf2ecaa7 Mon Sep 17 00:00:00 2001 From: Matt Gucci Date: Sun, 5 Jun 2022 22:31:27 +0900 Subject: [PATCH 082/855] Add Contact for ReadFragment --- .../V2/OpenApiV2VersionService.cs | 1 + .../V3/OpenApiV3VersionService.cs | 1 + .../V2Tests/OpenApiContactTests.cs | 41 +++++++++++++++++++ .../V3Tests/OpenApiContactTests.cs | 41 +++++++++++++++++++ 4 files changed, 84 insertions(+) create mode 100644 test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs create mode 100644 test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index c4d765734..718dcec04 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -34,6 +34,7 @@ public OpenApiV2VersionService(OpenApiDiagnostic diagnostic) private IDictionary> _loaders = new Dictionary> { [typeof(IOpenApiAny)] = OpenApiV2Deserializer.LoadAny, + [typeof(OpenApiContact)] = OpenApiV2Deserializer.LoadContact, [typeof(OpenApiExternalDocs)] = OpenApiV2Deserializer.LoadExternalDocs, [typeof(OpenApiHeader)] = OpenApiV2Deserializer.LoadHeader, [typeof(OpenApiInfo)] = OpenApiV2Deserializer.LoadInfo, diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index c967cde55..40b40e85a 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -35,6 +35,7 @@ public OpenApiV3VersionService(OpenApiDiagnostic diagnostic) [typeof(IOpenApiAny)] = OpenApiV3Deserializer.LoadAny, [typeof(OpenApiCallback)] = OpenApiV3Deserializer.LoadCallback, [typeof(OpenApiComponents)] = OpenApiV3Deserializer.LoadComponents, + [typeof(OpenApiContact)] = OpenApiV3Deserializer.LoadContact, [typeof(OpenApiEncoding)] = OpenApiV3Deserializer.LoadEncoding, [typeof(OpenApiExample)] = OpenApiV3Deserializer.LoadExample, [typeof(OpenApiExternalDocs)] = OpenApiV3Deserializer.LoadExternalDocs, diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs new file mode 100644 index 000000000..71489d39f --- /dev/null +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using FluentAssertions; +using Microsoft.OpenApi.Models; +using System; +using Xunit; + +namespace Microsoft.OpenApi.Readers.Tests.V2Tests +{ + public class OpenApiContactTests + { + [Fact] + public void ParseStringContactFragmentShouldSucceed() + { + var input = @" +{ + ""name"": ""API Support"", + ""url"": ""http://www.swagger.io/support"", + ""email"": ""support@swagger.io"" +} +"; + var reader = new OpenApiStringReader(); + var diagnostic = new OpenApiDiagnostic(); + + // Act + var contact = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi2_0, out diagnostic); + + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + + contact.Should().BeEquivalentTo( + new OpenApiContact + { + Email = "support@swagger.io", + Name = "API Support", + Url = new Uri("http://www.swagger.io/support") + }); + } + } +} diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs new file mode 100644 index 000000000..be78f942b --- /dev/null +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using FluentAssertions; +using Microsoft.OpenApi.Models; +using System; +using Xunit; + +namespace Microsoft.OpenApi.Readers.Tests.V3Tests +{ + public class OpenApiContactTests + { + [Fact] + public void ParseStringContactFragmentShouldSucceed() + { + var input = @" +{ + ""name"": ""API Support"", + ""url"": ""http://www.swagger.io/support"", + ""email"": ""support@swagger.io"" +} +"; + var reader = new OpenApiStringReader(); + var diagnostic = new OpenApiDiagnostic(); + + // Act + var contact = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + + contact.Should().BeEquivalentTo( + new OpenApiContact + { + Email = "support@swagger.io", + Name = "API Support", + Url = new Uri("http://www.swagger.io/support") + }); + } + } +} From 42258a87a95899be4bcb1b56efb89589ca7a90d2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Jun 2022 21:10:34 +0000 Subject: [PATCH 083/855] Bump Verify from 16.8.1 to 17.1.1 Bumps [Verify](https://github.com/VerifyTests/Verify) from 16.8.1 to 17.1.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/16.8.1...17.1.1) --- updated-dependencies: - dependency-name: Verify dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index e032e036e..72fda3aea 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + From 8c8f4b6dbb72dd50dfacb5c3d6f96207f026cff1 Mon Sep 17 00:00:00 2001 From: Irvine Date: Tue, 7 Jun 2022 15:17:35 +0300 Subject: [PATCH 084/855] Bump conversion lib version and hidi version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 4d2dc417d..00f726e0c 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview4 + 1.0.0-preview5 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET @@ -46,7 +46,7 @@ - + From 1978a482b744797d1f7b06f12d6d449335353227 Mon Sep 17 00:00:00 2001 From: Irvine Date: Tue, 7 Jun 2022 15:33:58 +0300 Subject: [PATCH 085/855] Adds entry to the csproj release notes --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 00f726e0c..6bc530517 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -23,6 +23,7 @@ - Enables discriminator values - Adds new OpenAPI convert setting, ExpandDerivedTypesNavigationProperties and sets it to false +- Bumps up the Microsoft.OpenApi.OData library to v1.0.11-preview2 Microsoft.OpenApi.Hidi Microsoft.OpenApi.Hidi From ba9ac7acd9b09e35ebe66ead30a25ff05dfbe9a4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 7 Jun 2022 14:34:14 +0000 Subject: [PATCH 086/855] Bump Verify.Xunit from 16.8.1 to 17.1.2 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 16.8.1 to 17.1.2. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/16.8.1...17.1.2) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 0d93018b0..d7918bf7a 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -21,7 +21,7 @@ - + all From 94de45a2ad9af8e00b75f231059b7e579b9c3f59 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 7 Jun 2022 07:42:13 -0700 Subject: [PATCH 087/855] - bumps verify to 17.1.2 --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index d7918bf7a..cf08a2645 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + From e9deeeace2ed89fabccca897c7fe260d38d0e5ef Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Jun 2022 21:13:27 +0000 Subject: [PATCH 088/855] Bump Verify from 17.1.2 to 17.1.4 Bumps [Verify](https://github.com/VerifyTests/Verify) from 17.1.2 to 17.1.4. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.1.2...17.1.4) --- updated-dependencies: - dependency-name: Verify dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index cf08a2645..71e76e904 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + From d0322530a397ad4d8991eecce7a81d0349f95345 Mon Sep 17 00:00:00 2001 From: Ji Hoon Date: Thu, 9 Jun 2022 22:34:59 -0500 Subject: [PATCH 089/855] added support for c-style hex numbers to be exported as strings --- .../Writers/SpecialCharacterStringExtensions.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs index 5c6831cb1..d4f78a5c1 100644 --- a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs @@ -187,9 +187,10 @@ internal static string GetYamlCompatibleString(this string input) return $"'{input}'"; } - // If string can be mistaken as a number, a boolean, or a timestamp, - // wrap it in quote to indicate that this is indeed a string, not a number, a boolean, or a timestamp + // If string can be mistaken as a number, c-style hexadecimal notation, a boolean, or a timestamp, + // wrap it in quote to indicate that this is indeed a string, not a number, c-style hexadecimal notation, a boolean, or a timestamp if (decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out var _) || + IsHexadecimalNotation(input) || bool.TryParse(input, out var _) || DateTime.TryParse(input, out var _)) { @@ -225,5 +226,10 @@ internal static string GetJsonCompatibleString(this string value) return $"\"{value}\""; } + + internal static bool IsHexadecimalNotation(string input) + { + return input.StartsWith("0x") && int.TryParse(input.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var _); + } } } From e125a56b096ae4e69a9a2713469c3b3832f32d29 Mon Sep 17 00:00:00 2001 From: Ji Hoon Date: Tue, 14 Jun 2022 22:55:37 -0500 Subject: [PATCH 090/855] resolved merge conflicts to add unit tests --- .../Writers/OpenApiWriterSpecialCharacterTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs index a81e9fc85..f23cc442a 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs @@ -38,6 +38,7 @@ from inputExpected in new[] { new[]{ "Test\\Test", "\"Test\\\\Test\""}, new[]{ "Test\"Test", "\"Test\\\"Test\""}, new[]{ "StringsWith\"Quotes\"", "\"StringsWith\\\"Quotes\\\"\""}, + new[]{ "0x1234", "\"0x1234\""}, } from shouldBeTerse in shouldProduceTerseOutputValues select new object[] { inputExpected[0], inputExpected[1], shouldBeTerse }; @@ -79,6 +80,7 @@ public void WriteStringWithSpecialCharactersAsJsonWorks(string input, string exp [InlineData("trailingspace ", " 'trailingspace '")] [InlineData(" trailingspace", " ' trailingspace'")] [InlineData("terminal:", " 'terminal:'")] + [InlineData("0x1234", " '0x1234'")] public void WriteStringWithSpecialCharactersAsYamlWorks(string input, string expected) { // Arrange From e8dded76c43106059d206190a1e294d4bdc40f6c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 18 Jun 2022 00:36:16 +0000 Subject: [PATCH 091/855] Bump Verify.Xunit from 17.1.2 to 17.1.4 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.1.2 to 17.1.4. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.1.2...17.1.4) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 71e76e904..fcb61c6ae 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -21,7 +21,7 @@ - + all From d8ad5f238afb9b8740ccc6093a232136f4d111f1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 18 Jun 2022 00:49:39 +0000 Subject: [PATCH 092/855] Bump Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers Bumps [Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers](https://github.com/dotnet/upgrade-assistant) from 0.3.326103 to 0.3.330701. - [Release notes](https://github.com/dotnet/upgrade-assistant/releases) - [Changelog](https://github.com/dotnet/upgrade-assistant/blob/main/CHANGELOG.md) - [Commits](https://github.com/dotnet/upgrade-assistant/commits) --- updated-dependencies: - dependency-name: Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index 5cb2f25c6..96dae450b 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -8,7 +8,7 @@ - + all From e6d02cb20553a893b90337366d580295cfb982f0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 18 Jun 2022 00:49:47 +0000 Subject: [PATCH 093/855] Bump SharpYaml from 1.9.1 to 1.9.2 Bumps [SharpYaml](https://github.com/xoofx/SharpYaml) from 1.9.1 to 1.9.2. - [Release notes](https://github.com/xoofx/SharpYaml/releases) - [Changelog](https://github.com/xoofx/SharpYaml/blob/master/changelog.md) - [Commits](https://github.com/xoofx/SharpYaml/compare/1.9.1...1.9.2) --- updated-dependencies: - dependency-name: SharpYaml dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index b6d43cf4c..595d93c2f 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -40,7 +40,7 @@ - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 73fa9f239..e1ec38f8f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -247,7 +247,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index fcb61c6ae..60bf287cc 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -19,7 +19,7 @@ - + From b0141b04dbb2b9e94010b8c0a8afeda468f9cf58 Mon Sep 17 00:00:00 2001 From: Fernando Gutierres Damaceno Date: Mon, 20 Jun 2022 15:29:26 -0300 Subject: [PATCH 094/855] feat: change DisplayAttribute to public --- .../Attributes/DisplayAttribute.cs | 2 +- .../Attributes/DisplayAttributeTests.cs | 28 +++++++++++++ .../PublicApi/PublicApi.approved.txt | 42 +++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 test/Microsoft.OpenApi.Tests/Attributes/DisplayAttributeTests.cs diff --git a/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs b/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs index 920593bbd..db60448ea 100644 --- a/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs +++ b/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs @@ -9,7 +9,7 @@ namespace Microsoft.OpenApi.Attributes /// Represents the Open Api Data type metadata attribute. /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - internal class DisplayAttribute : Attribute + public class DisplayAttribute : Attribute { /// /// Initializes a new instance of the class. diff --git a/test/Microsoft.OpenApi.Tests/Attributes/DisplayAttributeTests.cs b/test/Microsoft.OpenApi.Tests/Attributes/DisplayAttributeTests.cs new file mode 100644 index 000000000..26ec04556 --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Attributes/DisplayAttributeTests.cs @@ -0,0 +1,28 @@ +using Microsoft.OpenApi.Attributes; +using Microsoft.OpenApi.Extensions; +using Xunit; + +namespace Microsoft.OpenApi.Tests.Attributes +{ + + public enum ApiLevel + { + [DisplayAttribute("private")] + Private = 1, + [DisplayAttribute("public")] + Public = 2, + [DisplayAttribute("corporate")] + Corporate = 3 + } + public class DisplayAttributeTests + { + [Theory] + [InlineData(ApiLevel.Private,"private")] + [InlineData(ApiLevel.Public, "public")] + [InlineData(ApiLevel.Corporate, "corporate")] + public void GetDisplayNameExtensionShouldUseDisplayAttribute(ApiLevel apiLevel, string expected) + { + Assert.Equal(expected, apiLevel.GetDisplayName()); + } + } +} diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 02400ddd7..1ff59138d 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -120,6 +120,15 @@ namespace Microsoft.OpenApi.Any Password = 10, } } +namespace Microsoft.OpenApi.Attributes +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field)] + public class DisplayAttribute : System.Attribute + { + public DisplayAttribute(string name) { } + public string Name { get; } + } +} namespace Microsoft.OpenApi.Exceptions { public class OpenApiException : System.Exception @@ -899,43 +908,72 @@ namespace Microsoft.OpenApi.Models } public enum OperationType { + [Microsoft.OpenApi.Attributes.Display("get")] Get = 0, + [Microsoft.OpenApi.Attributes.Display("put")] Put = 1, + [Microsoft.OpenApi.Attributes.Display("post")] Post = 2, + [Microsoft.OpenApi.Attributes.Display("delete")] Delete = 3, + [Microsoft.OpenApi.Attributes.Display("options")] Options = 4, + [Microsoft.OpenApi.Attributes.Display("head")] Head = 5, + [Microsoft.OpenApi.Attributes.Display("patch")] Patch = 6, + [Microsoft.OpenApi.Attributes.Display("trace")] Trace = 7, } public enum ParameterLocation { + [Microsoft.OpenApi.Attributes.Display("query")] Query = 0, + [Microsoft.OpenApi.Attributes.Display("header")] Header = 1, + [Microsoft.OpenApi.Attributes.Display("path")] Path = 2, + [Microsoft.OpenApi.Attributes.Display("cookie")] Cookie = 3, } public enum ParameterStyle { + [Microsoft.OpenApi.Attributes.Display("matrix")] Matrix = 0, + [Microsoft.OpenApi.Attributes.Display("label")] Label = 1, + [Microsoft.OpenApi.Attributes.Display("form")] Form = 2, + [Microsoft.OpenApi.Attributes.Display("simple")] Simple = 3, + [Microsoft.OpenApi.Attributes.Display("spaceDelimited")] SpaceDelimited = 4, + [Microsoft.OpenApi.Attributes.Display("pipeDelimited")] PipeDelimited = 5, + [Microsoft.OpenApi.Attributes.Display("deepObject")] DeepObject = 6, } public enum ReferenceType { + [Microsoft.OpenApi.Attributes.Display("schemas")] Schema = 0, + [Microsoft.OpenApi.Attributes.Display("responses")] Response = 1, + [Microsoft.OpenApi.Attributes.Display("parameters")] Parameter = 2, + [Microsoft.OpenApi.Attributes.Display("examples")] Example = 3, + [Microsoft.OpenApi.Attributes.Display("requestBodies")] RequestBody = 4, + [Microsoft.OpenApi.Attributes.Display("headers")] Header = 5, + [Microsoft.OpenApi.Attributes.Display("securitySchemes")] SecurityScheme = 6, + [Microsoft.OpenApi.Attributes.Display("links")] Link = 7, + [Microsoft.OpenApi.Attributes.Display("callbacks")] Callback = 8, + [Microsoft.OpenApi.Attributes.Display("tags")] Tag = 9, } public class RuntimeExpressionAnyWrapper : Microsoft.OpenApi.Interfaces.IOpenApiElement @@ -947,9 +985,13 @@ namespace Microsoft.OpenApi.Models } public enum SecuritySchemeType { + [Microsoft.OpenApi.Attributes.Display("apiKey")] ApiKey = 0, + [Microsoft.OpenApi.Attributes.Display("http")] Http = 1, + [Microsoft.OpenApi.Attributes.Display("oauth2")] OAuth2 = 2, + [Microsoft.OpenApi.Attributes.Display("openIdConnect")] OpenIdConnect = 3, } } From 8a507640d9f748a800f4ccd1942fc78c6dcf8d1b Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 21 Jun 2022 11:45:08 -0400 Subject: [PATCH 095/855] - adds docker image definition for hidi --- .github/workflows/docker.yml | 45 ++++++++++++++++++++++++++++++++++++ Dockerfile | 21 +++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 .github/workflows/docker.yml create mode 100644 Dockerfile diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 000000000..25ce827bb --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,45 @@ +name: Publish Docker image +on: + workflow_dispatch: + push: + branches: [master, vnext] + paths: ['src/Microsoft.OpenApi.Hidi/**', '.github/workflows/**'] +env: + REGISTRY: msgraphprod.azurecr.io + IMAGE_NAME: public/hidi/generator +jobs: + push_to_registry: + environment: + name: acr + name: Push Docker image + runs-on: ubuntu-latest + steps: + - name: Check out the repo + uses: actions/checkout@v3 + - name: Login to GitHub package feed + uses: docker/login-action@v2.0.0 + with: + username: ${{ secrets.ACR_USERNAME }} + password: ${{ secrets.ACR_PASSWORD }} + registry: ${{ env.REGISTRY }} + - run: | + $content = [XML](Get-Content ./src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj) + $version = $content.Project.PropertyGroup.Version + echo "::set-output name=version::${version}" + shell: pwsh + id: getversion + if: contains(github.ref, 'refs/tags/v') + env: + BRANCH_NAME: ${{ github.ref }} + - name: Push to GitHub Packages - Nightly + if: contains(github.ref, 'refs/head/main') + uses: docker/build-push-action@v3.0.0 + with: + push: true + tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly + - name: Push to GitHub Packages - Release + if: contains(github.ref, 'refs/tags/v') + uses: docker/build-push-action@v3.0.0 + with: + push: true + tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest,${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.getversion.outputs.version }} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..8326ce3b9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env +WORKDIR /app + +COPY ./src ./hidi/src +WORKDIR /app/hidi +RUN dotnet publish ./src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj -c Release + +FROM mcr.microsoft.com/dotnet/runtime:6.0 as runtime +WORKDIR /app + +COPY --from=build-env /app/hidi/src/Microsoft.OpenApi.Hidi/bin/Release/net6.0 ./ + +VOLUME /app/output +VOLUME /app/openapi.yml +VOLUME /app/api.csdl +VOLUME /app/collection.json +ENV HIDI_CONTAINER=true DOTNET_TieredPGO=1 DOTNET_TC_QuickJitForLoops=1 +ENTRYPOINT ["dotnet", "Microsoft.OpenApi.Hidi.dll"] +LABEL description="# Welcome to Hidi \ +To start transforming OpenAPI documents checkout [the getting started documentation](https://github.com/microsoft/OpenAPI.NET/tree/vnext/src/Microsoft.OpenApi.Hidi) \ +[Source dockerfile](https://github.com/microsoft/OpenAPI.NET/blob/vnext/Dockerfile)" From 9b1c35c6df614fef3b1b39b6dc5d551fc5a8410e Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 21 Jun 2022 11:46:16 -0400 Subject: [PATCH 096/855] - fixes branch filters for docker image release --- .github/workflows/docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 25ce827bb..769e3a099 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -32,13 +32,13 @@ jobs: env: BRANCH_NAME: ${{ github.ref }} - name: Push to GitHub Packages - Nightly - if: contains(github.ref, 'refs/head/main') + if: contains(github.ref, 'refs/head/vnext') uses: docker/build-push-action@v3.0.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly - name: Push to GitHub Packages - Release - if: contains(github.ref, 'refs/tags/v') + if: contains(github.ref, 'refs/head/master') uses: docker/build-push-action@v3.0.0 with: push: true From 8bee807da0cc9251e7a442ebb7dd1729cce16947 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 21 Jun 2022 12:02:53 -0400 Subject: [PATCH 097/855] - fixes image name Signed-off-by: Vincent Biret --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 769e3a099..95f2e4d6b 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -6,7 +6,7 @@ on: paths: ['src/Microsoft.OpenApi.Hidi/**', '.github/workflows/**'] env: REGISTRY: msgraphprod.azurecr.io - IMAGE_NAME: public/hidi/generator + IMAGE_NAME: public/hidi jobs: push_to_registry: environment: From d239dab52c31a29cf411b689e6f1323f75d50d9d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Jun 2022 21:55:42 +0000 Subject: [PATCH 098/855] Bump Microsoft.OData.Edm from 7.11.0 to 7.12.0 Bumps Microsoft.OData.Edm from 7.11.0 to 7.12.0. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 6bc530517..d1b3724db 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -46,7 +46,7 @@ - + From 82ca7447b6aae719fa96f8379fabfbdca3661f30 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 23 Jun 2022 03:17:27 +0000 Subject: [PATCH 099/855] Bump Microsoft.OpenApi.OData from 1.0.11-preview2 to 1.0.11-preview3 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.0.11-preview2 to 1.0.11-preview3. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index d1b3724db..154e2d552 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -47,7 +47,7 @@ - + From a768c72eb451b512969026a15a974fb4c8fc3e9f Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 23 Jun 2022 13:08:08 -0400 Subject: [PATCH 100/855] - removes unecessary condition for get version step Signed-off-by: Vincent Biret --- .github/workflows/docker.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 95f2e4d6b..1d42d2094 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -28,7 +28,6 @@ jobs: echo "::set-output name=version::${version}" shell: pwsh id: getversion - if: contains(github.ref, 'refs/tags/v') env: BRANCH_NAME: ${{ github.ref }} - name: Push to GitHub Packages - Nightly From c8e75e74c04f81a5611542f480da2a25e2930061 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 23 Jun 2022 13:09:24 -0400 Subject: [PATCH 101/855] - removes unecessary branch name variable Signed-off-by: Vincent Biret --- .github/workflows/docker.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 1d42d2094..90bf97929 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -28,8 +28,6 @@ jobs: echo "::set-output name=version::${version}" shell: pwsh id: getversion - env: - BRANCH_NAME: ${{ github.ref }} - name: Push to GitHub Packages - Nightly if: contains(github.ref, 'refs/head/vnext') uses: docker/build-push-action@v3.0.0 From 2ae43e80a98fdab072ebe9393dd28c28ba20627a Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 23 Jun 2022 13:17:59 -0400 Subject: [PATCH 102/855] - adds release notes Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 8 ++++---- .../Microsoft.OpenApi.Readers.csproj | 4 ++-- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 154e2d552..f885e8d6f 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,15 +15,15 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview5 + 1.0.0-preview6 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET -- Enables discriminator values -- Adds new OpenAPI convert setting, ExpandDerivedTypesNavigationProperties and sets it to false -- Bumps up the Microsoft.OpenApi.OData library to v1.0.11-preview2 +- Bumps up the Microsoft.OpenAPI library to v1.3.2 +- Bumps up the Microsoft.OData library to v7.12.0 +- Bumps up the Microsoft.OpenApi.OData library to v1.0.11-preview3 Microsoft.OpenApi.Hidi Microsoft.OpenApi.Hidi diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 595d93c2f..8835b373c 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,13 +10,13 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.3.1 + 1.3.2 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET -- Publish symbols. +- Fixed a bug where contact information would not read properly. #892 Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index cbdcde393..980265e98 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,13 +11,13 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.3.1 + 1.3.2 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET -- Publish symbols. +- Adds support for c-style hex notation strings. #908 Microsoft.OpenApi Microsoft.OpenApi From 95301f1248eb36d1d2a7efabeab41ff3d9c9e5ca Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 23 Jun 2022 15:39:13 -0400 Subject: [PATCH 103/855] - another fix for branch filter Signed-off-by: Vincent Biret --- .github/workflows/docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 90bf97929..56f7dd61d 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -29,13 +29,13 @@ jobs: shell: pwsh id: getversion - name: Push to GitHub Packages - Nightly - if: contains(github.ref, 'refs/head/vnext') + if: ${{ github.ref == 'refs/heads/vnext' }} uses: docker/build-push-action@v3.0.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly - name: Push to GitHub Packages - Release - if: contains(github.ref, 'refs/head/master') + if: ${{ github.ref == 'refs/heads/master' }} uses: docker/build-push-action@v3.0.0 with: push: true From b83b2cca62a9273c5c40d4e24fad28d7918c2bcb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 28 Jun 2022 21:09:52 +0000 Subject: [PATCH 104/855] Bump Verify from 17.1.4 to 17.1.6 Bumps [Verify](https://github.com/VerifyTests/Verify) from 17.1.4 to 17.1.6. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.1.4...17.1.6) --- updated-dependencies: - dependency-name: Verify dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 60bf287cc..f1694736e 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + From bfac4a72b9dd6075f8790e3263ccc85140538151 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 29 Jun 2022 00:55:35 +0000 Subject: [PATCH 105/855] Bump Verify.Xunit from 17.1.4 to 17.1.6 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.1.4 to 17.1.6. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.1.4...17.1.6) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index f1694736e..56ac8e941 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -21,7 +21,7 @@ - + all From 673440ef36843caddbfdcb9f26ad0caf5d4c2e46 Mon Sep 17 00:00:00 2001 From: Mustafa Zengin Date: Tue, 28 Jun 2022 23:27:14 -0700 Subject: [PATCH 106/855] remove explicit nuget reference to Verify --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 56ac8e941..a7259e3f8 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,6 @@ - From ddee0b22fa6ba9b35db78d7a41910a227b2ef622 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 3 Jul 2022 18:38:26 -0400 Subject: [PATCH 107/855] Fixed reading v2 with path parameters that are form data --- .../V2/OpenApiPathItemDeserializer.cs | 55 ++++++++++++++++++- .../Microsoft.OpenApi.Readers.Tests.csproj | 4 ++ .../V2Tests/OpenApiPathItemTests.cs | 23 +++++++- .../pathItemWithFormDataPathParameter.yaml | 41 ++++++++++++++ 4 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/OpenApiPathItem/pathItemWithFormDataPathParameter.yaml diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index ba5707480..6134a4bc4 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System.Collections.Generic; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; @@ -32,7 +33,7 @@ internal static partial class OpenApiV2Deserializer { "parameters", (o, n) => { - o.Parameters = n.CreateList(LoadParameter); + LoadPathParameters(o,n); } }, }; @@ -53,5 +54,57 @@ public static OpenApiPathItem LoadPathItem(ParseNode node) return pathItem; } + + private static void LoadPathParameters(OpenApiPathItem pathItem, ParseNode node) + { + node.Context.SetTempStorage(TempStorageKeys.BodyParameter, null); + node.Context.SetTempStorage(TempStorageKeys.FormParameters, null); + + pathItem.Parameters = node.CreateList(LoadParameter); + + // Build request body based on information determined while parsing OpenApiOperation + var bodyParameter = node.Context.GetFromTempStorage(TempStorageKeys.BodyParameter); + if (bodyParameter != null) + { + var requestBody = CreateRequestBody(node.Context, bodyParameter); + foreach(var opPair in pathItem.Operations) + { + if (opPair.Value.RequestBody == null) + { + switch (opPair.Key) + { + case OperationType.Post: + case OperationType.Put: + case OperationType.Patch: + opPair.Value.RequestBody = requestBody; + break; + } + } + } + } + else + { + var formParameters = node.Context.GetFromTempStorage>(TempStorageKeys.FormParameters); + if (formParameters != null) + { + var requestBody = CreateFormBody(node.Context, formParameters); + foreach (var opPair in pathItem.Operations) + { + if (opPair.Value.RequestBody == null) + { + switch (opPair.Key) + { + case OperationType.Post: + case OperationType.Put: + case OperationType.Patch: + opPair.Value.RequestBody = requestBody; + break; + } + } + } + } + } + + } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index e1ec38f8f..fda5ed842 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -14,6 +14,7 @@ + @@ -85,6 +86,9 @@ Never + + Never + Never diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs index 5d3331207..ffa788bf2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text; using FluentAssertions; using Microsoft.OpenApi.Extensions; @@ -253,10 +254,28 @@ public void ParseBasicPathItemWithFormDataShouldSucceed() } // Act - var operation = OpenApiV2Deserializer.LoadPathItem(node); + var pathItem = OpenApiV2Deserializer.LoadPathItem(node); // Assert - operation.Should().BeEquivalentTo(_basicPathItemWithFormData); + pathItem.Should().BeEquivalentTo(_basicPathItemWithFormData); + } + + [Fact] + public void ParsePathItemWithFormDataPathParameterShouldSucceed() + { + // Arrange + MapNode node; + using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "pathItemWithFormDataPathParameter.yaml"))) + { + node = TestHelper.CreateYamlMapNode(stream); + } + + // Act + var pathItem = OpenApiV2Deserializer.LoadPathItem(node); + + // Assert + // FormData parameters at in the path level are pushed into Operation request bodies. + Assert.True(pathItem.Operations.All(o => o.Value.RequestBody != null)); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/OpenApiPathItem/pathItemWithFormDataPathParameter.yaml b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/OpenApiPathItem/pathItemWithFormDataPathParameter.yaml new file mode 100644 index 000000000..57178b4ba --- /dev/null +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/OpenApiPathItem/pathItemWithFormDataPathParameter.yaml @@ -0,0 +1,41 @@ +put: + summary: Puts a pet in the store with form data + description: "" + responses: + '200': + description: Pet updated. + '405': + description: Invalid input + x-http-tests: + - parameterValues: + petId: 10 + name: Milo + status: Happy + expectedRequest: + href: /pathitem-form-parameter/10 + headers: + Content-Type: multipart/form-data + content: name=Milo&status=Happy +post: + summary: Posts a pet in the store with form data + description: "" + responses: + '200': + description: Pet updated. +parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: string + - name: name + in: formData + description: Updated name of the pet + required: true + type: string + - name: status + in: formData + description: Updated status of the pet + required: false + type: string From 3dbe5d8040a7c64db0e4c62425c74703f2fc800d Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 4 Jul 2022 09:29:28 -0400 Subject: [PATCH 108/855] Fixed reading v2 with path parameter that is a body --- .../Microsoft.OpenApi.Readers.Tests.csproj | 4 +++ .../V2Tests/OpenApiPathItemTests.cs | 24 +++++++++++++- .../pathItemWithBodyPathParameter.yaml | 31 +++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/OpenApiPathItem/pathItemWithBodyPathParameter.yaml diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index fda5ed842..c04eb7fd2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -14,6 +14,7 @@ + @@ -89,6 +90,9 @@ Never + + Never + Never diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs index ffa788bf2..a11497cdf 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs @@ -275,7 +275,29 @@ public void ParsePathItemWithFormDataPathParameterShouldSucceed() // Assert // FormData parameters at in the path level are pushed into Operation request bodies. - Assert.True(pathItem.Operations.All(o => o.Value.RequestBody != null)); + Assert.True(pathItem.Operations[OperationType.Put].RequestBody != null); + Assert.True(pathItem.Operations[OperationType.Post].RequestBody != null); + Assert.Equal(2, pathItem.Operations.Count(o => o.Value.RequestBody != null)); } + [Fact] + public void ParsePathItemBodyDataPathParameterShouldSucceed() + { + // Arrange + MapNode node; + using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "pathItemWithBodyPathParameter.yaml"))) + { + node = TestHelper.CreateYamlMapNode(stream); + } + + // Act + var pathItem = OpenApiV2Deserializer.LoadPathItem(node); + + // Assert + // FormData parameters at in the path level are pushed into Operation request bodies. + Assert.True(pathItem.Operations[OperationType.Put].RequestBody != null); + Assert.True(pathItem.Operations[OperationType.Post].RequestBody != null); + Assert.Equal(2, pathItem.Operations.Count(o => o.Value.RequestBody != null)); + } + } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/OpenApiPathItem/pathItemWithBodyPathParameter.yaml b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/OpenApiPathItem/pathItemWithBodyPathParameter.yaml new file mode 100644 index 000000000..c17f4c54e --- /dev/null +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/OpenApiPathItem/pathItemWithBodyPathParameter.yaml @@ -0,0 +1,31 @@ +put: + summary: Puts a pet in the store with form data + description: "" + responses: + '200': + description: Pet updated. + '405': + description: Invalid input +post: + summary: Posts a pet in the store with form data + description: "" + responses: + '200': + description: Pet updated. +parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: string + - name: name + in: body + description: Updated pet body + required: true + type: object + properties: + name: + type: string + status: + type: string \ No newline at end of file From eae3641a6b3ad6ec0ad3f524e9eb23ad7464d3ad Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 4 Jul 2022 19:26:17 +0300 Subject: [PATCH 109/855] Create new object instances for copying purposes --- .../Models/OpenApiCallback.cs | 6 ++--- .../Models/OpenApiComponents.cs | 20 +++++++------- .../Models/OpenApiContact.cs | 2 +- .../Models/OpenApiDiscriminator.cs | 2 +- .../Models/OpenApiDocument.cs | 18 ++++++------- .../Models/OpenApiEncoding.cs | 4 +-- .../Models/OpenApiExample.cs | 4 +-- .../Models/OpenApiExternalDocs.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 10 +++---- src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 6 ++--- .../Models/OpenApiLicense.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 10 +++---- .../Models/OpenApiMediaType.cs | 8 +++--- .../Models/OpenApiOAuthFlow.cs | 4 +-- .../Models/OpenApiOAuthFlows.cs | 10 +++---- .../Models/OpenApiOperation.cs | 18 ++++++------- .../Models/OpenApiParameter.cs | 10 +++---- .../Models/OpenApiPathItem.cs | 10 +++---- src/Microsoft.OpenApi/Models/OpenApiPaths.cs | 3 +++ .../Models/OpenApiReference.cs | 2 +- .../Models/OpenApiRequestBody.cs | 6 ++--- .../Models/OpenApiResponse.cs | 10 +++---- .../Models/OpenApiResponses.cs | 4 +++ src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 26 +++++++++---------- .../Models/OpenApiSecurityScheme.cs | 6 ++--- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 4 +-- .../Models/OpenApiServerVariable.cs | 4 +-- src/Microsoft.OpenApi/Models/OpenApiTag.cs | 6 ++--- src/Microsoft.OpenApi/Models/OpenApiXml.cs | 2 +- .../Models/RuntimeExpressionAnyWrapper.cs | 8 ++++++ .../Services/OpenApiWorkspace.cs | 2 ++ 31 files changed, 123 insertions(+), 106 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index 57bdc3b73..e9701b17c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -45,10 +45,10 @@ public OpenApiCallback() { } /// public OpenApiCallback(OpenApiCallback callback) { - PathItems = callback.PathItems; + PathItems = new(callback.PathItems); UnresolvedReference = callback.UnresolvedReference; - Reference = callback.Reference; - Extensions = callback.Extensions; + Reference = new(callback.Reference); + Extensions = new Dictionary(callback.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 176f1277f..c23e569c5 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -78,16 +78,16 @@ public OpenApiComponents() { } /// public OpenApiComponents(OpenApiComponents components) { - Schemas = components.Schemas; - Responses = components.Responses; - Parameters = components.Parameters; - Examples = components.Examples; - RequestBodies = components.RequestBodies; - Headers = components.Headers; - SecuritySchemes = components.SecuritySchemes; - Links = components.Links; - Callbacks = components.Callbacks; - Extensions = components.Extensions; + Schemas = new Dictionary(components.Schemas); + Responses = new Dictionary(components.Responses); + Parameters = new Dictionary(components.Parameters); + Examples = new Dictionary(components.Examples); + RequestBodies = new Dictionary(components.RequestBodies); + Headers = new Dictionary(components.Headers); + SecuritySchemes = new Dictionary(components.SecuritySchemes); + Links = new Dictionary(components.Links); + Callbacks = new Dictionary(components.Callbacks); + Extensions = new Dictionary(components.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index c26e6512b..a49c80a08 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -48,7 +48,7 @@ public OpenApiContact(OpenApiContact contact) Name = contact.Name; Url = contact.Url; Email = contact.Email; - Extensions = contact.Extensions; + Extensions = new Dictionary(contact.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs index b8caf54bb..e03c7d59a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs @@ -33,7 +33,7 @@ public OpenApiDiscriminator() { } public OpenApiDiscriminator(OpenApiDiscriminator discriminator) { PropertyName = discriminator.PropertyName; - Mapping = discriminator.Mapping; + Mapping = new Dictionary(discriminator.Mapping); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index e8ad85c81..44cbc71ab 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -72,15 +72,15 @@ public OpenApiDocument() {} /// public OpenApiDocument(OpenApiDocument document) { - Workspace = document.Workspace; - Info = document.Info; - Servers = document.Servers; - Paths = document.Paths; - Components = document.Components; - SecurityRequirements = document.SecurityRequirements; - Tags = document.Tags; - ExternalDocs = document.ExternalDocs; - Extensions = document.Extensions; + Workspace = new(document.Workspace); + Info = new(document.Info); + Servers = new List(document.Servers); + Paths = new(document.Paths); + Components = new(document.Components); + SecurityRequirements = new List(document.SecurityRequirements); + Tags = new List(document.Tags); + ExternalDocs = new(document.ExternalDocs); + Extensions = new Dictionary(document.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index 0757c5f8d..533cb7e80 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -64,11 +64,11 @@ public OpenApiEncoding() {} public OpenApiEncoding(OpenApiEncoding encoding) { ContentType = encoding.ContentType; - Headers = encoding.Headers; + Headers = new Dictionary(encoding.Headers); Style = encoding.Style; Explode = encoding.Explode; AllowReserved = encoding.AllowReserved; - Extensions = encoding.Extensions; + Extensions = new Dictionary(encoding.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 2da67941f..b9d5b54bc 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -68,8 +68,8 @@ public OpenApiExample(OpenApiExample example) Description = example.Description; Value = example.Value; ExternalValue = example.ExternalValue; - Extensions = example.Extensions; - Reference = example.Reference; + Extensions = new Dictionary(example.Extensions); + Reference = new(example.Reference); UnresolvedReference = example.UnresolvedReference; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 412d773bb..afc9a5b3c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -41,7 +41,7 @@ public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) { Description = externalDocs.Description; Url = externalDocs.Url; - Extensions = externalDocs.Extensions; + Extensions = new Dictionary(externalDocs.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index ed782e7fd..85a27794f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -97,7 +97,7 @@ public OpenApiHeader() {} public OpenApiHeader(OpenApiHeader header) { UnresolvedReference = header.UnresolvedReference; - Reference = header.Reference; + Reference = new(header.Reference); Description = header.Description; Required = header.Required; Deprecated = header.Deprecated; @@ -105,11 +105,11 @@ public OpenApiHeader(OpenApiHeader header) Style = header.Style; Explode = header.Explode; AllowReserved = header.AllowReserved; - Schema = header.Schema; + Schema = new(header.Schema); Example = header.Example; - Examples = header.Examples; - Content = header.Content; - Extensions = header.Extensions; + Examples = new Dictionary(header.Examples); + Content = new Dictionary(header.Content); + Extensions = new Dictionary(header.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index 84bb63a3e..c5a44c448 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -63,9 +63,9 @@ public OpenApiInfo(OpenApiInfo info) Description = info.Description; Version = info.Version; TermsOfService = info.TermsOfService; - Contact = info.Contact; - License = info.License; - Extensions = info.Extensions; + Contact = new(info.Contact); + License = new(info.License); + Extensions = new Dictionary(info.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index eb4ce5e02..452f98918 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -41,7 +41,7 @@ public OpenApiLicense(OpenApiLicense license) { Name = license.Name; Url = license.Url; - Extensions = license.Extensions; + Extensions = new Dictionary(license.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index 68a8aa9fd..6ba3a65fd 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -73,13 +73,13 @@ public OpenApiLink(OpenApiLink link) { OperationRef = link.OperationRef; OperationId = link.OperationId; - Parameters = link.Parameters; - RequestBody = link.RequestBody; + Parameters = new(link.Parameters); + RequestBody = new(link.RequestBody); Description = link.Description; - Server = link.Server; - Extensions = link.Extensions; + Server = new(link.Server); + Extensions = new Dictionary(link.Extensions); UnresolvedReference = link.UnresolvedReference; - Reference = link.Reference; + Reference = new(link.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 0982800e2..102c9bbbf 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -53,11 +53,11 @@ public OpenApiMediaType() {} /// public OpenApiMediaType(OpenApiMediaType mediaType) { - Schema = mediaType.Schema; + Schema = new(mediaType.Schema); Example = mediaType.Example; - Examples = mediaType.Examples; - Encoding = mediaType.Encoding; - Extensions = mediaType.Extensions; + Examples = new Dictionary(mediaType.Examples); + Encoding = new Dictionary(mediaType.Encoding); + Extensions = new Dictionary(mediaType.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index a69562207..1ee47a499 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -54,8 +54,8 @@ public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) AuthorizationUrl = oAuthFlow.AuthorizationUrl; TokenUrl = oAuthFlow.TokenUrl; RefreshUrl = oAuthFlow.RefreshUrl; - Scopes = oAuthFlow.Scopes; - Extensions = oAuthFlow.Extensions; + Scopes = new Dictionary(oAuthFlow.Scopes); + Extensions = new Dictionary(oAuthFlow.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index f16afa961..973a403e0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -49,11 +49,11 @@ public OpenApiOAuthFlows() {} /// public OpenApiOAuthFlows(OpenApiOAuthFlows oAuthFlows) { - Implicit = oAuthFlows.Implicit; - Password = oAuthFlows.Password; - ClientCredentials = oAuthFlows.ClientCredentials; - AuthorizationCode = oAuthFlows.AuthorizationCode; - Extensions = oAuthFlows.Extensions; + Implicit = new(oAuthFlows.Implicit); + Password = new(oAuthFlows.Password); + ClientCredentials = new(oAuthFlows.ClientCredentials); + AuthorizationCode = new(oAuthFlows.AuthorizationCode); + Extensions = new Dictionary(oAuthFlows.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index f56674261..775532684 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -116,19 +116,19 @@ public OpenApiOperation() {} /// public OpenApiOperation(OpenApiOperation operation) { - Tags = operation.Tags; + Tags = new List(operation.Tags); Summary = operation.Summary; Description = operation.Description; - ExternalDocs = operation.ExternalDocs; + ExternalDocs = new(operation.ExternalDocs); OperationId = operation.OperationId; - Parameters = operation.Parameters; - RequestBody = operation.RequestBody; - Responses = operation.Responses; - Callbacks = operation.Callbacks; + Parameters = new List(operation.Parameters); + RequestBody = new(operation.RequestBody); + Responses = new(operation.Responses); + Callbacks = new Dictionary(operation.Callbacks); Deprecated = operation.Deprecated; - Security = operation.Security; - Servers = operation.Servers; - Extensions = operation.Extensions; + Security = new List(operation.Security); + Servers = new List(operation.Servers); + Extensions = new Dictionary(operation.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index c1946ab35..94eca4a75 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -147,7 +147,7 @@ public OpenApiParameter() {} public OpenApiParameter(OpenApiParameter parameter) { UnresolvedReference = parameter.UnresolvedReference; - Reference = parameter.Reference; + Reference = new(parameter.Reference); Name = parameter.Name; In = parameter.In; Description = parameter.Description; @@ -155,11 +155,11 @@ public OpenApiParameter(OpenApiParameter parameter) Style = parameter.Style; Explode = parameter.Explode; AllowReserved = parameter.AllowReserved; - Schema = parameter.Schema; - Examples = parameter.Examples; + Schema = new(parameter.Schema); + Examples = new Dictionary(parameter.Examples); Example = parameter.Example; - Content = parameter.Content; - Extensions = parameter.Extensions; + Content = new Dictionary(parameter.Content); + Extensions = new Dictionary(parameter.Extensions); AllowEmptyValue = parameter.AllowEmptyValue; Deprecated = parameter.Deprecated; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index cc824b184..8ce83c9eb 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -77,12 +77,12 @@ public OpenApiPathItem(OpenApiPathItem pathItem) { Summary = pathItem.Summary; Description = pathItem.Description; - Operations = pathItem.Operations; - Servers = pathItem.Servers; - Parameters = pathItem.Parameters; - Extensions = pathItem.Extensions; + Operations = new Dictionary(pathItem.Operations); + Servers = new List(pathItem.Servers); + Parameters = new List(pathItem.Parameters); + Extensions = new Dictionary(pathItem.Extensions); UnresolvedReference = pathItem.UnresolvedReference; - Reference = pathItem.Reference; + Reference = new(pathItem.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs index 72d0576d3..2ba371e61 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs @@ -8,5 +8,8 @@ namespace Microsoft.OpenApi.Models /// public class OpenApiPaths : OpenApiExtensibleDictionary { + public OpenApiPaths() {} + public OpenApiPaths(OpenApiPaths paths) {} + } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index 93cc0578f..9213e77bc 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -125,7 +125,7 @@ public OpenApiReference(OpenApiReference reference) ExternalResource = reference.ExternalResource; Type = reference.Type; Id = reference.Id; - HostDocument = reference.HostDocument; + HostDocument = new(reference.HostDocument); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 9ee0d5247..b82b67e8a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -56,11 +56,11 @@ public OpenApiRequestBody() { } public OpenApiRequestBody(OpenApiRequestBody requestBody) { UnresolvedReference = requestBody.UnresolvedReference; - Reference = requestBody.Reference; + Reference = new(requestBody.Reference); Description = requestBody.Description; Required = requestBody.Required; - Content = requestBody.Content; - Extensions = requestBody.Extensions; + Content = new Dictionary(requestBody.Content); + Extensions = new Dictionary(requestBody.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index 637e23835..cf0c796e6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -62,12 +62,12 @@ public OpenApiResponse() {} public OpenApiResponse(OpenApiResponse response) { Description = response.Description; - Headers = response.Headers; - Content = response.Content; - Links = response.Links; - Extensions = response.Extensions; + Headers = new Dictionary(response.Headers); + Content = new Dictionary(response.Content); + Links = new Dictionary(response.Links); + Extensions = new Dictionary(response.Extensions); UnresolvedReference = response.UnresolvedReference; - Reference = response.Reference; + Reference = new(response.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs index 818bf4ced..28fe62ad4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs @@ -8,5 +8,9 @@ namespace Microsoft.OpenApi.Models /// public class OpenApiResponses : OpenApiExtensibleDictionary { + public OpenApiResponses() { } + + public OpenApiResponses(OpenApiResponses openApiResponses) { } + } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 6934f2eda..a60cfae77 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -267,29 +267,29 @@ public OpenApiSchema(OpenApiSchema schema) Default = schema.Default; ReadOnly = schema.ReadOnly; WriteOnly = schema.WriteOnly; - AllOf = schema.AllOf; - OneOf = schema.OneOf; - AnyOf = schema.AnyOf; - Not = schema.Not; - Required = schema.Required; - Items = schema.Items; + AllOf = new List(schema.AllOf); + OneOf = new List(schema.OneOf); + AnyOf = new List(schema.AnyOf); + Not = new(schema.Not); + Required = new HashSet(schema.Required); + Items = new(schema.Items); MaxItems = schema.MaxItems; MinItems = schema.MinItems; UniqueItems = schema.UniqueItems; - Properties = schema.Properties; + Properties = new Dictionary(schema.Properties); MaxProperties = schema.MaxProperties; MinProperties = schema.MinProperties; AdditionalPropertiesAllowed = schema.AdditionalPropertiesAllowed; - AdditionalProperties = schema.AdditionalProperties; - Discriminator = schema.Discriminator; + AdditionalProperties = new(schema.AdditionalProperties); + Discriminator = new(schema.Discriminator); Example = schema.Example; - Enum = schema.Enum; + Enum = new List(schema.Enum); Nullable = schema.Nullable; - ExternalDocs = schema.ExternalDocs; + ExternalDocs = new(schema.ExternalDocs); Deprecated = schema.Deprecated; - Xml = schema.Xml; + Xml = new(schema.Xml); UnresolvedReference = schema.UnresolvedReference; - Reference = schema.Reference; + Reference = new(schema.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index eaba8b40d..b3b5dbe34 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -90,11 +90,11 @@ public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) In = securityScheme.In; Scheme = securityScheme.Scheme; BearerFormat = securityScheme.BearerFormat; - Flows = securityScheme.Flows; + Flows = new(securityScheme.Flows); OpenIdConnectUrl = securityScheme.OpenIdConnectUrl; - Extensions = securityScheme.Extensions; + Extensions = new Dictionary(securityScheme.Extensions); UnresolvedReference = securityScheme.UnresolvedReference; - Reference = securityScheme.Reference; + Reference = new(securityScheme.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index 0ae3f83e9..875bef5c7 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -48,8 +48,8 @@ public OpenApiServer(OpenApiServer server) { Description = server.Description; Url = server.Url; - Variables = server.Variables; - Extensions = server.Extensions; + Variables = new Dictionary(server.Variables); + Extensions = new Dictionary(server.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index 8813ab69b..b1f222e83 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -46,8 +46,8 @@ public OpenApiServerVariable(OpenApiServerVariable serverVariable) { Description = serverVariable.Description; Default = serverVariable.Default; - Enum = serverVariable.Enum; - Extensions = serverVariable.Extensions; + Enum = new List(serverVariable.Enum); + Extensions = new Dictionary(serverVariable.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index ed6f916b5..5ecfa0363 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -55,10 +55,10 @@ public OpenApiTag(OpenApiTag tag) { Name = tag.Name; Description = tag.Description; - ExternalDocs = tag.ExternalDocs; - Extensions = tag.Extensions; + ExternalDocs = new(tag.ExternalDocs); + Extensions = new Dictionary(tag.Extensions); UnresolvedReference = tag.UnresolvedReference; - Reference = tag.Reference; + Reference = new(tag.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index 70e438b1c..eb48132ad 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -61,7 +61,7 @@ public OpenApiXml(OpenApiXml xml) Prefix = xml.Prefix; Attribute = xml.Attribute; Wrapped = xml.Wrapped; - Extensions = xml.Extensions; + Extensions = new Dictionary(xml.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs index 12a525b4f..dec51998f 100644 --- a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs +++ b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -16,6 +16,14 @@ public class RuntimeExpressionAnyWrapper : IOpenApiElement private IOpenApiAny _any; private RuntimeExpression _expression; + public RuntimeExpressionAnyWrapper() {} + + public RuntimeExpressionAnyWrapper(RuntimeExpressionAnyWrapper runtimeExpressionAnyWrapper) + { + Any = runtimeExpressionAnyWrapper.Any; + Expression = runtimeExpressionAnyWrapper.Expression; + } + /// /// Gets/Sets the /// diff --git a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs index 4e6a619a6..05ce022e5 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs @@ -63,6 +63,8 @@ public OpenApiWorkspace() BaseUrl = new Uri("file://" + Environment.CurrentDirectory + "\\" ); } + public OpenApiWorkspace(OpenApiWorkspace workspace){} + /// /// Verify if workspace contains a document based on its URL. /// From d0dc9b34ef8417d091b725006d5f4db1dfdc1208 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 4 Jul 2022 19:47:20 +0300 Subject: [PATCH 110/855] Update public API interface --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index f753292e1..8c5c5ff47 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -747,6 +747,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiPaths : Microsoft.OpenApi.Models.OpenApiExtensibleDictionary { public OpenApiPaths() { } + public OpenApiPaths(Microsoft.OpenApi.Models.OpenApiPaths paths) { } } public class OpenApiReference : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { @@ -799,6 +800,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiResponses : Microsoft.OpenApi.Models.OpenApiExtensibleDictionary { public OpenApiResponses() { } + public OpenApiResponses(Microsoft.OpenApi.Models.OpenApiResponses openApiResponses) { } } public class OpenApiSchema : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { @@ -969,6 +971,7 @@ namespace Microsoft.OpenApi.Models public class RuntimeExpressionAnyWrapper : Microsoft.OpenApi.Interfaces.IOpenApiElement { public RuntimeExpressionAnyWrapper() { } + public RuntimeExpressionAnyWrapper(Microsoft.OpenApi.Models.RuntimeExpressionAnyWrapper runtimeExpressionAnyWrapper) { } public Microsoft.OpenApi.Any.IOpenApiAny Any { get; set; } public Microsoft.OpenApi.Expressions.RuntimeExpression Expression { get; set; } public void WriteValue(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } @@ -1082,6 +1085,7 @@ namespace Microsoft.OpenApi.Services public class OpenApiWorkspace { public OpenApiWorkspace() { } + public OpenApiWorkspace(Microsoft.OpenApi.Services.OpenApiWorkspace workspace) { } public OpenApiWorkspace(System.Uri baseUrl) { } public System.Collections.Generic.IEnumerable Artifacts { get; } public System.Uri BaseUrl { get; } From dc300ab567f94c0c92142d18266d2e380db2e085 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 4 Jul 2022 20:00:04 +0300 Subject: [PATCH 111/855] Add XML comments --- src/Microsoft.OpenApi/Models/OpenApiPaths.cs | 7 +++++++ src/Microsoft.OpenApi/Models/OpenApiResponses.cs | 6 ++++++ .../Models/RuntimeExpressionAnyWrapper.cs | 6 ++++++ src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs | 3 +++ 4 files changed, 22 insertions(+) diff --git a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs index 2ba371e61..f65ccb9c4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs @@ -8,7 +8,14 @@ namespace Microsoft.OpenApi.Models /// public class OpenApiPaths : OpenApiExtensibleDictionary { + /// + /// Parameterless constructor + /// public OpenApiPaths() {} + + /// + /// Initializes a copy of object + /// public OpenApiPaths(OpenApiPaths paths) {} } diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs index 28fe62ad4..24f4eba0d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs @@ -8,8 +8,14 @@ namespace Microsoft.OpenApi.Models /// public class OpenApiResponses : OpenApiExtensibleDictionary { + /// + /// Parameterless constructor + /// public OpenApiResponses() { } + /// + /// Initializes a copy of object + /// public OpenApiResponses(OpenApiResponses openApiResponses) { } } diff --git a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs index dec51998f..3acb2ed82 100644 --- a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs +++ b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -16,8 +16,14 @@ public class RuntimeExpressionAnyWrapper : IOpenApiElement private IOpenApiAny _any; private RuntimeExpression _expression; + /// + /// Parameterless constructor + /// public RuntimeExpressionAnyWrapper() {} + /// + /// Initializes a copy of an object + /// public RuntimeExpressionAnyWrapper(RuntimeExpressionAnyWrapper runtimeExpressionAnyWrapper) { Any = runtimeExpressionAnyWrapper.Any; diff --git a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs index 05ce022e5..7827a50c1 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs @@ -63,6 +63,9 @@ public OpenApiWorkspace() BaseUrl = new Uri("file://" + Environment.CurrentDirectory + "\\" ); } + /// + /// Initializes a copy of an object + /// public OpenApiWorkspace(OpenApiWorkspace workspace){} /// From ea83688677d3c54e2ff3fcc9389187e2e10593db Mon Sep 17 00:00:00 2001 From: Darrel Date: Mon, 4 Jul 2022 15:18:39 -0400 Subject: [PATCH 112/855] Update src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index 6134a4bc4..b04eae319 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -88,7 +88,7 @@ private static void LoadPathParameters(OpenApiPathItem pathItem, ParseNode node) if (formParameters != null) { var requestBody = CreateFormBody(node.Context, formParameters); - foreach (var opPair in pathItem.Operations) + foreach (var opPair in pathItem.Operations.Where(x => x.Value.RequestBody is null)) { if (opPair.Value.RequestBody == null) { From 364952b423861b6b79d04efbf92de858ee0f7e4d Mon Sep 17 00:00:00 2001 From: Darrel Date: Mon, 4 Jul 2022 15:19:11 -0400 Subject: [PATCH 113/855] Update src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs Co-authored-by: Vincent Biret --- .../V2/OpenApiPathItemDeserializer.cs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index b04eae319..4828f541d 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -90,16 +90,13 @@ private static void LoadPathParameters(OpenApiPathItem pathItem, ParseNode node) var requestBody = CreateFormBody(node.Context, formParameters); foreach (var opPair in pathItem.Operations.Where(x => x.Value.RequestBody is null)) { - if (opPair.Value.RequestBody == null) + switch (opPair.Key) { - switch (opPair.Key) - { - case OperationType.Post: - case OperationType.Put: - case OperationType.Patch: - opPair.Value.RequestBody = requestBody; - break; - } + case OperationType.Post: + case OperationType.Put: + case OperationType.Patch: + opPair.Value.RequestBody = requestBody; + break; } } } From bbb6ae068240922755cce73fccef744ef244453d Mon Sep 17 00:00:00 2001 From: Darrel Date: Mon, 4 Jul 2022 15:19:36 -0400 Subject: [PATCH 114/855] Update src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs Co-authored-by: Vincent Biret --- .../V2/OpenApiPathItemDeserializer.cs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index 4828f541d..64252571f 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -69,16 +69,13 @@ private static void LoadPathParameters(OpenApiPathItem pathItem, ParseNode node) var requestBody = CreateRequestBody(node.Context, bodyParameter); foreach(var opPair in pathItem.Operations) { - if (opPair.Value.RequestBody == null) + switch (opPair.Key) { - switch (opPair.Key) - { - case OperationType.Post: - case OperationType.Put: - case OperationType.Patch: - opPair.Value.RequestBody = requestBody; - break; - } + case OperationType.Post: + case OperationType.Put: + case OperationType.Patch: + opPair.Value.RequestBody = requestBody; + break; } } } From 8d28c5a587b36a0f63b3c8b7013c95b7c7f1cb30 Mon Sep 17 00:00:00 2001 From: Darrel Date: Mon, 4 Jul 2022 15:20:04 -0400 Subject: [PATCH 115/855] Update src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index 64252571f..a2179b31f 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -67,7 +67,7 @@ private static void LoadPathParameters(OpenApiPathItem pathItem, ParseNode node) if (bodyParameter != null) { var requestBody = CreateRequestBody(node.Context, bodyParameter); - foreach(var opPair in pathItem.Operations) + foreach(var opPair in pathItem.Operations.Where(x => x.Value.RequestBody is null)) { switch (opPair.Key) { From d4b2c7bd3701c67f3f58048fd13d920850598f9c Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 4 Jul 2022 15:23:06 -0400 Subject: [PATCH 116/855] - adds missing using for linq --- src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index a2179b31f..d905ea42e 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.Collections.Generic; +using System.Linq; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; From b6b71b750cda88e29dcdb2629d30f17259a97ba2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 4 Jul 2022 21:19:14 +0000 Subject: [PATCH 117/855] Bump Verify.Xunit from 17.1.6 to 17.2.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.1.6 to 17.2.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index a7259e3f8..9e1cb4f75 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 45d7ab1b765cee7376565a858dba00d2ba4cbd0d Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 4 Jul 2022 19:00:09 -0400 Subject: [PATCH 118/855] Added fix to handle case where produces or consumes is explicitly set as an empty array --- .../V2/OpenApiDocumentDeserializer.cs | 17 ++++++++++++++--- .../V2/OpenApiOperationDeserializer.cs | 19 +++++++++++++------ 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 6302eaf84..02e868412 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -36,11 +36,22 @@ internal static partial class OpenApiV2Deserializer }, { "consumes", - (o, n) => n.Context.SetTempStorage(TempStorageKeys.GlobalConsumes, n.CreateSimpleList(s => s.GetScalarValue())) + (o, n) => { + var consumes = n.CreateSimpleList(s => s.GetScalarValue()); + if (consumes.Count > 0) + { + n.Context.SetTempStorage(TempStorageKeys.GlobalConsumes, consumes); + } + } }, { - "produces", - (o, n) => n.Context.SetTempStorage(TempStorageKeys.GlobalProduces, n.CreateSimpleList(s => s.GetScalarValue())) + "produces", (o, n) => { + var produces = n.CreateSimpleList(s => s.GetScalarValue()); + if (produces.Count > 0) + { + n.Context.SetTempStorage(TempStorageKeys.GlobalProduces, produces); + } + } }, {"paths", (o, n) => o.Paths = LoadPaths(n)}, { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index 45d076370..f9a6357f8 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; +using System.Xml.Schema; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; @@ -57,14 +58,20 @@ internal static partial class OpenApiV2Deserializer } }, { - "consumes", (o, n) => n.Context.SetTempStorage( - TempStorageKeys.OperationConsumes, - n.CreateSimpleList(s => s.GetScalarValue())) + "consumes", (o, n) => { + var consumes = n.CreateSimpleList(s => s.GetScalarValue()); + if (consumes.Count > 0) { + n.Context.SetTempStorage(TempStorageKeys.OperationConsumes,consumes); + } + } }, { - "produces", (o, n) => n.Context.SetTempStorage( - TempStorageKeys.OperationProduces, - n.CreateSimpleList(s => s.GetScalarValue())) + "produces", (o, n) => { + var produces = n.CreateSimpleList(s => s.GetScalarValue()); + if (produces.Count > 0) { + n.Context.SetTempStorage(TempStorageKeys.OperationProduces, produces); + } + } }, { "responses", (o, n) => From 17d437104ed27adce74cfe27500e8204ecda16e7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 11:59:05 +0300 Subject: [PATCH 119/855] Implement ICloneable for type IOpenApiAny --- src/Microsoft.OpenApi/Any/IOpenApiAny.cs | 3 +- src/Microsoft.OpenApi/Any/OpenApiArray.cs | 12 ++++- src/Microsoft.OpenApi/Any/OpenApiNull.cs | 10 +++++ src/Microsoft.OpenApi/Any/OpenApiObject.cs | 9 ++++ src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs | 45 +++++++++++++++++++ .../Models/OpenApiExample.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 2 +- .../Models/OpenApiMediaType.cs | 2 +- .../Models/OpenApiParameter.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 4 +- .../Models/RuntimeExpressionAnyWrapper.cs | 2 +- 11 files changed, 84 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi/Any/IOpenApiAny.cs b/src/Microsoft.OpenApi/Any/IOpenApiAny.cs index 26c5f4d87..13fd70269 100644 --- a/src/Microsoft.OpenApi/Any/IOpenApiAny.cs +++ b/src/Microsoft.OpenApi/Any/IOpenApiAny.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using Microsoft.OpenApi.Interfaces; namespace Microsoft.OpenApi.Any @@ -8,7 +9,7 @@ namespace Microsoft.OpenApi.Any /// /// Base interface for all the types that represent Open API Any. /// - public interface IOpenApiAny : IOpenApiElement, IOpenApiExtension + public interface IOpenApiAny : IOpenApiElement, IOpenApiExtension, ICloneable { /// /// Type of an . diff --git a/src/Microsoft.OpenApi/Any/OpenApiArray.cs b/src/Microsoft.OpenApi/Any/OpenApiArray.cs index 5ef0087f2..343b44a16 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiArray.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiArray.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using Microsoft.OpenApi.Writers; +using System; using System.Collections.Generic; namespace Microsoft.OpenApi.Any @@ -9,13 +10,22 @@ namespace Microsoft.OpenApi.Any /// /// Open API array. /// - public class OpenApiArray : List, IOpenApiAny + public class OpenApiArray : List, IOpenApiAny, ICloneable { /// /// The type of /// public AnyType AnyType { get; } = AnyType.Array; + /// + /// Implement ICloneable interface to allow for deep copying + /// + /// A new copy of + public object Clone() + { + return new OpenApiArray(); + } + /// /// Write out contents of OpenApiArray to passed writer /// diff --git a/src/Microsoft.OpenApi/Any/OpenApiNull.cs b/src/Microsoft.OpenApi/Any/OpenApiNull.cs index 229409d95..426fbd031 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiNull.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiNull.cs @@ -15,6 +15,16 @@ public class OpenApiNull : IOpenApiAny /// public AnyType AnyType { get; } = AnyType.Null; + + /// + /// Implement ICloneable interface to allow for deep copying + /// + /// A new copy of + public object Clone() + { + return new OpenApiNull(); + } + /// /// Write out null representation /// diff --git a/src/Microsoft.OpenApi/Any/OpenApiObject.cs b/src/Microsoft.OpenApi/Any/OpenApiObject.cs index cd2f6ee64..9b8bdaf78 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiObject.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiObject.cs @@ -16,6 +16,15 @@ public class OpenApiObject : Dictionary, IOpenApiAny /// public AnyType AnyType { get; } = AnyType.Object; + /// + /// Implement ICloneable interface to allow for deep copying + /// + /// A new copy of + public object Clone() + { + return new OpenApiObject(); + } + /// /// Serialize OpenApiObject to writer /// diff --git a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs index b6a111e35..119d7dc00 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System; +using System.Reflection; using System.Text; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Properties; @@ -24,11 +25,21 @@ public OpenApiPrimitive(T value) Value = value; } + /// + /// + /// + /// + public OpenApiPrimitive(OpenApiPrimitive openApiPrimitive) + { + Value = openApiPrimitive.Value; + } + /// /// The kind of . /// public AnyType AnyType { get; } = AnyType.Primitive; + /// /// The primitive class this object represents. /// @@ -39,6 +50,40 @@ public OpenApiPrimitive(T value) /// public T Value { get; } + /// + /// Implement ICloneable interface to allow for deep copying + /// + /// A new copy of + public object Clone() + { + var clone = CloneFromCopyConstructor(this); + if (clone == null) throw new ApplicationException("There's no copy constructor defined"); + return clone; + } + + /// + /// Clones an instance of object from the copy constructor + /// + /// The object instance. + /// A clone copy. + public static object CloneFromCopyConstructor(Object obj) + { + if (obj != null) + { + Type t = obj.GetType(); + foreach (ConstructorInfo ci in t.GetConstructors()) + { + ParameterInfo[] pi = ci.GetParameters(); + if (pi.Length == 1 && pi[0].ParameterType == t) + { + return ci.Invoke(new object[] { obj }); + } + } + } + + return null; + } + /// /// Write out content of primitive element /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index b9d5b54bc..6d16ccf27 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -66,7 +66,7 @@ public OpenApiExample(OpenApiExample example) { Summary = example.Summary; Description = example.Description; - Value = example.Value; + Value = (IOpenApiAny)example.Value.Clone(); ExternalValue = example.ExternalValue; Extensions = new Dictionary(example.Extensions); Reference = new(example.Reference); diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index 85a27794f..330662c48 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -106,7 +106,7 @@ public OpenApiHeader(OpenApiHeader header) Explode = header.Explode; AllowReserved = header.AllowReserved; Schema = new(header.Schema); - Example = header.Example; + Example = (IOpenApiAny)header.Example.Clone(); Examples = new Dictionary(header.Examples); Content = new Dictionary(header.Content); Extensions = new Dictionary(header.Extensions); diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 102c9bbbf..178e97c62 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -54,7 +54,7 @@ public OpenApiMediaType() {} public OpenApiMediaType(OpenApiMediaType mediaType) { Schema = new(mediaType.Schema); - Example = mediaType.Example; + Example = (IOpenApiAny)mediaType.Example.Clone(); Examples = new Dictionary(mediaType.Examples); Encoding = new Dictionary(mediaType.Encoding); Extensions = new Dictionary(mediaType.Extensions); diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 94eca4a75..36cdfe595 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -157,7 +157,7 @@ public OpenApiParameter(OpenApiParameter parameter) AllowReserved = parameter.AllowReserved; Schema = new(parameter.Schema); Examples = new Dictionary(parameter.Examples); - Example = parameter.Example; + Example = (IOpenApiAny)parameter.Example.Clone(); Content = new Dictionary(parameter.Content); Extensions = new Dictionary(parameter.Extensions); AllowEmptyValue = parameter.AllowEmptyValue; diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index a60cfae77..b10b7e768 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -264,7 +264,7 @@ public OpenApiSchema(OpenApiSchema schema) MinLength = schema.MinLength; Pattern = schema.Pattern; MultipleOf = schema.MultipleOf; - Default = schema.Default; + Default = (IOpenApiAny)schema.Default.Clone(); ReadOnly = schema.ReadOnly; WriteOnly = schema.WriteOnly; AllOf = new List(schema.AllOf); @@ -282,7 +282,7 @@ public OpenApiSchema(OpenApiSchema schema) AdditionalPropertiesAllowed = schema.AdditionalPropertiesAllowed; AdditionalProperties = new(schema.AdditionalProperties); Discriminator = new(schema.Discriminator); - Example = schema.Example; + Example = (IOpenApiAny)schema.Example.Clone(); Enum = new List(schema.Enum); Nullable = schema.Nullable; ExternalDocs = new(schema.ExternalDocs); diff --git a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs index 3acb2ed82..be450cee2 100644 --- a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs +++ b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -26,7 +26,7 @@ public RuntimeExpressionAnyWrapper() {} /// public RuntimeExpressionAnyWrapper(RuntimeExpressionAnyWrapper runtimeExpressionAnyWrapper) { - Any = runtimeExpressionAnyWrapper.Any; + Any = (IOpenApiAny)runtimeExpressionAnyWrapper.Any.Clone(); Expression = runtimeExpressionAnyWrapper.Expression; } From 233da50838de49415a3662ff96166657c6cf59e4 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 12:00:49 +0300 Subject: [PATCH 120/855] Initialize a new Uri instance during copying --- src/Microsoft.OpenApi/Models/OpenApiContact.cs | 2 +- .../Models/OpenApiExternalDocs.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiLicense.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs | 6 +++--- .../Models/OpenApiSecurityScheme.cs | 2 +- .../Models/OpenApiLicenseTests.cs | 15 +++++++++++++++ 6 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index a49c80a08..9447d424e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -46,7 +46,7 @@ public OpenApiContact() { } public OpenApiContact(OpenApiContact contact) { Name = contact.Name; - Url = contact.Url; + Url = new Uri(contact.Url.OriginalString); Email = contact.Email; Extensions = new Dictionary(contact.Extensions); } diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index afc9a5b3c..95af8f01b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -40,7 +40,7 @@ public OpenApiExternalDocs() {} public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) { Description = externalDocs.Description; - Url = externalDocs.Url; + Url = new Uri(externalDocs.Url.OriginalString); Extensions = new Dictionary(externalDocs.Extensions); } diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 452f98918..431789aac 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -40,7 +40,7 @@ public OpenApiLicense() {} public OpenApiLicense(OpenApiLicense license) { Name = license.Name; - Url = license.Url; + Url = new Uri(license.Url.OriginalString); Extensions = new Dictionary(license.Extensions); } diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index 1ee47a499..02856d4cd 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -51,9 +51,9 @@ public OpenApiOAuthFlow() {} /// public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) { - AuthorizationUrl = oAuthFlow.AuthorizationUrl; - TokenUrl = oAuthFlow.TokenUrl; - RefreshUrl = oAuthFlow.RefreshUrl; + AuthorizationUrl = new Uri(oAuthFlow.AuthorizationUrl.OriginalString); + TokenUrl = new Uri(oAuthFlow.TokenUrl.OriginalString); + RefreshUrl = new Uri(oAuthFlow.RefreshUrl.OriginalString); Scopes = new Dictionary(oAuthFlow.Scopes); Extensions = new Dictionary(oAuthFlow.Extensions); } diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index b3b5dbe34..b87adf573 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -91,7 +91,7 @@ public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) Scheme = securityScheme.Scheme; BearerFormat = securityScheme.BearerFormat; Flows = new(securityScheme.Flows); - OpenIdConnectUrl = securityScheme.OpenIdConnectUrl; + OpenIdConnectUrl = new Uri(securityScheme.OpenIdConnectUrl.OriginalString); Extensions = new Dictionary(securityScheme.Extensions); UnresolvedReference = securityScheme.UnresolvedReference; Reference = new(securityScheme.Reference); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs index 52e99b0b4..46717ecec 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs @@ -108,5 +108,20 @@ public void SerializeAdvanceLicenseAsYamlWorks(OpenApiSpecVersion version) expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } + + [Fact] + public void ShouldCopyFromOriginalObjectWithoutMutating() + { + // Arrange + var licenseCopy = new OpenApiLicense(AdvanceLicense); + + // Act + licenseCopy.Name = ""; + licenseCopy.Url = new Uri("https://exampleCopy.com"); + + // Assert + Assert.NotEqual(AdvanceLicense.Name, licenseCopy.Name); + Assert.NotEqual(AdvanceLicense.Url, licenseCopy.Url); + } } } From 1dbab5dc1f1cd03fc164f4e1db4cfd5dfde6cfb9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 12:12:35 +0300 Subject: [PATCH 121/855] Update documentation --- src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs index 119d7dc00..0c81c6972 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -26,7 +26,7 @@ public OpenApiPrimitive(T value) } /// - /// + /// Initializes a copy of an object /// /// public OpenApiPrimitive(OpenApiPrimitive openApiPrimitive) From 12fa16b758366c9063b0434da33ee16830033a17 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 12:33:23 +0300 Subject: [PATCH 122/855] Update public API interface --- .../PublicApi/PublicApi.approved.txt | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 8c5c5ff47..ed9fb0962 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -11,18 +11,19 @@ namespace Microsoft.OpenApi.Any Array = 2, Object = 3, } - public interface IOpenApiAny : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension + public interface IOpenApiAny : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable { Microsoft.OpenApi.Any.AnyType AnyType { get; } } - public interface IOpenApiPrimitive : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension + public interface IOpenApiPrimitive : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable { Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } } - public class OpenApiArray : System.Collections.Generic.List, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension + public class OpenApiArray : System.Collections.Generic.List, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable { public OpenApiArray() { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } + public object Clone() { } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } public class OpenApiBinary : Microsoft.OpenApi.Any.OpenApiPrimitive @@ -71,16 +72,18 @@ namespace Microsoft.OpenApi.Any public OpenApiLong(long value) { } public override Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } } - public class OpenApiNull : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension + public class OpenApiNull : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable { public OpenApiNull() { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } + public object Clone() { } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } - public class OpenApiObject : System.Collections.Generic.Dictionary, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension + public class OpenApiObject : System.Collections.Generic.Dictionary, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable { public OpenApiObject() { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } + public object Clone() { } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } public class OpenApiPassword : Microsoft.OpenApi.Any.OpenApiPrimitive @@ -88,13 +91,16 @@ namespace Microsoft.OpenApi.Any public OpenApiPassword(string value) { } public override Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } } - public abstract class OpenApiPrimitive : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Any.IOpenApiPrimitive, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension + public abstract class OpenApiPrimitive : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Any.IOpenApiPrimitive, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable { + public OpenApiPrimitive(Microsoft.OpenApi.Any.OpenApiPrimitive openApiPrimitive) { } public OpenApiPrimitive(T value) { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } public abstract Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } public T Value { get; } + public object Clone() { } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } + public static object CloneFromCopyConstructor(object obj) { } } public class OpenApiString : Microsoft.OpenApi.Any.OpenApiPrimitive { From ccbf9eba3431e4c28e1f3de6989f7ea983e2baa8 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 12:55:20 +0300 Subject: [PATCH 123/855] Updates csproj release notes to point to Github release notes --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index f885e8d6f..27bf00b5b 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -20,11 +20,7 @@ © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET - -- Bumps up the Microsoft.OpenAPI library to v1.3.2 -- Bumps up the Microsoft.OData library to v7.12.0 -- Bumps up the Microsoft.OpenApi.OData library to v1.0.11-preview3 - + https://github.com/microsoft/OpenAPI.NET/releases/tag/1.3.3 Microsoft.OpenApi.Hidi Microsoft.OpenApi.Hidi true From 99c384f56ca54253e3b12101587c705f8e212a1c Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 6 Jul 2022 08:21:59 -0400 Subject: [PATCH 124/855] - releases hidi with discriminator fix Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index f885e8d6f..c5d6562aa 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,15 +15,13 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview6 + 1.0.0-preview7 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET -- Bumps up the Microsoft.OpenAPI library to v1.3.2 -- Bumps up the Microsoft.OData library to v7.12.0 -- Bumps up the Microsoft.OpenApi.OData library to v1.0.11-preview3 +- Bumps up the Microsoft.OpenApi.OData library to v1.0.11-preview4 Microsoft.OpenApi.Hidi Microsoft.OpenApi.Hidi @@ -47,7 +45,7 @@ - + From 1e83b7424944269b0a582674c1a28ee59c62e9e7 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 6 Jul 2022 08:27:16 -0400 Subject: [PATCH 125/855] - adds code owner configuration to the repository Signed-off-by: Vincent Biret --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..7cb46ae19 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @irvinesunday @darrelmiller @peombwa @zengin @baywet @millicentachieng @MaggieKimani1 From 6cf6f511c6b295b3aa2b35d987fbf9621660588b Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 6 Jul 2022 08:45:04 -0400 Subject: [PATCH 126/855] - review suggestions Co-authored-by: Millicent Achieng --- src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index f9a6357f8..a3bda05e1 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; -using System.Xml.Schema; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; From 404be88345e3ce519fc89ad5c6ce863fc3fdaf96 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 15:47:03 +0300 Subject: [PATCH 127/855] Add a Github release notes link to csproj --- .../Microsoft.OpenApi.Readers.csproj | 4 +--- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 8835b373c..3009dc24f 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -15,9 +15,7 @@ © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET - -- Fixed a bug where contact information would not read properly. #892 - + https://github.com/microsoft/OpenAPI.NET/releases/tag/1.3.3 Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers true diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 980265e98..e78dd9fee 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -16,9 +16,7 @@ © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET - -- Adds support for c-style hex notation strings. #908 - + https://github.com/microsoft/OpenAPI.NET/releases/tag/1.3.3 Microsoft.OpenApi Microsoft.OpenApi true From f07f345acefb73f1f2c9ae69a213fe86f0a6541d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 16:03:00 +0300 Subject: [PATCH 128/855] Clean up --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 3009dc24f..e9d3ba283 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -15,7 +15,7 @@ © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET - https://github.com/microsoft/OpenAPI.NET/releases/tag/1.3.3 + https://github.com/microsoft/OpenAPI.NET/releases Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers true diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index e78dd9fee..933b2bdb2 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -16,7 +16,7 @@ © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET - https://github.com/microsoft/OpenAPI.NET/releases/tag/1.3.3 + https://github.com/microsoft/OpenAPI.NET/releases Microsoft.OpenApi Microsoft.OpenApi true From 7cd6abc1d5fd9dc0a132397284cb4a9847462756 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 19:42:19 +0300 Subject: [PATCH 129/855] Revert ICloneable changes and use reflection for deep copying --- src/Microsoft.OpenApi/Any/CloneHelper.cs | 36 +++++++++++++++++++ src/Microsoft.OpenApi/Any/IOpenApiAny.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiArray.cs | 11 +----- src/Microsoft.OpenApi/Any/OpenApiNull.cs | 10 ------ src/Microsoft.OpenApi/Any/OpenApiObject.cs | 9 ----- src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs | 35 ------------------ .../Models/OpenApiExample.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 2 +- .../Models/OpenApiMediaType.cs | 2 +- .../Models/OpenApiParameter.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 4 +-- .../Models/RuntimeExpressionAnyWrapper.cs | 2 +- .../PublicApi/PublicApi.approved.txt | 22 ++++++------ 13 files changed, 56 insertions(+), 83 deletions(-) create mode 100644 src/Microsoft.OpenApi/Any/CloneHelper.cs diff --git a/src/Microsoft.OpenApi/Any/CloneHelper.cs b/src/Microsoft.OpenApi/Any/CloneHelper.cs new file mode 100644 index 000000000..43bec778e --- /dev/null +++ b/src/Microsoft.OpenApi/Any/CloneHelper.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Reflection; + +namespace Microsoft.OpenApi.Any +{ + /// + /// Contains logic for cloning objects through copy constructors. + /// + public class CloneHelper + { + /// + /// Clones an instance of object from the copy constructor + /// + /// The object instance. + /// A clone copy or the object itself. + public static IOpenApiAny CloneFromCopyConstructor(IOpenApiAny obj) + { + if (obj != null) + { + var t = obj.GetType(); + foreach (ConstructorInfo ci in t.GetConstructors()) + { + ParameterInfo[] pi = ci.GetParameters(); + if (pi.Length == 1 && pi[0].ParameterType == t) + { + return (IOpenApiAny)ci.Invoke(new object[] { obj }); + } + } + } + + return obj; + } + } +} diff --git a/src/Microsoft.OpenApi/Any/IOpenApiAny.cs b/src/Microsoft.OpenApi/Any/IOpenApiAny.cs index 13fd70269..5d1cf63e4 100644 --- a/src/Microsoft.OpenApi/Any/IOpenApiAny.cs +++ b/src/Microsoft.OpenApi/Any/IOpenApiAny.cs @@ -9,7 +9,7 @@ namespace Microsoft.OpenApi.Any /// /// Base interface for all the types that represent Open API Any. /// - public interface IOpenApiAny : IOpenApiElement, IOpenApiExtension, ICloneable + public interface IOpenApiAny : IOpenApiElement, IOpenApiExtension { /// /// Type of an . diff --git a/src/Microsoft.OpenApi/Any/OpenApiArray.cs b/src/Microsoft.OpenApi/Any/OpenApiArray.cs index 343b44a16..d19337f44 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiArray.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiArray.cs @@ -10,22 +10,13 @@ namespace Microsoft.OpenApi.Any /// /// Open API array. /// - public class OpenApiArray : List, IOpenApiAny, ICloneable + public class OpenApiArray : List, IOpenApiAny { /// /// The type of /// public AnyType AnyType { get; } = AnyType.Array; - /// - /// Implement ICloneable interface to allow for deep copying - /// - /// A new copy of - public object Clone() - { - return new OpenApiArray(); - } - /// /// Write out contents of OpenApiArray to passed writer /// diff --git a/src/Microsoft.OpenApi/Any/OpenApiNull.cs b/src/Microsoft.OpenApi/Any/OpenApiNull.cs index 426fbd031..229409d95 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiNull.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiNull.cs @@ -15,16 +15,6 @@ public class OpenApiNull : IOpenApiAny /// public AnyType AnyType { get; } = AnyType.Null; - - /// - /// Implement ICloneable interface to allow for deep copying - /// - /// A new copy of - public object Clone() - { - return new OpenApiNull(); - } - /// /// Write out null representation /// diff --git a/src/Microsoft.OpenApi/Any/OpenApiObject.cs b/src/Microsoft.OpenApi/Any/OpenApiObject.cs index 9b8bdaf78..cd2f6ee64 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiObject.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiObject.cs @@ -16,15 +16,6 @@ public class OpenApiObject : Dictionary, IOpenApiAny /// public AnyType AnyType { get; } = AnyType.Object; - /// - /// Implement ICloneable interface to allow for deep copying - /// - /// A new copy of - public object Clone() - { - return new OpenApiObject(); - } - /// /// Serialize OpenApiObject to writer /// diff --git a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs index 0c81c6972..5e32f1b2d 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -39,7 +39,6 @@ public OpenApiPrimitive(OpenApiPrimitive openApiPrimitive) /// public AnyType AnyType { get; } = AnyType.Primitive; - /// /// The primitive class this object represents. /// @@ -50,40 +49,6 @@ public OpenApiPrimitive(OpenApiPrimitive openApiPrimitive) /// public T Value { get; } - /// - /// Implement ICloneable interface to allow for deep copying - /// - /// A new copy of - public object Clone() - { - var clone = CloneFromCopyConstructor(this); - if (clone == null) throw new ApplicationException("There's no copy constructor defined"); - return clone; - } - - /// - /// Clones an instance of object from the copy constructor - /// - /// The object instance. - /// A clone copy. - public static object CloneFromCopyConstructor(Object obj) - { - if (obj != null) - { - Type t = obj.GetType(); - foreach (ConstructorInfo ci in t.GetConstructors()) - { - ParameterInfo[] pi = ci.GetParameters(); - if (pi.Length == 1 && pi[0].ParameterType == t) - { - return ci.Invoke(new object[] { obj }); - } - } - } - - return null; - } - /// /// Write out content of primitive element /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 6d16ccf27..8f7da5399 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -66,7 +66,7 @@ public OpenApiExample(OpenApiExample example) { Summary = example.Summary; Description = example.Description; - Value = (IOpenApiAny)example.Value.Clone(); + Value = CloneHelper.CloneFromCopyConstructor(example.Value); ExternalValue = example.ExternalValue; Extensions = new Dictionary(example.Extensions); Reference = new(example.Reference); diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index 330662c48..5ac25566b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -106,7 +106,7 @@ public OpenApiHeader(OpenApiHeader header) Explode = header.Explode; AllowReserved = header.AllowReserved; Schema = new(header.Schema); - Example = (IOpenApiAny)header.Example.Clone(); + Example = CloneHelper.CloneFromCopyConstructor(header.Example); Examples = new Dictionary(header.Examples); Content = new Dictionary(header.Content); Extensions = new Dictionary(header.Extensions); diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 178e97c62..4a9b857d0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -54,7 +54,7 @@ public OpenApiMediaType() {} public OpenApiMediaType(OpenApiMediaType mediaType) { Schema = new(mediaType.Schema); - Example = (IOpenApiAny)mediaType.Example.Clone(); + Example = CloneHelper.CloneFromCopyConstructor(mediaType.Example); Examples = new Dictionary(mediaType.Examples); Encoding = new Dictionary(mediaType.Encoding); Extensions = new Dictionary(mediaType.Extensions); diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 36cdfe595..03dfd1a42 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -157,7 +157,7 @@ public OpenApiParameter(OpenApiParameter parameter) AllowReserved = parameter.AllowReserved; Schema = new(parameter.Schema); Examples = new Dictionary(parameter.Examples); - Example = (IOpenApiAny)parameter.Example.Clone(); + Example = CloneHelper.CloneFromCopyConstructor(parameter.Example); Content = new Dictionary(parameter.Content); Extensions = new Dictionary(parameter.Extensions); AllowEmptyValue = parameter.AllowEmptyValue; diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index b10b7e768..36ef62dd1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -264,7 +264,7 @@ public OpenApiSchema(OpenApiSchema schema) MinLength = schema.MinLength; Pattern = schema.Pattern; MultipleOf = schema.MultipleOf; - Default = (IOpenApiAny)schema.Default.Clone(); + Default = CloneHelper.CloneFromCopyConstructor(schema.Default); ReadOnly = schema.ReadOnly; WriteOnly = schema.WriteOnly; AllOf = new List(schema.AllOf); @@ -282,7 +282,7 @@ public OpenApiSchema(OpenApiSchema schema) AdditionalPropertiesAllowed = schema.AdditionalPropertiesAllowed; AdditionalProperties = new(schema.AdditionalProperties); Discriminator = new(schema.Discriminator); - Example = (IOpenApiAny)schema.Example.Clone(); + Example = CloneHelper.CloneFromCopyConstructor(schema.Example); Enum = new List(schema.Enum); Nullable = schema.Nullable; ExternalDocs = new(schema.ExternalDocs); diff --git a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs index be450cee2..37764acb1 100644 --- a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs +++ b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -26,7 +26,7 @@ public RuntimeExpressionAnyWrapper() {} /// public RuntimeExpressionAnyWrapper(RuntimeExpressionAnyWrapper runtimeExpressionAnyWrapper) { - Any = (IOpenApiAny)runtimeExpressionAnyWrapper.Any.Clone(); + Any = CloneHelper.CloneFromCopyConstructor(runtimeExpressionAnyWrapper.Any); Expression = runtimeExpressionAnyWrapper.Expression; } diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index ed9fb0962..cdeeaad81 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -11,19 +11,23 @@ namespace Microsoft.OpenApi.Any Array = 2, Object = 3, } - public interface IOpenApiAny : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable + public class CloneHelper + { + public CloneHelper() { } + public static Microsoft.OpenApi.Any.IOpenApiAny CloneFromCopyConstructor(Microsoft.OpenApi.Any.IOpenApiAny obj) { } + } + public interface IOpenApiAny : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { Microsoft.OpenApi.Any.AnyType AnyType { get; } } - public interface IOpenApiPrimitive : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable + public interface IOpenApiPrimitive : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } } - public class OpenApiArray : System.Collections.Generic.List, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable + public class OpenApiArray : System.Collections.Generic.List, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { public OpenApiArray() { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } - public object Clone() { } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } public class OpenApiBinary : Microsoft.OpenApi.Any.OpenApiPrimitive @@ -72,18 +76,16 @@ namespace Microsoft.OpenApi.Any public OpenApiLong(long value) { } public override Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } } - public class OpenApiNull : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable + public class OpenApiNull : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { public OpenApiNull() { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } - public object Clone() { } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } - public class OpenApiObject : System.Collections.Generic.Dictionary, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable + public class OpenApiObject : System.Collections.Generic.Dictionary, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { public OpenApiObject() { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } - public object Clone() { } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } public class OpenApiPassword : Microsoft.OpenApi.Any.OpenApiPrimitive @@ -91,16 +93,14 @@ namespace Microsoft.OpenApi.Any public OpenApiPassword(string value) { } public override Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } } - public abstract class OpenApiPrimitive : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Any.IOpenApiPrimitive, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension, System.ICloneable + public abstract class OpenApiPrimitive : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Any.IOpenApiPrimitive, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { public OpenApiPrimitive(Microsoft.OpenApi.Any.OpenApiPrimitive openApiPrimitive) { } public OpenApiPrimitive(T value) { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } public abstract Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } public T Value { get; } - public object Clone() { } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } - public static object CloneFromCopyConstructor(object obj) { } } public class OpenApiString : Microsoft.OpenApi.Any.OpenApiPrimitive { From 85a0a1f1f20abb58043269b8b6599109155983cf Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 20:19:02 +0300 Subject: [PATCH 130/855] Clean up and add copy constructors --- src/Microsoft.OpenApi/Any/IOpenApiAny.cs | 1 - .../{CloneHelper.cs => OpenApiAnyCloneHelper.cs} | 2 +- src/Microsoft.OpenApi/Any/OpenApiArray.cs | 13 +++++++++++++ src/Microsoft.OpenApi/Any/OpenApiNull.cs | 13 +++++++++++++ src/Microsoft.OpenApi/Any/OpenApiObject.cs | 13 +++++++++++++ src/Microsoft.OpenApi/Models/OpenApiExample.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiMediaType.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 4 ++-- .../Models/RuntimeExpressionAnyWrapper.cs | 2 +- 11 files changed, 47 insertions(+), 9 deletions(-) rename src/Microsoft.OpenApi/Any/{CloneHelper.cs => OpenApiAnyCloneHelper.cs} (96%) diff --git a/src/Microsoft.OpenApi/Any/IOpenApiAny.cs b/src/Microsoft.OpenApi/Any/IOpenApiAny.cs index 5d1cf63e4..26c5f4d87 100644 --- a/src/Microsoft.OpenApi/Any/IOpenApiAny.cs +++ b/src/Microsoft.OpenApi/Any/IOpenApiAny.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using Microsoft.OpenApi.Interfaces; namespace Microsoft.OpenApi.Any diff --git a/src/Microsoft.OpenApi/Any/CloneHelper.cs b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs similarity index 96% rename from src/Microsoft.OpenApi/Any/CloneHelper.cs rename to src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs index 43bec778e..4a67e074e 100644 --- a/src/Microsoft.OpenApi/Any/CloneHelper.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs @@ -8,7 +8,7 @@ namespace Microsoft.OpenApi.Any /// /// Contains logic for cloning objects through copy constructors. /// - public class CloneHelper + public class OpenApiAnyCloneHelper { /// /// Clones an instance of object from the copy constructor diff --git a/src/Microsoft.OpenApi/Any/OpenApiArray.cs b/src/Microsoft.OpenApi/Any/OpenApiArray.cs index d19337f44..2c877d631 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiArray.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiArray.cs @@ -17,6 +17,19 @@ public class OpenApiArray : List, IOpenApiAny /// public AnyType AnyType { get; } = AnyType.Array; + /// + /// Parameterless constructor + /// + public OpenApiArray() { } + + /// + /// Initializes a copy of object + /// + public OpenApiArray(OpenApiArray array) + { + AnyType = array.AnyType; + } + /// /// Write out contents of OpenApiArray to passed writer /// diff --git a/src/Microsoft.OpenApi/Any/OpenApiNull.cs b/src/Microsoft.OpenApi/Any/OpenApiNull.cs index 229409d95..f1772c3e4 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiNull.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiNull.cs @@ -15,6 +15,19 @@ public class OpenApiNull : IOpenApiAny /// public AnyType AnyType { get; } = AnyType.Null; + /// + /// Parameterless constructor + /// + public OpenApiNull() { } + + /// + /// Initializes a copy of object + /// + public OpenApiNull(OpenApiNull openApiNull) + { + AnyType = openApiNull.AnyType; + } + /// /// Write out null representation /// diff --git a/src/Microsoft.OpenApi/Any/OpenApiObject.cs b/src/Microsoft.OpenApi/Any/OpenApiObject.cs index cd2f6ee64..d7e56e341 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiObject.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiObject.cs @@ -16,6 +16,19 @@ public class OpenApiObject : Dictionary, IOpenApiAny /// public AnyType AnyType { get; } = AnyType.Object; + /// + /// Parameterless constructor + /// + public OpenApiObject() { } + + /// + /// Initializes a copy of object + /// + public OpenApiObject(OpenApiObject obj) + { + AnyType = obj.AnyType; + } + /// /// Serialize OpenApiObject to writer /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 8f7da5399..5e105be26 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -66,7 +66,7 @@ public OpenApiExample(OpenApiExample example) { Summary = example.Summary; Description = example.Description; - Value = CloneHelper.CloneFromCopyConstructor(example.Value); + Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example.Value); ExternalValue = example.ExternalValue; Extensions = new Dictionary(example.Extensions); Reference = new(example.Reference); diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index 5ac25566b..b91440df8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -106,7 +106,7 @@ public OpenApiHeader(OpenApiHeader header) Explode = header.Explode; AllowReserved = header.AllowReserved; Schema = new(header.Schema); - Example = CloneHelper.CloneFromCopyConstructor(header.Example); + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header.Example); Examples = new Dictionary(header.Examples); Content = new Dictionary(header.Content); Extensions = new Dictionary(header.Extensions); diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 4a9b857d0..94dcbdfa7 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -54,7 +54,7 @@ public OpenApiMediaType() {} public OpenApiMediaType(OpenApiMediaType mediaType) { Schema = new(mediaType.Schema); - Example = CloneHelper.CloneFromCopyConstructor(mediaType.Example); + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType.Example); Examples = new Dictionary(mediaType.Examples); Encoding = new Dictionary(mediaType.Encoding); Extensions = new Dictionary(mediaType.Extensions); diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 03dfd1a42..f0b21b0d9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -157,7 +157,7 @@ public OpenApiParameter(OpenApiParameter parameter) AllowReserved = parameter.AllowReserved; Schema = new(parameter.Schema); Examples = new Dictionary(parameter.Examples); - Example = CloneHelper.CloneFromCopyConstructor(parameter.Example); + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter.Example); Content = new Dictionary(parameter.Content); Extensions = new Dictionary(parameter.Extensions); AllowEmptyValue = parameter.AllowEmptyValue; diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 36ef62dd1..d43756887 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -264,7 +264,7 @@ public OpenApiSchema(OpenApiSchema schema) MinLength = schema.MinLength; Pattern = schema.Pattern; MultipleOf = schema.MultipleOf; - Default = CloneHelper.CloneFromCopyConstructor(schema.Default); + Default = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema.Default); ReadOnly = schema.ReadOnly; WriteOnly = schema.WriteOnly; AllOf = new List(schema.AllOf); @@ -282,7 +282,7 @@ public OpenApiSchema(OpenApiSchema schema) AdditionalPropertiesAllowed = schema.AdditionalPropertiesAllowed; AdditionalProperties = new(schema.AdditionalProperties); Discriminator = new(schema.Discriminator); - Example = CloneHelper.CloneFromCopyConstructor(schema.Example); + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema.Example); Enum = new List(schema.Enum); Nullable = schema.Nullable; ExternalDocs = new(schema.ExternalDocs); diff --git a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs index 37764acb1..85c64dd30 100644 --- a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs +++ b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -26,7 +26,7 @@ public RuntimeExpressionAnyWrapper() {} /// public RuntimeExpressionAnyWrapper(RuntimeExpressionAnyWrapper runtimeExpressionAnyWrapper) { - Any = CloneHelper.CloneFromCopyConstructor(runtimeExpressionAnyWrapper.Any); + Any = OpenApiAnyCloneHelper.CloneFromCopyConstructor(runtimeExpressionAnyWrapper.Any); Expression = runtimeExpressionAnyWrapper.Expression; } From e034d0ca08dfe3be0c71c0a3d806961bf56ef0fa Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 20:22:09 +0300 Subject: [PATCH 131/855] Revert public API changes --- .../PublicApi/PublicApi.approved.txt | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index cdeeaad81..e9d78acb2 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -11,11 +11,6 @@ namespace Microsoft.OpenApi.Any Array = 2, Object = 3, } - public class CloneHelper - { - public CloneHelper() { } - public static Microsoft.OpenApi.Any.IOpenApiAny CloneFromCopyConstructor(Microsoft.OpenApi.Any.IOpenApiAny obj) { } - } public interface IOpenApiAny : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { Microsoft.OpenApi.Any.AnyType AnyType { get; } @@ -24,9 +19,15 @@ namespace Microsoft.OpenApi.Any { Microsoft.OpenApi.Any.PrimitiveType PrimitiveType { get; } } + public class OpenApiAnyCloneHelper + { + public OpenApiAnyCloneHelper() { } + public static Microsoft.OpenApi.Any.IOpenApiAny CloneFromCopyConstructor(Microsoft.OpenApi.Any.IOpenApiAny obj) { } + } public class OpenApiArray : System.Collections.Generic.List, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { public OpenApiArray() { } + public OpenApiArray(Microsoft.OpenApi.Any.OpenApiArray array) { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } @@ -79,12 +80,14 @@ namespace Microsoft.OpenApi.Any public class OpenApiNull : Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { public OpenApiNull() { } + public OpenApiNull(Microsoft.OpenApi.Any.OpenApiNull openApiNull) { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } public class OpenApiObject : System.Collections.Generic.Dictionary, Microsoft.OpenApi.Any.IOpenApiAny, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtension { public OpenApiObject() { } + public OpenApiObject(Microsoft.OpenApi.Any.OpenApiObject obj) { } public Microsoft.OpenApi.Any.AnyType AnyType { get; } public void Write(Microsoft.OpenApi.Writers.IOpenApiWriter writer, Microsoft.OpenApi.OpenApiSpecVersion specVersion) { } } From 87180dd37e1160dd824beebf61188670d0a180ff Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 6 Jul 2022 20:30:51 +0300 Subject: [PATCH 132/855] Remove unnecessary using --- src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs index 5e32f1b2d..e0abda167 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System; -using System.Reflection; using System.Text; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Properties; From ca1b351d9a065c69efac1b609cd3924c6fe860ea Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 7 Jul 2022 13:05:08 +0300 Subject: [PATCH 133/855] Infer input file path extension and add it to the default output path --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 26 +++++++++++++++----- src/Microsoft.OpenApi.Hidi/Program.cs | 2 +- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 8e1838d95..934b00cda 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.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; @@ -63,10 +63,11 @@ CancellationToken cancellationToken { throw new ArgumentException("Please input a file path"); } - if(output == null) + if (output == null) { - throw new ArgumentNullException(nameof(output)); - } + var inputExtension = GetInputPathExtension(openapi, csdl); + output = new FileInfo($"./output{inputExtension}"); + }; if (cleanoutput && output.Exists) { output.Delete(); @@ -249,8 +250,6 @@ private static Stream ApplyFilter(string csdl, string entitySetOrSingleton, XslC return stream; } - - /// /// Implementation of the validate command /// @@ -575,6 +574,21 @@ private static OpenApiFormat GetOpenApiFormat(string input, ILogger logger) return !input.StartsWith("http") && Path.GetExtension(input) == ".json" ? OpenApiFormat.Json : OpenApiFormat.Yaml; } + private static string GetInputPathExtension(string openapi = null, string csdl = null) + { + var extension = String.Empty; + if (!string.IsNullOrEmpty(openapi)) + { + extension = Path.GetExtension(openapi); + } + if (!string.IsNullOrEmpty(csdl)) + { + extension = ".yml"; + } + + return extension; + } + private static ILoggerFactory ConfigureLoggerInstance(LogLevel loglevel) { // Configure logger options diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index c8ba8fdcd..d19e48cf4 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -27,7 +27,7 @@ static async Task Main(string[] args) var csdlFilterOption = new Option("--csdl-filter", "Comma delimited list of EntitySets or Singletons to filter CSDL on. e.g. tasks,accounts"); csdlFilterOption.AddAlias("--csf"); - var outputOption = new Option("--output", () => new FileInfo("./output"), "The output directory path for the generated file.") { Arity = ArgumentArity.ZeroOrOne }; + var outputOption = new Option("--output", "The output directory path for the generated file.") { Arity = ArgumentArity.ZeroOrOne }; outputOption.AddAlias("-o"); var cleanOutputOption = new Option("--clean-output", "Overwrite an existing file"); From 7731e6df864b2f9f14c6c13632041442fe120edd Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 7 Jul 2022 13:05:26 +0300 Subject: [PATCH 134/855] Move Hidi tests to own test project --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 54 +++++++++++++++++++ .../Services/OpenApiFilterServiceTests.cs | 0 .../Services/OpenApiServiceTests.cs | 0 .../UtilityFiles/OpenApiDocumentMock.cs | 0 .../UtilityFiles/Todo.xml | 0 .../UtilityFiles/postmanCollection_ver1.json | 0 .../UtilityFiles/postmanCollection_ver2.json | 0 .../UtilityFiles/postmanCollection_ver3.json | 0 .../UtilityFiles/postmanCollection_ver4.json | 0 Microsoft.OpenApi.sln | 7 +++ .../Microsoft.OpenApi.Tests.csproj | 15 ------ 11 files changed, 61 insertions(+), 15 deletions(-) create mode 100644 Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj rename {test/Microsoft.OpenApi.Tests => Microsoft.OpenApi.Hidi.Tests}/Services/OpenApiFilterServiceTests.cs (100%) rename {test/Microsoft.OpenApi.Tests => Microsoft.OpenApi.Hidi.Tests}/Services/OpenApiServiceTests.cs (100%) rename {test/Microsoft.OpenApi.Tests => Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/OpenApiDocumentMock.cs (100%) rename {test/Microsoft.OpenApi.Tests => Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/Todo.xml (100%) rename {test/Microsoft.OpenApi.Tests => Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/postmanCollection_ver1.json (100%) rename {test/Microsoft.OpenApi.Tests => Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/postmanCollection_ver2.json (100%) rename {test/Microsoft.OpenApi.Tests => Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/postmanCollection_ver3.json (100%) rename {test/Microsoft.OpenApi.Tests => Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/postmanCollection_ver4.json (100%) diff --git a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj new file mode 100644 index 000000000..d179b0f57 --- /dev/null +++ b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -0,0 +1,54 @@ + + + + net6.0 + enable + enable + + false + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + Always + + + + + + Always + + + Always + + + Always + + + Always + + + Always + + + + diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs b/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs similarity index 100% rename from test/Microsoft.OpenApi.Tests/Services/OpenApiFilterServiceTests.cs rename to Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiServiceTests.cs b/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs similarity index 100% rename from test/Microsoft.OpenApi.Tests/Services/OpenApiServiceTests.cs rename to Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs diff --git a/test/Microsoft.OpenApi.Tests/UtilityFiles/OpenApiDocumentMock.cs b/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs similarity index 100% rename from test/Microsoft.OpenApi.Tests/UtilityFiles/OpenApiDocumentMock.cs rename to Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs diff --git a/test/Microsoft.OpenApi.Tests/UtilityFiles/Todo.xml b/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/Todo.xml similarity index 100% rename from test/Microsoft.OpenApi.Tests/UtilityFiles/Todo.xml rename to Microsoft.OpenApi.Hidi.Tests/UtilityFiles/Todo.xml diff --git a/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver1.json b/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver1.json similarity index 100% rename from test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver1.json rename to Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver1.json diff --git a/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver2.json b/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver2.json similarity index 100% rename from test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver2.json rename to Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver2.json diff --git a/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver3.json b/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver3.json similarity index 100% rename from test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver3.json rename to Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver3.json diff --git a/test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver4.json b/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver4.json similarity index 100% rename from test/Microsoft.OpenApi.Tests/UtilityFiles/postmanCollection_ver4.json rename to Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver4.json diff --git a/Microsoft.OpenApi.sln b/Microsoft.OpenApi.sln index cca18f1e5..157cb18ff 100644 --- a/Microsoft.OpenApi.sln +++ b/Microsoft.OpenApi.sln @@ -28,6 +28,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.OpenApi.SmokeTest EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.OpenApi.Hidi", "src\Microsoft.OpenApi.Hidi\Microsoft.OpenApi.Hidi.csproj", "{254841B5-7DAC-4D1D-A9C5-44FE5CE467BE}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.OpenApi.Hidi.Tests", "Microsoft.OpenApi.Hidi.Tests\Microsoft.OpenApi.Hidi.Tests.csproj", "{D8F799DD-04AC-4A13-B344-45A5B944450A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -62,6 +64,10 @@ Global {254841B5-7DAC-4D1D-A9C5-44FE5CE467BE}.Debug|Any CPU.Build.0 = Debug|Any CPU {254841B5-7DAC-4D1D-A9C5-44FE5CE467BE}.Release|Any CPU.ActiveCfg = Release|Any CPU {254841B5-7DAC-4D1D-A9C5-44FE5CE467BE}.Release|Any CPU.Build.0 = Release|Any CPU + {D8F799DD-04AC-4A13-B344-45A5B944450A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D8F799DD-04AC-4A13-B344-45A5B944450A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D8F799DD-04AC-4A13-B344-45A5B944450A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D8F799DD-04AC-4A13-B344-45A5B944450A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -74,6 +80,7 @@ Global {1ED3C2C1-E1E7-4925-B4E6-2D969C3F5237} = {6357D7FD-2DE4-4900-ADB9-ABC37052040A} {AD79B61D-88CF-497C-9ED5-41AE3867C5AC} = {6357D7FD-2DE4-4900-ADB9-ABC37052040A} {254841B5-7DAC-4D1D-A9C5-44FE5CE467BE} = {E546B92F-20A8-49C3-8323-4B25BB78F3E1} + {D8F799DD-04AC-4A13-B344-45A5B944450A} = {6357D7FD-2DE4-4900-ADB9-ABC37052040A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {9F171EFC-0DB5-4B10-ABFA-AF48D52CC565} diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 9e1cb4f75..9b837f1ea 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -37,20 +37,5 @@ - - Always - - - Always - - - Always - - - Always - - - Always - \ No newline at end of file From 2645555c49a5dd6b198697b7dc9622ec21acc185 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 7 Jul 2022 18:43:39 +0300 Subject: [PATCH 135/855] Use else if() clause --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 934b00cda..d9f9887e1 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -581,7 +581,7 @@ private static string GetInputPathExtension(string openapi = null, string csdl = { extension = Path.GetExtension(openapi); } - if (!string.IsNullOrEmpty(csdl)) + else if (!string.IsNullOrEmpty(csdl)) { extension = ".yml"; } From 339ea2506101e3f2d57e1832d044e3c8b3edb5bf Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 7 Jul 2022 18:45:31 +0300 Subject: [PATCH 136/855] Upgrade dependencies --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 6 +++--- .../Microsoft.OpenApi.Readers.Tests.csproj | 8 ++++---- .../Microsoft.OpenApi.SmokeTests.csproj | 6 +++--- .../Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index d179b0f57..fb6eaecc1 100644 --- a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -9,10 +9,10 @@ - + - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index c04eb7fd2..bfb749d0f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -250,14 +250,14 @@ - + - + - + - + all diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 58ecdc95a..6f1763b30 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -8,9 +8,9 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 9b837f1ea..6d1d86593 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -19,7 +19,7 @@ - + From 7fbe2342c16ab86a9aa0c667b444588389773b51 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Fri, 8 Jul 2022 12:13:50 -0400 Subject: [PATCH 137/855] - bumps hidi version and reference to conversion lib Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index cee484046..1cb71a20a 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview7 + 1.0.0-preview8 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET @@ -43,7 +43,7 @@ - + From c0e09c783c04dd2ff5d10848f59949a2a1977888 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 9 Jul 2022 18:44:59 +1000 Subject: [PATCH 138/855] remove duplicate SourceLink --- src/Directory.Build.props | 2 +- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ---- .../Microsoft.OpenApi.Readers.csproj | 4 ---- .../Microsoft.OpenApi.Workbench.csproj | 1 - src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 4 ---- 5 files changed, 1 insertion(+), 14 deletions(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 7f0f6e9c0..bfc937cba 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -3,6 +3,6 @@ $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb - + \ No newline at end of file diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 1cb71a20a..b6b0292c4 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -51,8 +51,4 @@ - - - - diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index e9d3ba283..072fdcbf1 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -33,10 +33,6 @@ true - - - - diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index 96dae450b..5b0cbf1e4 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -7,7 +7,6 @@ true - all diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 933b2bdb2..b30c7c1ca 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -34,10 +34,6 @@ true - - - - True From b39303e235fdd42bb9c54859e8c1409304585e44 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 14 Jul 2022 16:17:25 +0300 Subject: [PATCH 139/855] Retrieve missing path parameters during slicing --- .../Services/OpenApiFilterService.cs | 8 ++++++ .../Services/OperationSearch.cs | 27 ++++++++++++------- .../Services/SearchResult.cs | 7 +++++ 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs index 11dcaec14..7b9df3d0e 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs @@ -164,6 +164,14 @@ public static OpenApiDocument CreateFilteredDocument(OpenApiDocument source, Fun if (result.CurrentKeys.Operation != null) { pathItem.Operations.Add((OperationType)result.CurrentKeys.Operation, result.Operation); + + if (result.Parameters?.Any() ?? false) + { + foreach (var parameter in result.Parameters) + { + pathItem.Parameters.Add(parameter); + } + } } } diff --git a/src/Microsoft.OpenApi/Services/OperationSearch.cs b/src/Microsoft.OpenApi/Services/OperationSearch.cs index 95b3a6341..780c7ebd8 100644 --- a/src/Microsoft.OpenApi/Services/OperationSearch.cs +++ b/src/Microsoft.OpenApi/Services/OperationSearch.cs @@ -31,18 +31,25 @@ public OperationSearch(Func predi } /// - /// Visits . + /// Visits /// - /// The target . - public override void Visit(OpenApiOperation operation) + /// The target . + public override void Visit(OpenApiPathItem pathItem) { - if (_predicate(CurrentKeys.Path, CurrentKeys.Operation, operation)) + foreach (var item in pathItem.Operations) { - _searchResults.Add(new SearchResult() + var operation = item.Value; + var operationType = item.Key; + + if (_predicate(CurrentKeys.Path, CurrentKeys.Operation, operation)) { - Operation = operation, - CurrentKeys = CopyCurrentKeys(CurrentKeys) - }); + _searchResults.Add(new SearchResult() + { + Operation = operation, + Parameters = pathItem.Parameters, + CurrentKeys = CopyCurrentKeys(CurrentKeys, operationType) + }); + } } } @@ -65,12 +72,12 @@ public override void Visit(IList parameters) base.Visit(parameters); } - private static CurrentKeys CopyCurrentKeys(CurrentKeys currentKeys) + private static CurrentKeys CopyCurrentKeys(CurrentKeys currentKeys, OperationType operationType) { return new CurrentKeys { Path = currentKeys.Path, - Operation = currentKeys.Operation + Operation = operationType }; } } diff --git a/src/Microsoft.OpenApi/Services/SearchResult.cs b/src/Microsoft.OpenApi/Services/SearchResult.cs index 381a11f95..435711128 100644 --- a/src/Microsoft.OpenApi/Services/SearchResult.cs +++ b/src/Microsoft.OpenApi/Services/SearchResult.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System.Collections.Generic; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.Services @@ -19,5 +20,11 @@ public class SearchResult /// An Operation object. /// public OpenApiOperation Operation { get; set; } + + /// + /// Parameters object + /// + public IList Parameters { get; set; } + } } From ea2d73f5bb04775e377a54233f3ff8f6ae33853d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 14 Jul 2022 16:59:15 +0300 Subject: [PATCH 140/855] Adds test for retrieving path parameters --- .../Services/OpenApiFilterServiceTests.cs | 19 +++++++++++- .../UtilityFiles/OpenApiDocumentMock.cs | 30 ++++++++++++++++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs b/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs index 29cb684d2..176fb20d1 100644 --- a/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs +++ b/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.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; @@ -135,5 +135,22 @@ public void ThrowsInvalidOperationExceptionInCreatePredicateWhenInvalidArguments var message2 = Assert.Throws(() => OpenApiFilterService.CreatePredicate("users.user.ListUser", "users.user")).Message; Assert.Equal("Cannot specify both operationIds and tags at the same time.", message2); } + + [Theory] + [InlineData("reports.getTeamsUserActivityUserDetail-a3f1", null)] + [InlineData(null, "reports.Functions")] + public void ReturnsPathParametersOnSlicingBasedOnOperationIdsOrTags(string operationIds, string tags) + { + // Act + var predicate = OpenApiFilterService.CreatePredicate(operationIds, tags); + var subsetOpenApiDocument = OpenApiFilterService.CreateFilteredDocument(_openApiDocumentMock, predicate); + + // Assert + foreach (var pathItem in subsetOpenApiDocument.Paths) + { + Assert.True(pathItem.Value.Parameters.Any()); + Assert.Equal(1, pathItem.Value.Parameters.Count); + } + } } } diff --git a/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs b/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs index d21fccb9a..58b85d91d 100644 --- a/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs +++ b/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs @@ -116,6 +116,21 @@ public static OpenApiDocument CreateOpenApiDocument() } } } + }, + Parameters = new List + { + { + new OpenApiParameter() + { + Name = "period", + In = ParameterLocation.Path, + Required = true, + Schema = new OpenApiSchema() + { + Type = "string" + } + } + } } }, ["/reports/microsoft.graph.getTeamsUserActivityUserDetail(date={date})"] = new OpenApiPathItem() @@ -175,7 +190,20 @@ public static OpenApiDocument CreateOpenApiDocument() } } } - } + }, + Parameters = new List + { + new OpenApiParameter + { + Name = "period", + In = ParameterLocation.Path, + Required = true, + Schema = new OpenApiSchema() + { + Type = "string" + } + } + } }, ["/users"] = new OpenApiPathItem() { From 51d5018b2eac078362ac836e0dc27bbec0b4a62d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 15 Jul 2022 15:58:19 +0300 Subject: [PATCH 141/855] Code refactor and update public API interface --- src/Microsoft.OpenApi/Services/OperationSearch.cs | 4 ++-- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi/Services/OperationSearch.cs b/src/Microsoft.OpenApi/Services/OperationSearch.cs index 780c7ebd8..90e88cc70 100644 --- a/src/Microsoft.OpenApi/Services/OperationSearch.cs +++ b/src/Microsoft.OpenApi/Services/OperationSearch.cs @@ -41,7 +41,7 @@ public override void Visit(OpenApiPathItem pathItem) var operation = item.Value; var operationType = item.Key; - if (_predicate(CurrentKeys.Path, CurrentKeys.Operation, operation)) + if (_predicate(CurrentKeys.Path, operationType, operation)) { _searchResults.Add(new SearchResult() { @@ -77,7 +77,7 @@ private static CurrentKeys CopyCurrentKeys(CurrentKeys currentKeys, OperationTyp return new CurrentKeys { Path = currentKeys.Path, - Operation = operationType + Operation = operationType, }; } } diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index e9d78acb2..e7dc531c7 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1006,6 +1006,7 @@ namespace Microsoft.OpenApi.Services public string Header { get; } public string Link { get; set; } public Microsoft.OpenApi.Models.OperationType? Operation { get; set; } + public System.Collections.Generic.IList Parameters { get; set; } public string Path { get; set; } public string Response { get; set; } public string ServerVariable { get; } @@ -1111,7 +1112,7 @@ namespace Microsoft.OpenApi.Services { public OperationSearch(System.Func predicate) { } public System.Collections.Generic.IList SearchResults { get; } - public override void Visit(Microsoft.OpenApi.Models.OpenApiOperation operation) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiPathItem pathItem) { } public override void Visit(System.Collections.Generic.IList parameters) { } } public class SearchResult @@ -1119,6 +1120,7 @@ namespace Microsoft.OpenApi.Services public SearchResult() { } public Microsoft.OpenApi.Services.CurrentKeys CurrentKeys { get; set; } public Microsoft.OpenApi.Models.OpenApiOperation Operation { get; set; } + public System.Collections.Generic.IList Parameters { get; set; } } } namespace Microsoft.OpenApi.Validations From 69d0bdd667f04a82fdb8a8b7bf1a2c3975eafead Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 15 Jul 2022 16:25:42 +0300 Subject: [PATCH 142/855] Revert API change --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index e7dc531c7..a3c284b0e 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1006,7 +1006,6 @@ namespace Microsoft.OpenApi.Services public string Header { get; } public string Link { get; set; } public Microsoft.OpenApi.Models.OperationType? Operation { get; set; } - public System.Collections.Generic.IList Parameters { get; set; } public string Path { get; set; } public string Response { get; set; } public string ServerVariable { get; } From e8cd960837cc75d882cea8dbbc53d97d6ecaccd0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Jul 2022 21:41:14 +0000 Subject: [PATCH 143/855] Bump Microsoft.OpenApi.OData from 1.0.11-preview5 to 1.0.11 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.0.11-preview5 to 1.0.11. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index b6b0292c4..0eefee6db 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 29c9d0d156548a3476e6e076c4f86d015b7a88e0 Mon Sep 17 00:00:00 2001 From: Andrew Omondi Date: Tue, 19 Jul 2022 11:12:29 +0300 Subject: [PATCH 144/855] Bumps Hidi version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 0eefee6db..cb67b1211 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview8 + 1.0.0-preview9 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET From 4ff0d5449c513c2b73354b046d0a9f939dc9c8d9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 19 Jul 2022 17:45:58 +0300 Subject: [PATCH 145/855] Update ci-build.yml for Azure Pipelines --- .azure-pipelines/ci-build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 345d50af9..a1f5a827d 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -290,6 +290,7 @@ stages: displayName: 'GitHub release (edit)' inputs: gitHubConnection: 'Github-MaggieKimani1' + action: edit tagSource: userSpecifiedTag tag: '$(artifactVersion)' title: '$(artifactVersion)' From 49a99c6f80be50ae4234d2d50c479657653e28d1 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 19 Jul 2022 18:22:55 +0300 Subject: [PATCH 146/855] Use Powershell task to pack the dlls --- .azure-pipelines/ci-build.yml | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index a1f5a827d..5e8ddbd3b 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -157,30 +157,18 @@ stages: } ] SessionTimeout: 20 - + # Pack - - task: DotNetCoreCLI@2 + - pwsh: dotnet pack $(Build.SourcesDirectory)/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj -o $(Build.ArtifactStagingDirectory) --configuration $(BuildConfiguration) --no-build --include-symbols --include-source /p:SymbolPackageFormat=snupkg displayName: 'pack OpenAPI' - inputs: - command: pack - projects: src/Microsoft.OpenApi/Microsoft.OpenApi.csproj - arguments: '-o $(Build.ArtifactStagingDirectory) --configuration $(BuildConfiguration) --no-build --include-symbols --include-source /p:SymbolPackageFormat=snupkg' # Pack - - task: DotNetCoreCLI@2 + - pwsh: dotnet pack $(Build.SourcesDirectory)/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj -o $(Build.ArtifactStagingDirectory) --configuration $(BuildConfiguration) --no-build --include-symbols --include-source /p:SymbolPackageFormat=snupkg displayName: 'pack Readers' - inputs: - command: pack - projects: src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj - arguments: '-o $(Build.ArtifactStagingDirectory) --configuration $(BuildConfiguration) --no-build --include-symbols --include-source /p:SymbolPackageFormat=snupkg' - + # Pack - - task: DotNetCoreCLI@2 - displayName: 'pack Hidi' - inputs: - command: pack - projects: src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj - arguments: '-o $(Build.ArtifactStagingDirectory) --configuration $(BuildConfiguration) --no-build --include-symbols --include-source /p:SymbolPackageFormat=snupkg' + - pwsh: dotnet pack $(Build.SourcesDirectory)/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj -o $(Build.ArtifactStagingDirectory) --configuration $(BuildConfiguration) --no-build --include-symbols --include-source /p:SymbolPackageFormat=snupkg + displayName: 'pack Hidi' - task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@1 displayName: 'ESRP CodeSigning Nuget Packages' From caf14fb07541672a575c102bef1f210985fe471c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 20 Jul 2022 21:23:30 +0000 Subject: [PATCH 147/855] Bump Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers Bumps [Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers](https://github.com/dotnet/upgrade-assistant) from 0.3.330701 to 0.4.336902. - [Release notes](https://github.com/dotnet/upgrade-assistant/releases) - [Changelog](https://github.com/dotnet/upgrade-assistant/blob/main/CHANGELOG.md) - [Commits](https://github.com/dotnet/upgrade-assistant/commits) --- updated-dependencies: - dependency-name: Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index 5b0cbf1e4..326ef4b69 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -7,7 +7,7 @@ true - + all From f2faaaaeba0dde9d33414ba96396e96c8917d41d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 20 Jul 2022 21:23:33 +0000 Subject: [PATCH 148/855] Bump Microsoft.OData.Edm from 7.12.0 to 7.12.1 Bumps Microsoft.OData.Edm from 7.12.0 to 7.12.1. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index cb67b1211..f9e1f0d9e 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From 254b70f04e6daca40898fdc8046ba02c09a094b3 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 21 Jul 2022 17:14:08 +0300 Subject: [PATCH 149/855] Add logic to check whether the properties of anyOf/oneOf/allOf match the property name in the dicriminator --- .../Validations/Rules/OpenApiSchemaRules.cs | 43 +++++++++++++++++-- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index 1639e6248..aadaac4ec 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -72,13 +72,48 @@ public static class OpenApiSchemaRules { if (!schema.Required.Contains(schema.Discriminator?.PropertyName)) { - context.CreateError(nameof(ValidateSchemaDiscriminator), - string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, - schema.Reference.Id, schema.Discriminator.PropertyName)); + // check schema.OneOf, schema.AnyOf or schema.AllOf + if(schema.OneOf.Count != 0) + { + ValidateDiscriminatorAgainstChildSchema(schema.OneOf, schema, context); + } + else if (schema.AnyOf.Count != 0) + { + ValidateDiscriminatorAgainstChildSchema(schema.AnyOf, schema, context); + } + else if (schema.AllOf.Count != 0) + { + ValidateDiscriminatorAgainstChildSchema(schema.AllOf, schema, context); + } + else + { + context.CreateError(nameof(ValidateSchemaDiscriminator), + string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, + schema.Reference.Id, schema.Discriminator.PropertyName)); + } } - } + } context.Exit(); }); + + /// + /// Validates the property name in the discriminator against the ones present in the children schema + /// + /// The derived schema. + /// The parent schema. + /// A validation context. + public static void ValidateDiscriminatorAgainstChildSchema(IList childSchema, OpenApiSchema schema, IValidationContext context) + { + foreach (var schemaItem in childSchema) + { + if (!schemaItem.Properties.Keys.Contains(schema.Discriminator?.PropertyName)) + { + context.CreateError(nameof(ValidateSchemaDiscriminator), + string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, + schema.Reference.Id, schema.Discriminator.PropertyName)); + } + } + } } } From 96cfc45bbb7a7c66afbe6d30b672b636fbec4c09 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 21 Jul 2022 17:14:28 +0300 Subject: [PATCH 150/855] Add test case --- .../OpenApiSchemaValidationTests.cs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs index d239e15a1..04acf7737 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs @@ -268,5 +268,60 @@ public void ValidateSchemaRequiredFieldListMustContainThePropertySpecifiedInTheD "schema1", "property1")) }); } + + [Fact] + public void ValidateOneOfSchemaPropertyNameContainsPropertySpecifiedInTheDiscriminator() + { + // Arrange + var components = new OpenApiComponents + { + Schemas = + { + { + "Person", + new OpenApiSchema + { + Type = "array", + Discriminator = new OpenApiDiscriminator + { + PropertyName = "type" + }, + OneOf = new List + { + new OpenApiSchema + { + Properties = + { + { + "type", + new OpenApiSchema + { + Type = "array" + } + } + }, + Reference = new OpenApiReference + { + Type = ReferenceType.Schema, + Id = "Person" + } + } + }, + Reference = new OpenApiReference { Id = "Person" } + } + } + } + }; + + // Act + var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet()); + var walker = new OpenApiWalker(validator); + walker.Walk(components); + + var errors = validator.Errors; + + //Assert + errors.Should().BeEmpty(); + } } } From 2b34d2dad6c7fcdb657437a5c320a0c655cdcd9e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 21 Jul 2022 17:22:09 +0300 Subject: [PATCH 151/855] Update public Api --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index e9d78acb2..dc42f5485 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1283,6 +1283,7 @@ namespace Microsoft.OpenApi.Validations.Rules { public static Microsoft.OpenApi.Validations.ValidationRule SchemaMismatchedDataType { get; } public static Microsoft.OpenApi.Validations.ValidationRule ValidateSchemaDiscriminator { get; } + public static void ValidateDiscriminatorAgainstChildSchema(System.Collections.Generic.IList childSchema, Microsoft.OpenApi.Models.OpenApiSchema schema, Microsoft.OpenApi.Validations.IValidationContext context) { } } [Microsoft.OpenApi.Validations.Rules.OpenApiRule] public static class OpenApiServerRules From 6af10c23e2c68f5f14c7c9d3dcb49400fd0cbb43 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 21 Jul 2022 17:27:13 +0300 Subject: [PATCH 152/855] Remove whitespace --- src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index aadaac4ec..0b72ebc52 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -92,8 +92,8 @@ public static class OpenApiSchemaRules schema.Reference.Id, schema.Discriminator.PropertyName)); } } - } - + } + context.Exit(); }); From aba7b38c5a01ab3ce59411f634196c33774c1d7d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Jul 2022 21:10:34 +0000 Subject: [PATCH 153/855] Bump docker/build-push-action from 3.0.0 to 3.1.0 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3.0.0 to 3.1.0. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v3.0.0...v3.1.0) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 56f7dd61d..43ea50e2f 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -30,13 +30,13 @@ jobs: id: getversion - name: Push to GitHub Packages - Nightly if: ${{ github.ref == 'refs/heads/vnext' }} - uses: docker/build-push-action@v3.0.0 + uses: docker/build-push-action@v3.1.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly - name: Push to GitHub Packages - Release if: ${{ github.ref == 'refs/heads/master' }} - uses: docker/build-push-action@v3.0.0 + uses: docker/build-push-action@v3.1.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest,${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.getversion.outputs.version }} From 55e0eac2a1fff9b5a67852abc475fe0c8cc7356c Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 27 Jul 2022 15:35:38 +0300 Subject: [PATCH 154/855] Bump lib versions --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 072fdcbf1..1ff5b99e9 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.3.2 + 1.4.0-preview1 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index b30c7c1ca..a11622ec1 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.3.2 + 1.4.0-preview1 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 8654070f7e75c51011b02c60be6322c3ff327c32 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 27 Jul 2022 20:38:10 +0000 Subject: [PATCH 155/855] Bump Verify.Xunit from 17.2.1 to 17.4.2 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.2.1 to 17.4.2. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits/17.4.2) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 6d1d86593..5104ebbe9 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 93464f44aa1caf384b8a94dcc76a600eae6b2ac3 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 1 Aug 2022 10:45:28 +0300 Subject: [PATCH 156/855] Bumps up System.Commandline API to v2.0.0-beta4.22272.1 and resolve breaking change --- .../Handlers/TransformCommandHandler.cs | 73 +++++++++++++++++++ .../Handlers/ValidateCommandHandler.cs | 49 +++++++++++++ .../Microsoft.OpenApi.Hidi.csproj | 14 ++-- src/Microsoft.OpenApi.Hidi/Program.cs | 28 +++++-- 4 files changed, 152 insertions(+), 12 deletions(-) create mode 100644 src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs create mode 100644 src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs new file mode 100644 index 000000000..8123f4620 --- /dev/null +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.CommandLine; +using System.CommandLine.Invocation; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace Microsoft.OpenApi.Hidi.Handlers +{ + internal class TransformCommandHandler : ICommandHandler + { + public Option DescriptionOption { get; set; } + public Option CsdlOption { get; set; } + public Option CsdlFilterOption { get; set; } + public Option OutputOption { get; set; } + public Option CleanOutputOption { get; set; } + public Option VersionOption { get; set; } + public Option FormatOption { get; set; } + public Option TerseOutputOption { get; set; } + public Option LogLevelOption { get; set; } + public Option FilterByOperationIdsOption { get; set; } + public Option FilterByTagsOption { get; set; } + public Option FilterByCollectionOption { get; set; } + public Option InlineLocalOption { get; set; } + public Option InlineExternalOption { get; set; } + + public int Invoke(InvocationContext context) + { + return InvokeAsync(context).GetAwaiter().GetResult(); + } + public async Task InvokeAsync(InvocationContext context) + { + string openapi = context.ParseResult.GetValueForOption(DescriptionOption); + string csdlFilter = context.ParseResult.GetValueForOption(CsdlFilterOption); + string csdl = context.ParseResult.GetValueForOption(CsdlOption); + FileInfo output = context.ParseResult.GetValueForOption(OutputOption); + bool cleanOutput = context.ParseResult.GetValueForOption(CleanOutputOption); + string? version = context.ParseResult.GetValueForOption(VersionOption); + OpenApiFormat? format = context.ParseResult.GetValueForOption(FormatOption); + bool terseOutput = context.ParseResult.GetValueForOption(TerseOutputOption); + LogLevel logLevel = context.ParseResult.GetValueForOption(LogLevelOption); + bool inlineLocal = context.ParseResult.GetValueForOption(InlineLocalOption); + bool inlineExternal = context.ParseResult.GetValueForOption(InlineExternalOption); + string filterbyoperationids = context.ParseResult.GetValueForOption(FilterByOperationIdsOption); + string filterbytags = context.ParseResult.GetValueForOption(FilterByTagsOption); + string filterbycollection = context.ParseResult.GetValueForOption(FilterByCollectionOption); + CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken)); + + var logger = Logger.ConfigureLogger(logLevel); + + try + { + await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, logLevel, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, cancellationToken); + + return 0; + } + catch (Exception ex) + { +#if DEBUG + logger.LogCritical(ex, ex.Message); + throw; // so debug tools go straight to the source of the exception when attached +#else + logger.LogCritical( ex.Message); + return 1; +#endif + } + } + } +} diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs new file mode 100644 index 000000000..84ffcc122 --- /dev/null +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.CommandLine; +using System.CommandLine.Invocation; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace Microsoft.OpenApi.Hidi.Handlers +{ + internal class ValidateCommandHandler : ICommandHandler + { + public Option DescriptionOption { get; set; } + public Option LogLevelOption { get; set; } + + public int Invoke(InvocationContext context) + { + return InvokeAsync(context).GetAwaiter().GetResult(); + } + public async Task InvokeAsync(InvocationContext context) + { + string openapi = context.ParseResult.GetValueForOption(DescriptionOption); + LogLevel logLevel = context.ParseResult.GetValueForOption(LogLevelOption); + CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken)); + + + var logger = Logger.ConfigureLogger(logLevel); + + try + { + await OpenApiService.ValidateOpenApiDocument(openapi, logLevel, cancellationToken); + return 0; + } + catch (Exception ex) + { +#if DEBUG + logger.LogCritical(ex, ex.Message); + throw; // so debug tools go straight to the source of the exception when attached +#else + logger.LogCritical( ex.Message); + Environment.Exit(1); + return 1; +#endif + } + } + } +} diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index cee484046..e48cecc8b 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -37,13 +37,13 @@ - - - - - - - + + + + + + + diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index c8ba8fdcd..88c72fa8b 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.CommandLine; using System.IO; -using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Hidi.Handlers; namespace Microsoft.OpenApi.Hidi { @@ -66,7 +65,11 @@ static async Task Main(string[] args) logLevelOption }; - validateCommand.SetHandler(OpenApiService.ValidateOpenApiDocument, descriptionOption, logLevelOption); + validateCommand.Handler = new ValidateCommandHandler + { + DescriptionOption = descriptionOption, + LogLevelOption = logLevelOption + }; var transformCommand = new Command("transform") { @@ -86,8 +89,23 @@ static async Task Main(string[] args) inlineExternalOption }; - transformCommand.SetHandler ( - OpenApiService.TransformOpenApiDocument, descriptionOption, csdlOption, csdlFilterOption, outputOption, cleanOutputOption, versionOption, formatOption, terseOutputOption, logLevelOption, inlineLocalOption, inlineExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption); + transformCommand.Handler = new TransformCommandHandler + { + DescriptionOption = descriptionOption, + CsdlOption = csdlOption, + CsdlFilterOption = csdlFilterOption, + OutputOption = outputOption, + CleanOutputOption = cleanOutputOption, + VersionOption = versionOption, + FormatOption = formatOption, + TerseOutputOption = terseOutputOption, + LogLevelOption = logLevelOption, + FilterByOperationIdsOption = filterByOperationIdsOption, + FilterByTagsOption = filterByTagsOption, + FilterByCollectionOption = filterByCollectionOption, + InlineLocalOption = inlineLocalOption, + InlineExternalOption = inlineExternalOption + }; rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); From 8a91397ceb4a9ebe7d5de38c47d668e13e6cbd2e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 1 Aug 2022 10:46:07 +0300 Subject: [PATCH 157/855] Add logger class for easy reuse and clean up code --- src/Microsoft.OpenApi.Hidi/Logger.cs | 35 ++++++++++++++++++++ src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 34 ++++--------------- 2 files changed, 42 insertions(+), 27 deletions(-) create mode 100644 src/Microsoft.OpenApi.Hidi/Logger.cs diff --git a/src/Microsoft.OpenApi.Hidi/Logger.cs b/src/Microsoft.OpenApi.Hidi/Logger.cs new file mode 100644 index 000000000..cca906949 --- /dev/null +++ b/src/Microsoft.OpenApi.Hidi/Logger.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Microsoft.Extensions.Logging; + +namespace Microsoft.OpenApi.Hidi +{ + public class Logger + { + public static ILogger ConfigureLogger(LogLevel logLevel) + { + // Configure logger options +#if DEBUG + logLevel = logLevel > LogLevel.Debug ? LogLevel.Debug : logLevel; +#endif + + using var loggerFactory = LoggerFactory.Create((builder) => + { + builder + .AddSimpleConsole(c => + { + c.IncludeScopes = true; + }) +#if DEBUG + .AddDebug() +#endif + .SetMinimumLevel(logLevel); + }); + + var logger = loggerFactory.CreateLogger(); + + return logger; + } + } +} diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 8e1838d95..79b518507 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -26,7 +26,6 @@ using System.Threading; using System.Xml.Xsl; using System.Xml; -using System.Runtime.CompilerServices; using System.Reflection; namespace Microsoft.OpenApi.Hidi @@ -36,7 +35,7 @@ public class OpenApiService /// /// Implementation of the transform command /// - public static async Task TransformOpenApiDocument( + public static async Task TransformOpenApiDocument( string openapi, string csdl, string csdlFilter, @@ -54,8 +53,7 @@ public static async Task TransformOpenApiDocument( CancellationToken cancellationToken ) { - using var loggerFactory = ConfigureLoggerInstance(loglevel); - var logger = loggerFactory.CreateLogger(); + var logger = Logger.ConfigureLogger(loglevel); try { @@ -212,18 +210,11 @@ CancellationToken cancellationToken logger.LogTrace($"Finished serializing in {stopwatch.ElapsedMilliseconds}ms"); textWriter.Flush(); } - return 0; } catch (Exception ex) { -#if DEBUG - logger.LogCritical(ex, ex.Message); -#else - logger.LogCritical(ex.Message); - -#endif - return 1; - } + throw new InvalidOperationException($"Could not transform the document, reason: {ex.Message}", ex); + } } private static XslCompiledTransform GetFilterTransform() @@ -249,18 +240,15 @@ private static Stream ApplyFilter(string csdl, string entitySetOrSingleton, XslC return stream; } - - /// /// Implementation of the validate command /// - public static async Task ValidateOpenApiDocument( + public static async Task ValidateOpenApiDocument( string openapi, LogLevel loglevel, CancellationToken cancellationToken) { - using var loggerFactory = ConfigureLoggerInstance(loglevel); - var logger = loggerFactory.CreateLogger(); + var logger = Logger.ConfigureLogger(loglevel); try { @@ -308,19 +296,11 @@ public static async Task ValidateOpenApiDocument( logger.LogTrace("Finished walking through the OpenApi document. Generating a statistics report.."); logger.LogInformation(statsVisitor.GetStatisticsReport()); } - - return 0; } catch (Exception ex) { -#if DEBUG - logger.LogCritical(ex, ex.Message); -#else - logger.LogCritical(ex.Message); -#endif - return 1; + throw new InvalidOperationException($"Could not validate the document, reason: {ex.Message}", ex); } - } /// From b4c38cf555fab7584a882556a391833d1296c5cc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Aug 2022 21:11:50 +0000 Subject: [PATCH 158/855] Bump Verify.Xunit from 17.4.2 to 17.5.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.4.2 to 17.5.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.4.2...17.5.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 5104ebbe9..986b2cb18 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 3e89450df6823cf49c6ac9a4cd5e4014247a30e6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Aug 2022 23:25:20 +0000 Subject: [PATCH 159/855] Bump xunit from 2.4.1 to 2.4.2 Bumps [xunit](https://github.com/xunit/xunit) from 2.4.1 to 2.4.2. - [Release notes](https://github.com/xunit/xunit/releases) - [Commits](https://github.com/xunit/xunit/compare/2.4.1...2.4.2) --- updated-dependencies: - dependency-name: xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index fb6eaecc1..b74df3589 100644 --- a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -11,7 +11,7 @@ - + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index bfb749d0f..e89e47745 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -257,7 +257,7 @@ - + all diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 6f1763b30..9a6c89d88 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -10,7 +10,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 986b2cb18..80cf71300 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -21,7 +21,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive From 5fd60398c3347ec814f9f65b38fbc164055601fe Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 2 Aug 2022 12:13:07 +0300 Subject: [PATCH 160/855] Update the validation process to be recursive --- .../Validations/Rules/OpenApiSchemaRules.cs | 87 ++++++++++++------- 1 file changed, 56 insertions(+), 31 deletions(-) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index 0b72ebc52..e6316588c 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; using System.Collections.Generic; @@ -11,7 +10,6 @@ namespace Microsoft.OpenApi.Validations.Rules /// /// The validation rules for . /// - [OpenApiRule] public static class OpenApiSchemaRules { @@ -70,50 +68,77 @@ public static class OpenApiSchemaRules if (schema.Reference != null && schema.Discriminator != null) { - if (!schema.Required.Contains(schema.Discriminator?.PropertyName)) + var discriminator = schema.Discriminator?.PropertyName; + var schemaReferenceId = schema.Reference.Id; + + if (!ValidateChildSchemaAgainstDiscriminator(schema, discriminator, schemaReferenceId, context)) { - // check schema.OneOf, schema.AnyOf or schema.AllOf - if(schema.OneOf.Count != 0) - { - ValidateDiscriminatorAgainstChildSchema(schema.OneOf, schema, context); - } - else if (schema.AnyOf.Count != 0) - { - ValidateDiscriminatorAgainstChildSchema(schema.AnyOf, schema, context); - } - else if (schema.AllOf.Count != 0) - { - ValidateDiscriminatorAgainstChildSchema(schema.AllOf, schema, context); - } - else - { - context.CreateError(nameof(ValidateSchemaDiscriminator), - string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, - schema.Reference.Id, schema.Discriminator.PropertyName)); - } + context.CreateError(nameof(ValidateSchemaDiscriminator), + string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, + schemaReferenceId, discriminator)); } } - + context.Exit(); }); /// /// Validates the property name in the discriminator against the ones present in the children schema /// - /// The derived schema. /// The parent schema. + /// Adds support for polymorphism. The discriminator is an object name that is used to differentiate + /// between other schemas which may satisfy the payload description. + /// /// A validation context. - public static void ValidateDiscriminatorAgainstChildSchema(IList childSchema, OpenApiSchema schema, IValidationContext context) + public static bool ValidateChildSchemaAgainstDiscriminator(OpenApiSchema schema, string discriminator, string schemaReferenceId, IValidationContext context) { - foreach (var schemaItem in childSchema) + bool containsDiscriminator = false; + + if (!schema.Required.Contains(discriminator)) { - if (!schemaItem.Properties.Keys.Contains(schema.Discriminator?.PropertyName)) + // recursively check nested schema.OneOf, schema.AnyOf or schema.AllOf and their required fields for the discriminator + if (schema.OneOf.Count != 0) + { + return TraverseSchemaElements(discriminator, schema.OneOf, schemaReferenceId, context, containsDiscriminator); + } + if (schema.AnyOf.Count != 0) { - context.CreateError(nameof(ValidateSchemaDiscriminator), - string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, - schema.Reference.Id, schema.Discriminator.PropertyName)); + return TraverseSchemaElements(discriminator, schema.AnyOf, schemaReferenceId, context, containsDiscriminator); } - } + if (schema.AllOf.Count != 0) + { + return TraverseSchemaElements(discriminator, schema.AllOf, schemaReferenceId, context, containsDiscriminator); + } + } + + return containsDiscriminator; + } + + /// + /// Traverses the schema elements and checks whether the schema contains the discriminator. + /// + /// Adds support for polymorphism. The discriminator is an object name that is used to differentiate + /// between other schemas which may satisfy the payload description. + /// The child schema. + /// The schema reference Id. + /// A validation context. + /// Tracks whether the discriminator is present. + /// + public static bool TraverseSchemaElements(string discriminator, IList childSchema, string schemaReferenceId, IValidationContext context, bool containsDiscriminator) + { + foreach (var childItem in childSchema) + { + if (!childItem.Properties.ContainsKey(discriminator) && !childItem.Required.Contains(discriminator)) + { + return ValidateChildSchemaAgainstDiscriminator(childItem, discriminator, schemaReferenceId, context); + } + else + { + return containsDiscriminator = true; + } + } + + return containsDiscriminator; } } } From 2707493e77b3dcac79e1531bd46fe550e2f36d9b Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 2 Aug 2022 15:39:51 +0300 Subject: [PATCH 161/855] Code cleanup --- .../Validations/Rules/OpenApiSchemaRules.cs | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index e6316588c..3b274232e 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -68,14 +68,13 @@ public static class OpenApiSchemaRules if (schema.Reference != null && schema.Discriminator != null) { - var discriminator = schema.Discriminator?.PropertyName; - var schemaReferenceId = schema.Reference.Id; + var discriminatorName = schema.Discriminator?.PropertyName; - if (!ValidateChildSchemaAgainstDiscriminator(schema, discriminator, schemaReferenceId, context)) + if (!ValidateChildSchemaAgainstDiscriminator(schema, discriminatorName)) { context.CreateError(nameof(ValidateSchemaDiscriminator), string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, - schemaReferenceId, discriminator)); + schema.Reference.Id, discriminatorName)); } } @@ -86,30 +85,32 @@ public static class OpenApiSchemaRules /// Validates the property name in the discriminator against the ones present in the children schema /// /// The parent schema. - /// Adds support for polymorphism. The discriminator is an object name that is used to differentiate + /// Adds support for polymorphism. The discriminator is an object name that is used to differentiate /// between other schemas which may satisfy the payload description. - /// - /// A validation context. - public static bool ValidateChildSchemaAgainstDiscriminator(OpenApiSchema schema, string discriminator, string schemaReferenceId, IValidationContext context) + public static bool ValidateChildSchemaAgainstDiscriminator(OpenApiSchema schema, string discriminatorName) { bool containsDiscriminator = false; - if (!schema.Required.Contains(discriminator)) + if (!schema.Required?.Contains(discriminatorName) ?? false) { // recursively check nested schema.OneOf, schema.AnyOf or schema.AllOf and their required fields for the discriminator if (schema.OneOf.Count != 0) { - return TraverseSchemaElements(discriminator, schema.OneOf, schemaReferenceId, context, containsDiscriminator); + return TraverseSchemaElements(discriminatorName, schema.OneOf, ref containsDiscriminator); } if (schema.AnyOf.Count != 0) { - return TraverseSchemaElements(discriminator, schema.AnyOf, schemaReferenceId, context, containsDiscriminator); + return TraverseSchemaElements(discriminatorName, schema.AnyOf, ref containsDiscriminator); } if (schema.AllOf.Count != 0) { - return TraverseSchemaElements(discriminator, schema.AllOf, schemaReferenceId, context, containsDiscriminator); + return TraverseSchemaElements(discriminatorName, schema.AllOf, ref containsDiscriminator); } } + else + { + return true; + } return containsDiscriminator; } @@ -117,20 +118,19 @@ public static bool ValidateChildSchemaAgainstDiscriminator(OpenApiSchema schema, /// /// Traverses the schema elements and checks whether the schema contains the discriminator. /// - /// Adds support for polymorphism. The discriminator is an object name that is used to differentiate + /// Adds support for polymorphism. The discriminator is an object name that is used to differentiate /// between other schemas which may satisfy the payload description. /// The child schema. - /// The schema reference Id. - /// A validation context. /// Tracks whether the discriminator is present. /// - public static bool TraverseSchemaElements(string discriminator, IList childSchema, string schemaReferenceId, IValidationContext context, bool containsDiscriminator) + public static bool TraverseSchemaElements(string discriminatorName, IList childSchema, ref bool containsDiscriminator) { foreach (var childItem in childSchema) { - if (!childItem.Properties.ContainsKey(discriminator) && !childItem.Required.Contains(discriminator)) + if ((!childItem.Properties?.ContainsKey(discriminatorName) ?? false) && + (!childItem.Required?.Contains(discriminatorName) ?? false)) { - return ValidateChildSchemaAgainstDiscriminator(childItem, discriminator, schemaReferenceId, context); + return ValidateChildSchemaAgainstDiscriminator(childItem, discriminatorName); } else { From 13fa9e82cd09007f416f2ae117f58594bfca6864 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 2 Aug 2022 15:44:13 +0300 Subject: [PATCH 162/855] Update public API interface --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index dc42f5485..87300f76d 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1283,7 +1283,8 @@ namespace Microsoft.OpenApi.Validations.Rules { public static Microsoft.OpenApi.Validations.ValidationRule SchemaMismatchedDataType { get; } public static Microsoft.OpenApi.Validations.ValidationRule ValidateSchemaDiscriminator { get; } - public static void ValidateDiscriminatorAgainstChildSchema(System.Collections.Generic.IList childSchema, Microsoft.OpenApi.Models.OpenApiSchema schema, Microsoft.OpenApi.Validations.IValidationContext context) { } + public static bool TraverseSchemaElements(string discriminatorName, System.Collections.Generic.IList childSchema, ref bool containsDiscriminator) { } + public static bool ValidateChildSchemaAgainstDiscriminator(Microsoft.OpenApi.Models.OpenApiSchema schema, string discriminatorName) { } } [Microsoft.OpenApi.Validations.Rules.OpenApiRule] public static class OpenApiServerRules From 8bb1a19ba2da4b5b43c1e7a32d58bfb4495045ad Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 2 Aug 2022 17:06:16 +0300 Subject: [PATCH 163/855] Treat an empty string as valid and only check for null --- src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs index 1e4739374..4d7f11032 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs @@ -393,9 +393,9 @@ private bool IsScopeType(ScopeType type) /// property name protected void VerifyCanWritePropertyName(string name) { - if (string.IsNullOrWhiteSpace(name)) + if (name == null) { - throw Error.ArgumentNullOrWhiteSpace(nameof(name)); + throw Error.ArgumentNull(nameof(name)); } if (Scopes.Count == 0) From 6cca4012709a5f99f2ef888f2baf7fd2c7a4f6dd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 2 Aug 2022 21:07:24 +0000 Subject: [PATCH 164/855] Bump Moq from 4.18.1 to 4.18.2 Bumps [Moq](https://github.com/moq/moq4) from 4.18.1 to 4.18.2. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/main/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/compare/v4.18.1...v4.18.2) --- updated-dependencies: - dependency-name: Moq dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index b74df3589..de148b7d3 100644 --- a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -10,7 +10,7 @@ - + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 80cf71300..04010213b 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -17,7 +17,7 @@ - + From a3b4b0d425d3a65791812e920df90baa7ddab687 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 3 Aug 2022 11:27:45 +0300 Subject: [PATCH 165/855] Clean up code --- src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs index 84ffcc122..194a1eba8 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs @@ -40,7 +40,6 @@ public async Task InvokeAsync(InvocationContext context) throw; // so debug tools go straight to the source of the exception when attached #else logger.LogCritical( ex.Message); - Environment.Exit(1); return 1; #endif } From 02570f58a9c8de39f1a211cc9180f944d0d359ef Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 3 Aug 2022 17:16:21 +0300 Subject: [PATCH 166/855] Refactor code --- .../Handlers/TransformCommandHandler.cs | 4 ++-- .../Handlers/ValidateCommandHandler.cs | 4 ++-- src/Microsoft.OpenApi.Hidi/Logger.cs | 8 ++------ src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 16 ++++++++-------- 4 files changed, 14 insertions(+), 18 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index 8123f4620..e8d9431de 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -50,8 +50,8 @@ public async Task InvokeAsync(InvocationContext context) string filterbycollection = context.ParseResult.GetValueForOption(FilterByCollectionOption); CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken)); - var logger = Logger.ConfigureLogger(logLevel); - + using var loggerFactory = Logger.ConfigureLogger(logLevel); + var logger = loggerFactory.CreateLogger(); try { await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, logLevel, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, cancellationToken); diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs index 194a1eba8..2faa771ea 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs @@ -26,8 +26,8 @@ public async Task InvokeAsync(InvocationContext context) CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken)); - var logger = Logger.ConfigureLogger(logLevel); - + using var loggerFactory = Logger.ConfigureLogger(logLevel); + var logger = loggerFactory.CreateLogger(); try { await OpenApiService.ValidateOpenApiDocument(openapi, logLevel, cancellationToken); diff --git a/src/Microsoft.OpenApi.Hidi/Logger.cs b/src/Microsoft.OpenApi.Hidi/Logger.cs index cca906949..2b02e9600 100644 --- a/src/Microsoft.OpenApi.Hidi/Logger.cs +++ b/src/Microsoft.OpenApi.Hidi/Logger.cs @@ -7,14 +7,14 @@ namespace Microsoft.OpenApi.Hidi { public class Logger { - public static ILogger ConfigureLogger(LogLevel logLevel) + public static ILoggerFactory ConfigureLogger(LogLevel logLevel) { // Configure logger options #if DEBUG logLevel = logLevel > LogLevel.Debug ? LogLevel.Debug : logLevel; #endif - using var loggerFactory = LoggerFactory.Create((builder) => + return LoggerFactory.Create((builder) => { builder .AddSimpleConsole(c => @@ -26,10 +26,6 @@ public static ILogger ConfigureLogger(LogLevel logLevel) #endif .SetMinimumLevel(logLevel); }); - - var logger = loggerFactory.CreateLogger(); - - return logger; } } } diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 0d2d5d531..c37c9479d 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.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; @@ -44,7 +44,7 @@ public static async Task TransformOpenApiDocument( string? version, OpenApiFormat? format, bool terseOutput, - LogLevel loglevel, + LogLevel logLevel, bool inlineLocal, bool inlineExternal, string filterbyoperationids, @@ -53,8 +53,8 @@ public static async Task TransformOpenApiDocument( CancellationToken cancellationToken ) { - var logger = Logger.ConfigureLogger(loglevel); - + using var loggerFactory = Logger.ConfigureLogger(logLevel); + var logger = loggerFactory.CreateLogger(); try { if (string.IsNullOrEmpty(openapi) && string.IsNullOrEmpty(csdl)) @@ -246,11 +246,11 @@ private static Stream ApplyFilter(string csdl, string entitySetOrSingleton, XslC /// public static async Task ValidateOpenApiDocument( string openapi, - LogLevel loglevel, + LogLevel logLevel, CancellationToken cancellationToken) { - var logger = Logger.ConfigureLogger(loglevel); - + using var loggerFactory = Logger.ConfigureLogger(logLevel); + var logger = loggerFactory.CreateLogger(); try { if (string.IsNullOrEmpty(openapi)) @@ -578,7 +578,7 @@ private static ILoggerFactory ConfigureLoggerInstance(LogLevel loglevel) loglevel = loglevel > LogLevel.Debug ? LogLevel.Debug : loglevel; #endif - return LoggerFactory.Create((builder) => { + return Microsoft.Extensions.Logging.LoggerFactory.Create((builder) => { builder .AddSimpleConsole(c => { c.IncludeScopes = true; From f0a0eb84a445b2760eab119cd668468a5d0be5cd Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 4 Aug 2022 14:31:38 +0300 Subject: [PATCH 167/855] Revert packages to stable versions --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 71570a9c4..c35c40209 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -37,10 +37,10 @@ - - - - + + + + From 3682ceaea538e6026c9e81edb78fa52c6c88bc3e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 4 Aug 2022 15:18:13 +0300 Subject: [PATCH 168/855] Clean up code --- .../Validations/Rules/OpenApiSchemaRules.cs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index 3b274232e..a8ed2e93c 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -89,22 +89,20 @@ public static class OpenApiSchemaRules /// between other schemas which may satisfy the payload description. public static bool ValidateChildSchemaAgainstDiscriminator(OpenApiSchema schema, string discriminatorName) { - bool containsDiscriminator = false; - if (!schema.Required?.Contains(discriminatorName) ?? false) { // recursively check nested schema.OneOf, schema.AnyOf or schema.AllOf and their required fields for the discriminator if (schema.OneOf.Count != 0) { - return TraverseSchemaElements(discriminatorName, schema.OneOf, ref containsDiscriminator); + return TraverseSchemaElements(discriminatorName, schema.OneOf); } if (schema.AnyOf.Count != 0) { - return TraverseSchemaElements(discriminatorName, schema.AnyOf, ref containsDiscriminator); + return TraverseSchemaElements(discriminatorName, schema.AnyOf); } if (schema.AllOf.Count != 0) { - return TraverseSchemaElements(discriminatorName, schema.AllOf, ref containsDiscriminator); + return TraverseSchemaElements(discriminatorName, schema.AllOf); } } else @@ -112,7 +110,7 @@ public static bool ValidateChildSchemaAgainstDiscriminator(OpenApiSchema schema, return true; } - return containsDiscriminator; + return false; } /// @@ -121,9 +119,8 @@ public static bool ValidateChildSchemaAgainstDiscriminator(OpenApiSchema schema, /// Adds support for polymorphism. The discriminator is an object name that is used to differentiate /// between other schemas which may satisfy the payload description. /// The child schema. - /// Tracks whether the discriminator is present. /// - public static bool TraverseSchemaElements(string discriminatorName, IList childSchema, ref bool containsDiscriminator) + public static bool TraverseSchemaElements(string discriminatorName, IList childSchema) { foreach (var childItem in childSchema) { @@ -134,11 +131,11 @@ public static bool TraverseSchemaElements(string discriminatorName, IList Date: Thu, 4 Aug 2022 15:36:40 +0300 Subject: [PATCH 169/855] Remove param --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 87300f76d..c8930e9fb 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1283,7 +1283,7 @@ namespace Microsoft.OpenApi.Validations.Rules { public static Microsoft.OpenApi.Validations.ValidationRule SchemaMismatchedDataType { get; } public static Microsoft.OpenApi.Validations.ValidationRule ValidateSchemaDiscriminator { get; } - public static bool TraverseSchemaElements(string discriminatorName, System.Collections.Generic.IList childSchema, ref bool containsDiscriminator) { } + public static bool TraverseSchemaElements(string discriminatorName, System.Collections.Generic.IList childSchema) { } public static bool ValidateChildSchemaAgainstDiscriminator(Microsoft.OpenApi.Models.OpenApiSchema schema, string discriminatorName) { } } [Microsoft.OpenApi.Validations.Rules.OpenApiRule] From d3f9c1ce7644edff613ff07f49f6ecd3a1b86f11 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Aug 2022 21:06:34 +0000 Subject: [PATCH 170/855] Bump docker/build-push-action from 3.1.0 to 3.1.1 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3.1.0 to 3.1.1. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v3.1.0...v3.1.1) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 43ea50e2f..ec86e0b7f 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -30,13 +30,13 @@ jobs: id: getversion - name: Push to GitHub Packages - Nightly if: ${{ github.ref == 'refs/heads/vnext' }} - uses: docker/build-push-action@v3.1.0 + uses: docker/build-push-action@v3.1.1 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly - name: Push to GitHub Packages - Release if: ${{ github.ref == 'refs/heads/master' }} - uses: docker/build-push-action@v3.1.0 + uses: docker/build-push-action@v3.1.1 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest,${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.getversion.outputs.version }} From c4cd7c938264945e5d1a6c59067070124bf8b64e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Aug 2022 21:12:52 +0000 Subject: [PATCH 171/855] Bump Verify.Xunit from 17.5.0 to 17.7.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.5.0 to 17.7.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.5.0...17.7.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 04010213b..75b34ad22 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 5c9e0783e124fd358589e672e0985a286a6b45bb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 9 Aug 2022 21:08:22 +0000 Subject: [PATCH 172/855] Bump Verify.Xunit from 17.7.0 to 17.8.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.7.0 to 17.8.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.7.0...17.8.1) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 75b34ad22..8baa82c36 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From c6417ba42411fd30e2864243db4ce194a5fd2743 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 10 Aug 2022 21:12:33 +0000 Subject: [PATCH 173/855] Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.2.0 to 17.3.0. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v17.2.0...v17.3.0) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index de148b7d3..6045d85b6 100644 --- a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index e89e47745..83e5482a7 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -250,7 +250,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 9a6c89d88..ef9886bb9 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -8,7 +8,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 8baa82c36..1d8d8c45b 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -16,7 +16,7 @@ - + From 50610bef8a1e43ea6d67cab95bfd20318e05cb93 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 11 Aug 2022 09:17:40 +0300 Subject: [PATCH 174/855] Adds an issue template for a unified and concise bug report --- .github/ISSUE_TEMPLATE/bug_report.md | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..a7e4e9837 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,30 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the current behavior: + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots/Code Snippets** +If applicable, add screenshots or code snippets to help explain your problem. + +**Your environment:** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + - Desktop or mobile + - If applicable, Link to your project + +**Additional context** +Add any other context about the problem here. From 9cbac86671e48f46d9ee2e109848f4b47daecb78 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 11 Aug 2022 09:24:17 +0300 Subject: [PATCH 175/855] Adds a feature template --- .github/ISSUE_TEMPLATE/feature_request.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..021458556 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. From fc43d0c322e2a2d82963c0e662c37c05b4621b28 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 11 Aug 2022 09:33:07 +0300 Subject: [PATCH 176/855] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9405526bf..0190e572d 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,8 @@ Project Objectives # Installation -- Install core Nuget package `Microsoft.OpenApi` -- Install readers Nuget package `Microsoft.OpenApi.Readers` +- Install core Nuget package [**Microsoft.OpenApi**](https://www.nuget.org/packages/Microsoft.OpenApi) +- Install readers Nuget package [**Microsoft.OpenApi.Readers**](https://www.nuget.org/packages/Microsoft.OpenApi.Readers) # Processors The OpenAPI.NET project holds the base object model for representing OpenAPI documents as .NET objects. Some developers have found the need to write processors that convert other data formats into this OpenAPI.NET object model. We'd like to curate that list of processors in this section of the readme. From aba7694d96acb84e65c9f15fc5446584ec50e8ec Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 11 Aug 2022 10:03:06 +0300 Subject: [PATCH 177/855] Edit bug template --- .github/ISSUE_TEMPLATE/bug_report.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index a7e4e9837..2c10124b0 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -17,7 +17,7 @@ Steps to reproduce the current behavior: A clear and concise description of what you expected to happen. **Screenshots/Code Snippets** -If applicable, add screenshots or code snippets to help explain your problem. +If applicable, add screenshots of the stack trace or a code snippet to help explain your problem. **Your environment:** - OS: [e.g. iOS] @@ -25,6 +25,6 @@ If applicable, add screenshots or code snippets to help explain your problem. - Version [e.g. 22] - Desktop or mobile - If applicable, Link to your project - + **Additional context** Add any other context about the problem here. From b0557a13ef24cc7f5f3d9e3a02432f9e84688158 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 12 Aug 2022 15:43:20 +0300 Subject: [PATCH 178/855] Add defensive programming --- .../Models/OpenApiCallback.cs | 8 +- .../Models/OpenApiComponents.cs | 20 ++--- .../Models/OpenApiContact.cs | 8 +- .../Models/OpenApiDiscriminator.cs | 4 +- .../Models/OpenApiDocument.cs | 18 ++--- .../Models/OpenApiEncoding.cs | 12 +-- .../Models/OpenApiExample.cs | 14 ++-- .../Models/OpenApiExternalDocs.cs | 6 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 28 +++---- src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 14 ++-- .../Models/OpenApiLicense.cs | 6 +- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 18 ++--- .../Models/OpenApiMediaType.cs | 10 +-- .../Models/OpenApiOAuthFlow.cs | 10 +-- .../Models/OpenApiOAuthFlows.cs | 10 +-- .../Models/OpenApiOperation.cs | 26 +++---- .../Models/OpenApiParameter.cs | 32 ++++---- .../Models/OpenApiPathItem.cs | 16 ++-- .../Models/OpenApiReference.cs | 8 +- .../Models/OpenApiRequestBody.cs | 12 +-- .../Models/OpenApiResponse.cs | 14 ++-- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 76 +++++++++---------- .../Models/OpenApiSecurityScheme.cs | 22 +++--- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 8 +- .../Models/OpenApiServerVariable.cs | 8 +- src/Microsoft.OpenApi/Models/OpenApiTag.cs | 12 +-- src/Microsoft.OpenApi/Models/OpenApiXml.cs | 12 +-- .../Models/RuntimeExpressionAnyWrapper.cs | 4 +- 28 files changed, 218 insertions(+), 218 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index e9701b17c..beed0ad06 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -45,10 +45,10 @@ public OpenApiCallback() { } /// public OpenApiCallback(OpenApiCallback callback) { - PathItems = new(callback.PathItems); - UnresolvedReference = callback.UnresolvedReference; - Reference = new(callback.Reference); - Extensions = new Dictionary(callback.Extensions); + PathItems = new(callback?.PathItems); + UnresolvedReference = callback?.UnresolvedReference ?? false; + Reference = new(callback?.Reference); + Extensions = callback?.Extensions != null ? new Dictionary(callback?.Extensions) : callback?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index c23e569c5..7e4a481ac 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -78,16 +78,16 @@ public OpenApiComponents() { } /// public OpenApiComponents(OpenApiComponents components) { - Schemas = new Dictionary(components.Schemas); - Responses = new Dictionary(components.Responses); - Parameters = new Dictionary(components.Parameters); - Examples = new Dictionary(components.Examples); - RequestBodies = new Dictionary(components.RequestBodies); - Headers = new Dictionary(components.Headers); - SecuritySchemes = new Dictionary(components.SecuritySchemes); - Links = new Dictionary(components.Links); - Callbacks = new Dictionary(components.Callbacks); - Extensions = new Dictionary(components.Extensions); + Schemas = components?.Schemas != null ? new Dictionary(components?.Schemas) : components?.Schemas; + Responses = components?.Responses != null ? new Dictionary(components?.Responses) : components?.Responses; + Parameters = components?.Parameters != null ? new Dictionary(components?.Parameters) : components?.Parameters; + Examples = components?.Examples != null ? new Dictionary(components?.Examples) : components?.Examples; + RequestBodies = components?.RequestBodies != null ? new Dictionary(components?.RequestBodies) : components?.RequestBodies; + Headers = components?.Headers != null ? new Dictionary(components?.Headers) : components?.Headers; + SecuritySchemes = components?.SecuritySchemes != null ? new Dictionary(components?.SecuritySchemes) : components?.SecuritySchemes; + Links = components?.Links != null ? new Dictionary(components?.Links) : components?.Links; + Callbacks = components?.Callbacks != null ? new Dictionary(components?.Callbacks) : components?.Callbacks; + Extensions = components?.Extensions != null ? new Dictionary(components?.Extensions) : components?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 9447d424e..28001e928 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -45,10 +45,10 @@ public OpenApiContact() { } /// public OpenApiContact(OpenApiContact contact) { - Name = contact.Name; - Url = new Uri(contact.Url.OriginalString); - Email = contact.Email; - Extensions = new Dictionary(contact.Extensions); + Name = contact?.Name; + Url = contact?.Url; + Email = contact?.Email; + Extensions = contact?.Extensions != null ? new Dictionary(contact?.Extensions) : contact?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs index e03c7d59a..f39819a0a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs @@ -32,8 +32,8 @@ public OpenApiDiscriminator() { } /// public OpenApiDiscriminator(OpenApiDiscriminator discriminator) { - PropertyName = discriminator.PropertyName; - Mapping = new Dictionary(discriminator.Mapping); + PropertyName = discriminator?.PropertyName; + Mapping = discriminator?.Mapping != null ? new Dictionary(discriminator?.Mapping) : discriminator?.Mapping; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 44cbc71ab..21c5f2e53 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -72,15 +72,15 @@ public OpenApiDocument() {} /// public OpenApiDocument(OpenApiDocument document) { - Workspace = new(document.Workspace); - Info = new(document.Info); - Servers = new List(document.Servers); - Paths = new(document.Paths); - Components = new(document.Components); - SecurityRequirements = new List(document.SecurityRequirements); - Tags = new List(document.Tags); - ExternalDocs = new(document.ExternalDocs); - Extensions = new Dictionary(document.Extensions); + Workspace = new(document?.Workspace); + Info = new(document?.Info); + Servers = document?.Servers != null ? new List(document?.Servers) : document?.Servers; + Paths = new(document?.Paths); + Components = new(document?.Components); + SecurityRequirements = document?.SecurityRequirements != null ? new List(document?.SecurityRequirements) : document?.SecurityRequirements; + Tags = document?.Tags != null ? new List(document?.Tags) : document?.Tags; + ExternalDocs = new(document?.ExternalDocs); + Extensions = document?.Extensions != null ? new Dictionary(document?.Extensions) : document?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index 533cb7e80..bc154e8fb 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -63,12 +63,12 @@ public OpenApiEncoding() {} /// public OpenApiEncoding(OpenApiEncoding encoding) { - ContentType = encoding.ContentType; - Headers = new Dictionary(encoding.Headers); - Style = encoding.Style; - Explode = encoding.Explode; - AllowReserved = encoding.AllowReserved; - Extensions = new Dictionary(encoding.Extensions); + ContentType = encoding?.ContentType; + Headers = encoding?.Headers != null ? new Dictionary(encoding?.Headers) : encoding?.Headers; + Style = encoding?.Style; + Explode = encoding?.Explode ?? false; + AllowReserved = encoding?.AllowReserved ?? false; + Extensions = encoding?.Extensions != null ? new Dictionary(encoding?.Extensions) : encoding?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 5e105be26..b9bfc031a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -64,13 +64,13 @@ public OpenApiExample() {} /// public OpenApiExample(OpenApiExample example) { - Summary = example.Summary; - Description = example.Description; - Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example.Value); - ExternalValue = example.ExternalValue; - Extensions = new Dictionary(example.Extensions); - Reference = new(example.Reference); - UnresolvedReference = example.UnresolvedReference; + Summary = example?.Summary; + Description = example?.Description; + Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example?.Value); + ExternalValue = example?.ExternalValue; + Extensions = example?.Extensions != null ? new Dictionary(example?.Extensions) : example?.Extensions; + Reference = new(example?.Reference); + UnresolvedReference = example?.UnresolvedReference ?? false; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 95af8f01b..040b7d674 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -39,9 +39,9 @@ public OpenApiExternalDocs() {} /// public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) { - Description = externalDocs.Description; - Url = new Uri(externalDocs.Url.OriginalString); - Extensions = new Dictionary(externalDocs.Extensions); + Description = externalDocs?.Description; + Url = externalDocs?.Url != null ? new Uri(externalDocs?.Url?.OriginalString) : externalDocs?.Url; + Extensions = externalDocs?.Extensions != null ? new Dictionary(externalDocs?.Extensions) : externalDocs?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index b91440df8..a7ca745d2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -96,20 +96,20 @@ public OpenApiHeader() {} /// public OpenApiHeader(OpenApiHeader header) { - UnresolvedReference = header.UnresolvedReference; - Reference = new(header.Reference); - Description = header.Description; - Required = header.Required; - Deprecated = header.Deprecated; - AllowEmptyValue = header.AllowEmptyValue; - Style = header.Style; - Explode = header.Explode; - AllowReserved = header.AllowReserved; - Schema = new(header.Schema); - Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header.Example); - Examples = new Dictionary(header.Examples); - Content = new Dictionary(header.Content); - Extensions = new Dictionary(header.Extensions); + UnresolvedReference = header?.UnresolvedReference ?? false; + Reference = new(header?.Reference); + Description = header?.Description; + Required = header?.Required ?? false; + Deprecated = header?.Deprecated ?? false; + AllowEmptyValue = header?.AllowEmptyValue ?? false; + Style = header?.Style; + Explode = header?.Explode ?? false; + AllowReserved = header?.AllowReserved ?? false; + Schema = new(header?.Schema); + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header?.Example); + Examples = header?.Examples != null ? new Dictionary(header?.Examples) : header?.Examples; + Content = header?.Content != null ? new Dictionary(header?.Content) : header?.Content; + Extensions = header?.Extensions != null ? new Dictionary(header?.Extensions) : header?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index c5a44c448..1dcae81e2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -59,13 +59,13 @@ public OpenApiInfo() {} /// public OpenApiInfo(OpenApiInfo info) { - Title = info.Title; - Description = info.Description; - Version = info.Version; - TermsOfService = info.TermsOfService; - Contact = new(info.Contact); - License = new(info.License); - Extensions = new Dictionary(info.Extensions); + Title = info?.Title; + Description = info?.Description; + Version = info?.Version; + TermsOfService = info?.TermsOfService; + Contact = new(info?.Contact); + License = new(info?.License); + Extensions = info?.Extensions != null ? new Dictionary(info?.Extensions) : info?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 431789aac..399441b46 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -39,9 +39,9 @@ public OpenApiLicense() {} /// public OpenApiLicense(OpenApiLicense license) { - Name = license.Name; - Url = new Uri(license.Url.OriginalString); - Extensions = new Dictionary(license.Extensions); + Name = license?.Name; + Url = license?.Url != null ? new Uri(license?.Url?.OriginalString) : license?.Url; + Extensions = license?.Extensions != null ? new Dictionary(license?.Extensions) : license?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index 6ba3a65fd..3a5a72c1d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -71,15 +71,15 @@ public OpenApiLink() {} /// public OpenApiLink(OpenApiLink link) { - OperationRef = link.OperationRef; - OperationId = link.OperationId; - Parameters = new(link.Parameters); - RequestBody = new(link.RequestBody); - Description = link.Description; - Server = new(link.Server); - Extensions = new Dictionary(link.Extensions); - UnresolvedReference = link.UnresolvedReference; - Reference = new(link.Reference); + OperationRef = link?.OperationRef; + OperationId = link?.OperationId; + Parameters = new(link?.Parameters); + RequestBody = new(link?.RequestBody); + Description = link?.Description; + Server = new(link?.Server); + Extensions = link?.Extensions != null ? new Dictionary(link?.Extensions) : link?.Extensions; + UnresolvedReference = link?.UnresolvedReference ?? false; + Reference = new(link?.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 94dcbdfa7..b6245f202 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -53,11 +53,11 @@ public OpenApiMediaType() {} /// public OpenApiMediaType(OpenApiMediaType mediaType) { - Schema = new(mediaType.Schema); - Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType.Example); - Examples = new Dictionary(mediaType.Examples); - Encoding = new Dictionary(mediaType.Encoding); - Extensions = new Dictionary(mediaType.Extensions); + Schema = new(mediaType?.Schema); + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType?.Example); + Examples = mediaType?.Examples != null ? new Dictionary(mediaType?.Examples) : mediaType?.Examples; + Encoding = mediaType?.Encoding != null ? new Dictionary(mediaType?.Encoding) : mediaType?.Encoding; + Extensions = mediaType?.Extensions != null ? new Dictionary(mediaType?.Extensions) : mediaType?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index 02856d4cd..f5a9b46c4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -51,11 +51,11 @@ public OpenApiOAuthFlow() {} /// public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) { - AuthorizationUrl = new Uri(oAuthFlow.AuthorizationUrl.OriginalString); - TokenUrl = new Uri(oAuthFlow.TokenUrl.OriginalString); - RefreshUrl = new Uri(oAuthFlow.RefreshUrl.OriginalString); - Scopes = new Dictionary(oAuthFlow.Scopes); - Extensions = new Dictionary(oAuthFlow.Extensions); + AuthorizationUrl = oAuthFlow?.AuthorizationUrl != null ? new Uri(oAuthFlow?.AuthorizationUrl?.OriginalString) : oAuthFlow?.AuthorizationUrl; + TokenUrl = oAuthFlow?.TokenUrl != null ? new Uri(oAuthFlow?.TokenUrl?.OriginalString) : oAuthFlow?.TokenUrl; + RefreshUrl = oAuthFlow?.RefreshUrl != null ? new Uri(oAuthFlow?.RefreshUrl?.OriginalString) : oAuthFlow?.RefreshUrl; + Scopes = oAuthFlow?.Scopes != null ? new Dictionary(oAuthFlow?.Scopes) : oAuthFlow?.Scopes; + Extensions = oAuthFlow?.Extensions != null ? new Dictionary(oAuthFlow?.Extensions) : oAuthFlow?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index 973a403e0..d286c7641 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -49,11 +49,11 @@ public OpenApiOAuthFlows() {} /// public OpenApiOAuthFlows(OpenApiOAuthFlows oAuthFlows) { - Implicit = new(oAuthFlows.Implicit); - Password = new(oAuthFlows.Password); - ClientCredentials = new(oAuthFlows.ClientCredentials); - AuthorizationCode = new(oAuthFlows.AuthorizationCode); - Extensions = new Dictionary(oAuthFlows.Extensions); + Implicit = new(oAuthFlows?.Implicit); + Password = new(oAuthFlows?.Password); + ClientCredentials = new(oAuthFlows?.ClientCredentials); + AuthorizationCode = new(oAuthFlows?.AuthorizationCode); + Extensions = oAuthFlows?.Extensions != null ? new Dictionary(oAuthFlows?.Extensions) : oAuthFlows?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 775532684..e7f8b8910 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -116,19 +116,19 @@ public OpenApiOperation() {} /// public OpenApiOperation(OpenApiOperation operation) { - Tags = new List(operation.Tags); - Summary = operation.Summary; - Description = operation.Description; - ExternalDocs = new(operation.ExternalDocs); - OperationId = operation.OperationId; - Parameters = new List(operation.Parameters); - RequestBody = new(operation.RequestBody); - Responses = new(operation.Responses); - Callbacks = new Dictionary(operation.Callbacks); - Deprecated = operation.Deprecated; - Security = new List(operation.Security); - Servers = new List(operation.Servers); - Extensions = new Dictionary(operation.Extensions); + Tags = new List(operation?.Tags); + Summary = operation?.Summary; + Description = operation?.Description; + ExternalDocs = new(operation?.ExternalDocs); + OperationId = operation?.OperationId; + Parameters = operation?.Parameters != null ? new List(operation?.Parameters) : operation?.Parameters; + RequestBody = new(operation?.RequestBody); + Responses = new(operation?.Responses); + Callbacks = operation?.Callbacks != null ? new Dictionary(operation?.Callbacks) : operation?.Callbacks; + Deprecated = operation?.Deprecated ?? false; + Security = operation?.Security != null ? new List(operation?.Security) : operation?.Security; + Servers = operation?.Servers != null ? new List(operation?.Servers) : operation?.Servers; + Extensions = operation?.Extensions != null ? new Dictionary(operation?.Extensions) : operation?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index f0b21b0d9..7a429ef0a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -146,22 +146,22 @@ public OpenApiParameter() {} /// public OpenApiParameter(OpenApiParameter parameter) { - UnresolvedReference = parameter.UnresolvedReference; - Reference = new(parameter.Reference); - Name = parameter.Name; - In = parameter.In; - Description = parameter.Description; - Required = parameter.Required; - Style = parameter.Style; - Explode = parameter.Explode; - AllowReserved = parameter.AllowReserved; - Schema = new(parameter.Schema); - Examples = new Dictionary(parameter.Examples); - Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter.Example); - Content = new Dictionary(parameter.Content); - Extensions = new Dictionary(parameter.Extensions); - AllowEmptyValue = parameter.AllowEmptyValue; - Deprecated = parameter.Deprecated; + UnresolvedReference = parameter?.UnresolvedReference ?? false; + Reference = new(parameter?.Reference); + Name = parameter?.Name; + In = parameter?.In; + Description = parameter?.Description; + Required = parameter?.Required ?? false; + Style = parameter?.Style; + Explode = parameter?.Explode ?? false; + AllowReserved = parameter?.AllowReserved ?? false; + Schema = new(parameter?.Schema); + Examples = parameter?.Examples != null ? new Dictionary(parameter?.Examples) : parameter?.Examples; + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); + Content = parameter?.Content != null ? new Dictionary(parameter?.Content) : parameter?.Content; + Extensions = parameter?.Extensions != null ? new Dictionary(parameter?.Extensions) : parameter?.Extensions; + AllowEmptyValue = parameter?.AllowEmptyValue ?? false; + Deprecated = parameter?.Deprecated ?? false; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index 8ce83c9eb..89313be87 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -75,14 +75,14 @@ public OpenApiPathItem() {} /// public OpenApiPathItem(OpenApiPathItem pathItem) { - Summary = pathItem.Summary; - Description = pathItem.Description; - Operations = new Dictionary(pathItem.Operations); - Servers = new List(pathItem.Servers); - Parameters = new List(pathItem.Parameters); - Extensions = new Dictionary(pathItem.Extensions); - UnresolvedReference = pathItem.UnresolvedReference; - Reference = new(pathItem.Reference); + Summary = pathItem?.Summary; + Description = pathItem?.Description; + Operations = pathItem?.Operations != null ? new Dictionary(pathItem?.Operations) : pathItem?.Operations; + Servers = pathItem?.Servers != null ? new List(pathItem?.Servers) : pathItem?.Servers; + Parameters = pathItem?.Parameters != null ? new List(pathItem?.Parameters) : pathItem?.Parameters; + Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem?.Extensions) : pathItem?.Extensions; + UnresolvedReference = pathItem?.UnresolvedReference ?? false; + Reference = new(pathItem?.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index 9213e77bc..31cc5a6e8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -122,10 +122,10 @@ public OpenApiReference() {} /// public OpenApiReference(OpenApiReference reference) { - ExternalResource = reference.ExternalResource; - Type = reference.Type; - Id = reference.Id; - HostDocument = new(reference.HostDocument); + ExternalResource = reference?.ExternalResource; + Type = reference?.Type; + Id = reference?.Id; + HostDocument = new(reference?.HostDocument); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index b82b67e8a..6e7bdaf77 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -55,12 +55,12 @@ public OpenApiRequestBody() { } /// public OpenApiRequestBody(OpenApiRequestBody requestBody) { - UnresolvedReference = requestBody.UnresolvedReference; - Reference = new(requestBody.Reference); - Description = requestBody.Description; - Required = requestBody.Required; - Content = new Dictionary(requestBody.Content); - Extensions = new Dictionary(requestBody.Extensions); + UnresolvedReference = requestBody?.UnresolvedReference ?? false; + Reference = new(requestBody?.Reference); + Description = requestBody?.Description; + Required = requestBody?.Required ?? false; + Content = requestBody?.Content != null ? new Dictionary(requestBody?.Content) : requestBody?.Content; + Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody?.Extensions) : requestBody?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index cf0c796e6..46b7b63b0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -61,13 +61,13 @@ public OpenApiResponse() {} /// public OpenApiResponse(OpenApiResponse response) { - Description = response.Description; - Headers = new Dictionary(response.Headers); - Content = new Dictionary(response.Content); - Links = new Dictionary(response.Links); - Extensions = new Dictionary(response.Extensions); - UnresolvedReference = response.UnresolvedReference; - Reference = new(response.Reference); + Description = response?.Description; + Headers = response?.Headers != null ? new Dictionary(response?.Headers) : response?.Headers; + Content = response?.Content != null ? new Dictionary(response?.Content) : response?.Content; + Links = response?.Links != null ? new Dictionary(response?.Links) : response?.Links; + Extensions = response?.Extensions != null ? new Dictionary(response?.Extensions) : response?.Extensions; + UnresolvedReference = response?.UnresolvedReference ?? false; + Reference = new(response?.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index d43756887..45d520b3a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -252,44 +252,44 @@ public OpenApiSchema() {} /// public OpenApiSchema(OpenApiSchema schema) { - Title = schema.Title; - Type = schema.Type; - Format = schema.Format; - Description = schema.Description; - Maximum = schema.Maximum; - ExclusiveMaximum = schema.ExclusiveMaximum; - Minimum = schema.Minimum; - ExclusiveMinimum = schema.ExclusiveMinimum; - MaxLength = schema.MaxLength; - MinLength = schema.MinLength; - Pattern = schema.Pattern; - MultipleOf = schema.MultipleOf; - Default = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema.Default); - ReadOnly = schema.ReadOnly; - WriteOnly = schema.WriteOnly; - AllOf = new List(schema.AllOf); - OneOf = new List(schema.OneOf); - AnyOf = new List(schema.AnyOf); - Not = new(schema.Not); - Required = new HashSet(schema.Required); - Items = new(schema.Items); - MaxItems = schema.MaxItems; - MinItems = schema.MinItems; - UniqueItems = schema.UniqueItems; - Properties = new Dictionary(schema.Properties); - MaxProperties = schema.MaxProperties; - MinProperties = schema.MinProperties; - AdditionalPropertiesAllowed = schema.AdditionalPropertiesAllowed; - AdditionalProperties = new(schema.AdditionalProperties); - Discriminator = new(schema.Discriminator); - Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema.Example); - Enum = new List(schema.Enum); - Nullable = schema.Nullable; - ExternalDocs = new(schema.ExternalDocs); - Deprecated = schema.Deprecated; - Xml = new(schema.Xml); - UnresolvedReference = schema.UnresolvedReference; - Reference = new(schema.Reference); + Title = schema?.Title; + Type = schema?.Type; + Format = schema?.Format; + Description = schema?.Description; + Maximum = schema?.Maximum; + ExclusiveMaximum = schema?.ExclusiveMaximum; + Minimum = schema?.Minimum; + ExclusiveMinimum = schema?.ExclusiveMinimum; + MaxLength = schema?.MaxLength; + MinLength = schema?.MinLength; + Pattern = schema?.Pattern; + MultipleOf = schema?.MultipleOf; + Default = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema?.Default); + ReadOnly = schema?.ReadOnly ?? false; + WriteOnly = schema?.WriteOnly ?? false; + AllOf = schema?.AllOf != null ? new List(schema?.AllOf) : schema?.AllOf; + OneOf = schema?.OneOf != null ? new List(schema?.OneOf) : schema?.OneOf; + AnyOf = schema?.AnyOf != null ? new List(schema?.AnyOf) : schema?.AnyOf; + Not = new(schema?.Not); + Required = schema?.Required != null ? new HashSet(schema?.Required) : schema?.Required; + Items = new(schema?.Items); + MaxItems = schema?.MaxItems; + MinItems = schema?.MinItems; + UniqueItems = schema?.UniqueItems; + Properties = schema?.Properties != null ? new Dictionary(schema?.Properties) : schema?.Properties; + MaxProperties = schema?.MaxProperties; + MinProperties = schema?.MinProperties; + AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? false; + AdditionalProperties = new(schema?.AdditionalProperties); + Discriminator = new(schema?.Discriminator); + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema?.Example); + Enum = schema?.Enum != null ? new List(schema?.Enum) : schema?.Enum; + Nullable = schema?.Nullable ?? false; + ExternalDocs = new(schema?.ExternalDocs); + Deprecated = schema?.Deprecated ?? false; + Xml = new(schema?.Xml); + UnresolvedReference = schema?.UnresolvedReference; + Reference = new(schema?.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index b87adf573..1bc427e9a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -84,17 +84,17 @@ public OpenApiSecurityScheme() {} /// public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) { - Type = securityScheme.Type; - Description = securityScheme.Description; - Name = securityScheme.Name; - In = securityScheme.In; - Scheme = securityScheme.Scheme; - BearerFormat = securityScheme.BearerFormat; - Flows = new(securityScheme.Flows); - OpenIdConnectUrl = new Uri(securityScheme.OpenIdConnectUrl.OriginalString); - Extensions = new Dictionary(securityScheme.Extensions); - UnresolvedReference = securityScheme.UnresolvedReference; - Reference = new(securityScheme.Reference); + Type = (SecuritySchemeType)(securityScheme?.Type); + Description = securityScheme?.Description; + Name = securityScheme?.Name; + In = (ParameterLocation)(securityScheme?.In); + Scheme = securityScheme?.Scheme; + BearerFormat = securityScheme?.BearerFormat; + Flows = new(securityScheme?.Flows); + OpenIdConnectUrl = new Uri(securityScheme?.OpenIdConnectUrl?.OriginalString); + Extensions = securityScheme?.Extensions != null ? new Dictionary(securityScheme?.Extensions) : securityScheme?.Extensions; + UnresolvedReference = securityScheme?.UnresolvedReference ?? false; + Reference = new(securityScheme?.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index 875bef5c7..c0ec7114a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -46,10 +46,10 @@ public OpenApiServer() {} /// public OpenApiServer(OpenApiServer server) { - Description = server.Description; - Url = server.Url; - Variables = new Dictionary(server.Variables); - Extensions = new Dictionary(server.Extensions); + Description = server?.Description; + Url = server?.Url; + Variables = server?.Variables != null ? new Dictionary(server?.Variables) : server?.Variables; + Extensions = server?.Extensions != null ? new Dictionary(server?.Extensions) : server?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index b1f222e83..70164bc59 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -44,10 +44,10 @@ public OpenApiServerVariable() {} /// public OpenApiServerVariable(OpenApiServerVariable serverVariable) { - Description = serverVariable.Description; - Default = serverVariable.Default; - Enum = new List(serverVariable.Enum); - Extensions = new Dictionary(serverVariable.Extensions); + Description = serverVariable?.Description; + Default = serverVariable?.Default; + Enum = serverVariable?.Enum != null ? new List(serverVariable?.Enum) : serverVariable?.Enum; + Extensions = serverVariable?.Extensions != null ? new Dictionary(serverVariable?.Extensions) : serverVariable?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index 5ecfa0363..4e3785d4e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -53,12 +53,12 @@ public OpenApiTag() {} /// public OpenApiTag(OpenApiTag tag) { - Name = tag.Name; - Description = tag.Description; - ExternalDocs = new(tag.ExternalDocs); - Extensions = new Dictionary(tag.Extensions); - UnresolvedReference = tag.UnresolvedReference; - Reference = new(tag.Reference); + Name = tag?.Name; + Description = tag?.Description; + ExternalDocs = new(tag?.ExternalDocs); + Extensions = tag?.Extensions != null ? new Dictionary(tag?.Extensions) : tag?.Extensions; + UnresolvedReference = tag?.UnresolvedReference ?? false; + Reference = new(tag?.Reference); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index eb48132ad..19e231dea 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -56,12 +56,12 @@ public OpenApiXml() {} /// public OpenApiXml(OpenApiXml xml) { - Name = xml.Name; - Namespace = xml.Namespace; - Prefix = xml.Prefix; - Attribute = xml.Attribute; - Wrapped = xml.Wrapped; - Extensions = new Dictionary(xml.Extensions); + Name = xml?.Name; + Namespace = xml?.Namespace; + Prefix = xml?.Prefix; + Attribute = xml?.Attribute ?? false; + Wrapped = xml?.Wrapped ?? false; + Extensions = xml?.Extensions != null ? new Dictionary(xml?.Extensions) : xml?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs index 85c64dd30..1a1f12a18 100644 --- a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs +++ b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -26,8 +26,8 @@ public RuntimeExpressionAnyWrapper() {} /// public RuntimeExpressionAnyWrapper(RuntimeExpressionAnyWrapper runtimeExpressionAnyWrapper) { - Any = OpenApiAnyCloneHelper.CloneFromCopyConstructor(runtimeExpressionAnyWrapper.Any); - Expression = runtimeExpressionAnyWrapper.Expression; + Any = OpenApiAnyCloneHelper.CloneFromCopyConstructor(runtimeExpressionAnyWrapper?.Any); + Expression = runtimeExpressionAnyWrapper?.Expression; } /// From 0eb6becf41ccc0adaae4da41804048c22b3e7952 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 12 Aug 2022 15:50:58 +0300 Subject: [PATCH 179/855] Defaults to false for bool property --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 45d520b3a..8b073244c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -288,7 +288,7 @@ public OpenApiSchema(OpenApiSchema schema) ExternalDocs = new(schema?.ExternalDocs); Deprecated = schema?.Deprecated ?? false; Xml = new(schema?.Xml); - UnresolvedReference = schema?.UnresolvedReference; + UnresolvedReference = schema?.UnresolvedReference ?? false; Reference = new(schema?.Reference); } From 9c5aa0059adc9a5d14c1488ccb310c3a6e3d6408 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 12 Aug 2022 16:07:02 +0300 Subject: [PATCH 180/855] Resort to default is enum value is null --- src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 1bc427e9a..8b85e4575 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -84,10 +84,10 @@ public OpenApiSecurityScheme() {} /// public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) { - Type = (SecuritySchemeType)(securityScheme?.Type); + Type = securityScheme?.Type ?? default; Description = securityScheme?.Description; Name = securityScheme?.Name; - In = (ParameterLocation)(securityScheme?.In); + In = securityScheme?.In ?? default; Scheme = securityScheme?.Scheme; BearerFormat = securityScheme?.BearerFormat; Flows = new(securityScheme?.Flows); From 17dfe3c6fa32b634d846bf26b73f7d09fe800f21 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 12 Aug 2022 18:12:35 +0300 Subject: [PATCH 181/855] Address PR feedback --- .../Models/OpenApiCallback.cs | 8 +-- .../Models/OpenApiComponents.cs | 20 +++--- .../Models/OpenApiContact.cs | 8 +-- .../Models/OpenApiDiscriminator.cs | 4 +- .../Models/OpenApiDocument.cs | 18 ++--- .../Models/OpenApiEncoding.cs | 12 ++-- .../Models/OpenApiExample.cs | 12 ++-- .../Models/OpenApiExternalDocs.cs | 6 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 26 +++---- src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 14 ++-- .../Models/OpenApiLicense.cs | 6 +- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 18 ++--- .../Models/OpenApiMediaType.cs | 8 +-- .../Models/OpenApiOAuthFlow.cs | 10 +-- .../Models/OpenApiOAuthFlows.cs | 10 +-- .../Models/OpenApiOperation.cs | 22 +++--- .../Models/OpenApiParameter.cs | 30 ++++---- .../Models/OpenApiPathItem.cs | 16 ++--- .../Models/OpenApiRequestBody.cs | 12 ++-- .../Models/OpenApiResponse.cs | 14 ++-- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 70 +++++++++---------- .../Models/OpenApiSecurityScheme.cs | 22 +++--- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 8 +-- src/Microsoft.OpenApi/Models/OpenApiTag.cs | 12 ++-- src/Microsoft.OpenApi/Models/OpenApiXml.cs | 12 ++-- 25 files changed, 199 insertions(+), 199 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index beed0ad06..2dcae12d1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -45,10 +45,10 @@ public OpenApiCallback() { } /// public OpenApiCallback(OpenApiCallback callback) { - PathItems = new(callback?.PathItems); - UnresolvedReference = callback?.UnresolvedReference ?? false; - Reference = new(callback?.Reference); - Extensions = callback?.Extensions != null ? new Dictionary(callback?.Extensions) : callback?.Extensions; + PathItems = callback?.PathItems != null ? new(callback?.PathItems) : null; + UnresolvedReference = callback?.UnresolvedReference ?? UnresolvedReference; + Reference = callback?.Reference != null ? new(callback?.Reference) : null; + Extensions = callback?.Extensions != null ? new Dictionary(callback.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 7e4a481ac..1f41080bc 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -78,16 +78,16 @@ public OpenApiComponents() { } /// public OpenApiComponents(OpenApiComponents components) { - Schemas = components?.Schemas != null ? new Dictionary(components?.Schemas) : components?.Schemas; - Responses = components?.Responses != null ? new Dictionary(components?.Responses) : components?.Responses; - Parameters = components?.Parameters != null ? new Dictionary(components?.Parameters) : components?.Parameters; - Examples = components?.Examples != null ? new Dictionary(components?.Examples) : components?.Examples; - RequestBodies = components?.RequestBodies != null ? new Dictionary(components?.RequestBodies) : components?.RequestBodies; - Headers = components?.Headers != null ? new Dictionary(components?.Headers) : components?.Headers; - SecuritySchemes = components?.SecuritySchemes != null ? new Dictionary(components?.SecuritySchemes) : components?.SecuritySchemes; - Links = components?.Links != null ? new Dictionary(components?.Links) : components?.Links; - Callbacks = components?.Callbacks != null ? new Dictionary(components?.Callbacks) : components?.Callbacks; - Extensions = components?.Extensions != null ? new Dictionary(components?.Extensions) : components?.Extensions; + Schemas = components?.Schemas != null ? new Dictionary(components.Schemas) : null; + Responses = components?.Responses != null ? new Dictionary(components.Responses) : null; + Parameters = components?.Parameters != null ? new Dictionary(components.Parameters) : null; + Examples = components?.Examples != null ? new Dictionary(components.Examples) : null; + RequestBodies = components?.RequestBodies != null ? new Dictionary(components.RequestBodies) : null; + Headers = components?.Headers != null ? new Dictionary(components.Headers) : null; + SecuritySchemes = components?.SecuritySchemes != null ? new Dictionary(components.SecuritySchemes) : null; + Links = components?.Links != null ? new Dictionary(components.Links) : null; + Callbacks = components?.Callbacks != null ? new Dictionary(components.Callbacks) : null; + Extensions = components?.Extensions != null ? new Dictionary(components.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 28001e928..352697bf2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -45,10 +45,10 @@ public OpenApiContact() { } /// public OpenApiContact(OpenApiContact contact) { - Name = contact?.Name; - Url = contact?.Url; - Email = contact?.Email; - Extensions = contact?.Extensions != null ? new Dictionary(contact?.Extensions) : contact?.Extensions; + Name = contact?.Name ?? Name; + Url = contact?.Url != null ? new Uri(contact.Url.OriginalString) : null; + Email = contact?.Email ?? Email; + Extensions = contact?.Extensions != null ? new Dictionary(contact.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs index f39819a0a..9ae7f0e6a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs @@ -32,8 +32,8 @@ public OpenApiDiscriminator() { } /// public OpenApiDiscriminator(OpenApiDiscriminator discriminator) { - PropertyName = discriminator?.PropertyName; - Mapping = discriminator?.Mapping != null ? new Dictionary(discriminator?.Mapping) : discriminator?.Mapping; + PropertyName = discriminator?.PropertyName ?? PropertyName; + Mapping = discriminator?.Mapping != null ? new Dictionary(discriminator.Mapping) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 21c5f2e53..01edcebba 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -72,15 +72,15 @@ public OpenApiDocument() {} /// public OpenApiDocument(OpenApiDocument document) { - Workspace = new(document?.Workspace); - Info = new(document?.Info); - Servers = document?.Servers != null ? new List(document?.Servers) : document?.Servers; - Paths = new(document?.Paths); - Components = new(document?.Components); - SecurityRequirements = document?.SecurityRequirements != null ? new List(document?.SecurityRequirements) : document?.SecurityRequirements; - Tags = document?.Tags != null ? new List(document?.Tags) : document?.Tags; - ExternalDocs = new(document?.ExternalDocs); - Extensions = document?.Extensions != null ? new Dictionary(document?.Extensions) : document?.Extensions; + Workspace = document?.Workspace != null ? new(document?.Workspace) : null; + Info = document?.Info != null ? new(document?.Info) : null; + Servers = document?.Servers != null ? new List(document.Servers) : null; + Paths = document?.Paths != null ? new(document?.Paths) : null; + Components = document?.Components != null ? new(document?.Components) : null; + SecurityRequirements = document?.SecurityRequirements != null ? new List(document.SecurityRequirements) : null; + Tags = document?.Tags != null ? new List(document.Tags) : null; + ExternalDocs = document?.ExternalDocs != null ? new(document?.ExternalDocs) : null; + Extensions = document?.Extensions != null ? new Dictionary(document.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index bc154e8fb..ddb4162bc 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -63,12 +63,12 @@ public OpenApiEncoding() {} /// public OpenApiEncoding(OpenApiEncoding encoding) { - ContentType = encoding?.ContentType; - Headers = encoding?.Headers != null ? new Dictionary(encoding?.Headers) : encoding?.Headers; - Style = encoding?.Style; - Explode = encoding?.Explode ?? false; - AllowReserved = encoding?.AllowReserved ?? false; - Extensions = encoding?.Extensions != null ? new Dictionary(encoding?.Extensions) : encoding?.Extensions; + ContentType = encoding?.ContentType ?? ContentType; + Headers = encoding?.Headers != null ? new Dictionary(encoding.Headers) : null; + Style = encoding?.Style ?? Style; + Explode = encoding?.Explode ?? Explode; + AllowReserved = encoding?.AllowReserved ?? AllowReserved; + Extensions = encoding?.Extensions != null ? new Dictionary(encoding.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index b9bfc031a..4d091a361 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -64,13 +64,13 @@ public OpenApiExample() {} /// public OpenApiExample(OpenApiExample example) { - Summary = example?.Summary; - Description = example?.Description; + Summary = example?.Summary ?? Summary; + Description = example?.Description ?? Description; Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example?.Value); - ExternalValue = example?.ExternalValue; - Extensions = example?.Extensions != null ? new Dictionary(example?.Extensions) : example?.Extensions; - Reference = new(example?.Reference); - UnresolvedReference = example?.UnresolvedReference ?? false; + ExternalValue = example?.ExternalValue ?? ExternalValue; + Extensions = example?.Extensions != null ? new Dictionary(example.Extensions) : null; + Reference = example?.Reference != null ? new(example?.Reference) : null; + UnresolvedReference = example?.UnresolvedReference ?? UnresolvedReference; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 040b7d674..9ad3b9e55 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -39,9 +39,9 @@ public OpenApiExternalDocs() {} /// public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) { - Description = externalDocs?.Description; - Url = externalDocs?.Url != null ? new Uri(externalDocs?.Url?.OriginalString) : externalDocs?.Url; - Extensions = externalDocs?.Extensions != null ? new Dictionary(externalDocs?.Extensions) : externalDocs?.Extensions; + Description = externalDocs?.Description ?? Description; + Url = externalDocs?.Url != null ? new Uri(externalDocs.Url.OriginalString) : null; + Extensions = externalDocs?.Extensions != null ? new Dictionary(externalDocs.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index a7ca745d2..fb4411478 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -96,20 +96,20 @@ public OpenApiHeader() {} /// public OpenApiHeader(OpenApiHeader header) { - UnresolvedReference = header?.UnresolvedReference ?? false; - Reference = new(header?.Reference); - Description = header?.Description; - Required = header?.Required ?? false; - Deprecated = header?.Deprecated ?? false; - AllowEmptyValue = header?.AllowEmptyValue ?? false; - Style = header?.Style; - Explode = header?.Explode ?? false; - AllowReserved = header?.AllowReserved ?? false; - Schema = new(header?.Schema); + UnresolvedReference = header?.UnresolvedReference ?? UnresolvedReference; + Reference = header?.Reference != null ? new(header?.Reference) : null; + Description = header?.Description ?? Description; + Required = header?.Required ?? Required; + Deprecated = header?.Deprecated ?? Deprecated; + AllowEmptyValue = header?.AllowEmptyValue ?? AllowEmptyValue; + Style = header?.Style ?? Style; + Explode = header?.Explode ?? Explode; + AllowReserved = header?.AllowReserved ?? AllowReserved; + Schema = header?.Schema != null ? new(header?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header?.Example); - Examples = header?.Examples != null ? new Dictionary(header?.Examples) : header?.Examples; - Content = header?.Content != null ? new Dictionary(header?.Content) : header?.Content; - Extensions = header?.Extensions != null ? new Dictionary(header?.Extensions) : header?.Extensions; + Examples = header?.Examples != null ? new Dictionary(header.Examples) : null; + Content = header?.Content != null ? new Dictionary(header.Content) : null; + Extensions = header?.Extensions != null ? new Dictionary(header.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index 1dcae81e2..df0aa0a49 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -59,13 +59,13 @@ public OpenApiInfo() {} /// public OpenApiInfo(OpenApiInfo info) { - Title = info?.Title; - Description = info?.Description; - Version = info?.Version; - TermsOfService = info?.TermsOfService; - Contact = new(info?.Contact); - License = new(info?.License); - Extensions = info?.Extensions != null ? new Dictionary(info?.Extensions) : info?.Extensions; + Title = info?.Title ?? Title; + Description = info?.Description ?? Description; + Version = info?.Version ?? Version; + TermsOfService = info?.TermsOfService ?? TermsOfService; + Contact = info?.Contact != null ? new(info?.Contact) : null; + License = info?.License != null ? new(info?.License) : null; + Extensions = info?.Extensions != null ? new Dictionary(info.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 399441b46..1a8d1a4d8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -39,9 +39,9 @@ public OpenApiLicense() {} /// public OpenApiLicense(OpenApiLicense license) { - Name = license?.Name; - Url = license?.Url != null ? new Uri(license?.Url?.OriginalString) : license?.Url; - Extensions = license?.Extensions != null ? new Dictionary(license?.Extensions) : license?.Extensions; + Name = license?.Name ?? Name; + Url = license?.Url != null ? new Uri(license.Url.OriginalString) : null; + Extensions = license?.Extensions != null ? new Dictionary(license.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index 3a5a72c1d..b682744e9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -71,15 +71,15 @@ public OpenApiLink() {} /// public OpenApiLink(OpenApiLink link) { - OperationRef = link?.OperationRef; - OperationId = link?.OperationId; - Parameters = new(link?.Parameters); - RequestBody = new(link?.RequestBody); - Description = link?.Description; - Server = new(link?.Server); - Extensions = link?.Extensions != null ? new Dictionary(link?.Extensions) : link?.Extensions; - UnresolvedReference = link?.UnresolvedReference ?? false; - Reference = new(link?.Reference); + OperationRef = link?.OperationRef ?? OperationRef; + OperationId = link?.OperationId ?? OperationId; + Parameters = link?.Parameters != null ? new(link?.Parameters) : null; + RequestBody = link?.RequestBody != null ? new(link?.RequestBody) : null; + Description = link?.Description ?? Description; + Server = link?.Server != null ? new(link?.Server) : null; + Extensions = link?.Extensions != null ? new Dictionary(link.Extensions) : null; + UnresolvedReference = link?.UnresolvedReference ?? UnresolvedReference; + Reference = link?.Reference != null ? new(link?.Reference) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index b6245f202..63a58cd02 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -53,11 +53,11 @@ public OpenApiMediaType() {} /// public OpenApiMediaType(OpenApiMediaType mediaType) { - Schema = new(mediaType?.Schema); + Schema = mediaType?.Schema != null ? new(mediaType?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType?.Example); - Examples = mediaType?.Examples != null ? new Dictionary(mediaType?.Examples) : mediaType?.Examples; - Encoding = mediaType?.Encoding != null ? new Dictionary(mediaType?.Encoding) : mediaType?.Encoding; - Extensions = mediaType?.Extensions != null ? new Dictionary(mediaType?.Extensions) : mediaType?.Extensions; + Examples = mediaType?.Examples != null ? new Dictionary(mediaType.Examples) : null; + Encoding = mediaType?.Encoding != null ? new Dictionary(mediaType.Encoding) : null; + Extensions = mediaType?.Extensions != null ? new Dictionary(mediaType.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index f5a9b46c4..c6f91fbd8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -51,11 +51,11 @@ public OpenApiOAuthFlow() {} /// public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) { - AuthorizationUrl = oAuthFlow?.AuthorizationUrl != null ? new Uri(oAuthFlow?.AuthorizationUrl?.OriginalString) : oAuthFlow?.AuthorizationUrl; - TokenUrl = oAuthFlow?.TokenUrl != null ? new Uri(oAuthFlow?.TokenUrl?.OriginalString) : oAuthFlow?.TokenUrl; - RefreshUrl = oAuthFlow?.RefreshUrl != null ? new Uri(oAuthFlow?.RefreshUrl?.OriginalString) : oAuthFlow?.RefreshUrl; - Scopes = oAuthFlow?.Scopes != null ? new Dictionary(oAuthFlow?.Scopes) : oAuthFlow?.Scopes; - Extensions = oAuthFlow?.Extensions != null ? new Dictionary(oAuthFlow?.Extensions) : oAuthFlow?.Extensions; + AuthorizationUrl = oAuthFlow?.AuthorizationUrl != null ? new Uri(oAuthFlow.AuthorizationUrl.OriginalString) : null; + TokenUrl = oAuthFlow?.TokenUrl != null ? new Uri(oAuthFlow.TokenUrl.OriginalString) : null; + RefreshUrl = oAuthFlow?.RefreshUrl != null ? new Uri(oAuthFlow.RefreshUrl.OriginalString) : null; + Scopes = oAuthFlow?.Scopes != null ? new Dictionary(oAuthFlow.Scopes) : null; + Extensions = oAuthFlow?.Extensions != null ? new Dictionary(oAuthFlow.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index d286c7641..8443e6730 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -49,11 +49,11 @@ public OpenApiOAuthFlows() {} /// public OpenApiOAuthFlows(OpenApiOAuthFlows oAuthFlows) { - Implicit = new(oAuthFlows?.Implicit); - Password = new(oAuthFlows?.Password); - ClientCredentials = new(oAuthFlows?.ClientCredentials); - AuthorizationCode = new(oAuthFlows?.AuthorizationCode); - Extensions = oAuthFlows?.Extensions != null ? new Dictionary(oAuthFlows?.Extensions) : oAuthFlows?.Extensions; + Implicit = oAuthFlows?.Implicit != null ? new(oAuthFlows?.Implicit) : null; + Password = oAuthFlows?.Password != null ? new(oAuthFlows?.Password) : null; + ClientCredentials = oAuthFlows?.ClientCredentials != null ? new(oAuthFlows?.ClientCredentials) : null; + AuthorizationCode = oAuthFlows?.AuthorizationCode != null ? new(oAuthFlows?.AuthorizationCode) : null; + Extensions = oAuthFlows?.Extensions != null ? new Dictionary(oAuthFlows.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index e7f8b8910..ba0af7317 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -117,18 +117,18 @@ public OpenApiOperation() {} public OpenApiOperation(OpenApiOperation operation) { Tags = new List(operation?.Tags); - Summary = operation?.Summary; - Description = operation?.Description; - ExternalDocs = new(operation?.ExternalDocs); - OperationId = operation?.OperationId; - Parameters = operation?.Parameters != null ? new List(operation?.Parameters) : operation?.Parameters; + Summary = operation?.Summary ?? Summary; + Description = operation?.Description ?? Description; + ExternalDocs = operation?.ExternalDocs != null ? new(operation?.ExternalDocs) : null; + OperationId = operation?.OperationId ?? OperationId; + Parameters = operation?.Parameters != null ? new List(operation.Parameters) : null; RequestBody = new(operation?.RequestBody); - Responses = new(operation?.Responses); - Callbacks = operation?.Callbacks != null ? new Dictionary(operation?.Callbacks) : operation?.Callbacks; - Deprecated = operation?.Deprecated ?? false; - Security = operation?.Security != null ? new List(operation?.Security) : operation?.Security; - Servers = operation?.Servers != null ? new List(operation?.Servers) : operation?.Servers; - Extensions = operation?.Extensions != null ? new Dictionary(operation?.Extensions) : operation?.Extensions; + Responses = operation?.Responses != null ? new(operation?.Responses) : null; + Callbacks = operation?.Callbacks != null ? new Dictionary(operation.Callbacks) : null; + Deprecated = operation?.Deprecated ?? Deprecated; + Security = operation?.Security != null ? new List(operation.Security) : null; + Servers = operation?.Servers != null ? new List(operation.Servers) : null; + Extensions = operation?.Extensions != null ? new Dictionary(operation.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 7a429ef0a..c6f06b1f6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -146,22 +146,22 @@ public OpenApiParameter() {} /// public OpenApiParameter(OpenApiParameter parameter) { - UnresolvedReference = parameter?.UnresolvedReference ?? false; - Reference = new(parameter?.Reference); - Name = parameter?.Name; - In = parameter?.In; - Description = parameter?.Description; - Required = parameter?.Required ?? false; - Style = parameter?.Style; - Explode = parameter?.Explode ?? false; - AllowReserved = parameter?.AllowReserved ?? false; - Schema = new(parameter?.Schema); - Examples = parameter?.Examples != null ? new Dictionary(parameter?.Examples) : parameter?.Examples; + UnresolvedReference = parameter?.UnresolvedReference ?? UnresolvedReference; + Reference = parameter?.Reference != null ? new(parameter?.Reference) : null; + Name = parameter?.Name ?? Name; + In = parameter?.In ?? In; + Description = parameter?.Description ?? Description; + Required = parameter?.Required ?? Required; + Style = parameter?.Style ?? Style; + Explode = parameter?.Explode ?? Explode; + AllowReserved = parameter?.AllowReserved ?? AllowReserved; + Schema = parameter?.Schema != null ? new(parameter?.Schema) : null; + Examples = parameter?.Examples != null ? new Dictionary(parameter.Examples) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); - Content = parameter?.Content != null ? new Dictionary(parameter?.Content) : parameter?.Content; - Extensions = parameter?.Extensions != null ? new Dictionary(parameter?.Extensions) : parameter?.Extensions; - AllowEmptyValue = parameter?.AllowEmptyValue ?? false; - Deprecated = parameter?.Deprecated ?? false; + Content = parameter?.Content != null ? new Dictionary(parameter.Content) : null; + Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; + AllowEmptyValue = parameter?.AllowEmptyValue ?? AllowEmptyValue; + Deprecated = parameter?.Deprecated ?? Deprecated; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index 89313be87..ddd358dc2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -75,14 +75,14 @@ public OpenApiPathItem() {} /// public OpenApiPathItem(OpenApiPathItem pathItem) { - Summary = pathItem?.Summary; - Description = pathItem?.Description; - Operations = pathItem?.Operations != null ? new Dictionary(pathItem?.Operations) : pathItem?.Operations; - Servers = pathItem?.Servers != null ? new List(pathItem?.Servers) : pathItem?.Servers; - Parameters = pathItem?.Parameters != null ? new List(pathItem?.Parameters) : pathItem?.Parameters; - Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem?.Extensions) : pathItem?.Extensions; - UnresolvedReference = pathItem?.UnresolvedReference ?? false; - Reference = new(pathItem?.Reference); + Summary = pathItem?.Summary ?? Summary; + Description = pathItem?.Description ?? Description; + Operations = pathItem?.Operations != null ? new Dictionary(pathItem.Operations) : null; + Servers = pathItem?.Servers != null ? new List(pathItem.Servers) : null; + Parameters = pathItem?.Parameters != null ? new List(pathItem.Parameters) : null; + Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem.Extensions) : null; + UnresolvedReference = pathItem?.UnresolvedReference ?? UnresolvedReference; + Reference = pathItem?.Reference != null ? new(pathItem?.Reference) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 6e7bdaf77..9016fd7a3 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -55,12 +55,12 @@ public OpenApiRequestBody() { } /// public OpenApiRequestBody(OpenApiRequestBody requestBody) { - UnresolvedReference = requestBody?.UnresolvedReference ?? false; - Reference = new(requestBody?.Reference); - Description = requestBody?.Description; - Required = requestBody?.Required ?? false; - Content = requestBody?.Content != null ? new Dictionary(requestBody?.Content) : requestBody?.Content; - Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody?.Extensions) : requestBody?.Extensions; + UnresolvedReference = requestBody?.UnresolvedReference ?? UnresolvedReference; + Reference = requestBody?.Reference != null ? new(requestBody?.Reference) : null; + Description = requestBody?.Description ?? Description; + Required = requestBody?.Required ?? Required; + Content = requestBody?.Content != null ? new Dictionary(requestBody.Content) : null; + Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index 46b7b63b0..a173f6c1a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -61,13 +61,13 @@ public OpenApiResponse() {} /// public OpenApiResponse(OpenApiResponse response) { - Description = response?.Description; - Headers = response?.Headers != null ? new Dictionary(response?.Headers) : response?.Headers; - Content = response?.Content != null ? new Dictionary(response?.Content) : response?.Content; - Links = response?.Links != null ? new Dictionary(response?.Links) : response?.Links; - Extensions = response?.Extensions != null ? new Dictionary(response?.Extensions) : response?.Extensions; - UnresolvedReference = response?.UnresolvedReference ?? false; - Reference = new(response?.Reference); + Description = response?.Description ?? Description; + Headers = response?.Headers != null ? new Dictionary(response.Headers) : null; + Content = response?.Content != null ? new Dictionary(response.Content) : null; + Links = response?.Links != null ? new Dictionary(response.Links) : null; + Extensions = response?.Extensions != null ? new Dictionary(response.Extensions) : null; + UnresolvedReference = response?.UnresolvedReference ?? UnresolvedReference; + Reference = response?.Reference != null ? new(response?.Reference) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 8b073244c..3886a5555 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -252,44 +252,44 @@ public OpenApiSchema() {} /// public OpenApiSchema(OpenApiSchema schema) { - Title = schema?.Title; - Type = schema?.Type; - Format = schema?.Format; - Description = schema?.Description; - Maximum = schema?.Maximum; - ExclusiveMaximum = schema?.ExclusiveMaximum; - Minimum = schema?.Minimum; - ExclusiveMinimum = schema?.ExclusiveMinimum; - MaxLength = schema?.MaxLength; - MinLength = schema?.MinLength; - Pattern = schema?.Pattern; - MultipleOf = schema?.MultipleOf; + Title = schema?.Title ?? Title; + Type = schema?.Type ?? Type; + Format = schema?.Format ?? Format; + Description = schema?.Description ?? Description; + Maximum = schema?.Maximum ?? Maximum; + ExclusiveMaximum = schema?.ExclusiveMaximum ?? ExclusiveMaximum; + Minimum = schema?.Minimum ?? Minimum; + ExclusiveMinimum = schema?.ExclusiveMinimum ?? ExclusiveMinimum; + MaxLength = schema?.MaxLength ?? MaxLength; + MinLength = schema?.MinLength ?? MinLength; + Pattern = schema?.Pattern ?? Pattern; + MultipleOf = schema?.MultipleOf ?? MultipleOf; Default = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema?.Default); - ReadOnly = schema?.ReadOnly ?? false; - WriteOnly = schema?.WriteOnly ?? false; - AllOf = schema?.AllOf != null ? new List(schema?.AllOf) : schema?.AllOf; - OneOf = schema?.OneOf != null ? new List(schema?.OneOf) : schema?.OneOf; - AnyOf = schema?.AnyOf != null ? new List(schema?.AnyOf) : schema?.AnyOf; - Not = new(schema?.Not); - Required = schema?.Required != null ? new HashSet(schema?.Required) : schema?.Required; - Items = new(schema?.Items); - MaxItems = schema?.MaxItems; - MinItems = schema?.MinItems; - UniqueItems = schema?.UniqueItems; - Properties = schema?.Properties != null ? new Dictionary(schema?.Properties) : schema?.Properties; - MaxProperties = schema?.MaxProperties; - MinProperties = schema?.MinProperties; - AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? false; + ReadOnly = schema?.ReadOnly ?? ReadOnly; + WriteOnly = schema?.WriteOnly ?? WriteOnly; + AllOf = schema?.AllOf != null ? new List(schema.AllOf) : null; + OneOf = schema?.OneOf != null ? new List(schema.OneOf) : null; + AnyOf = schema?.AnyOf != null ? new List(schema.AnyOf) : null; + Not = schema?.Not != null ? new(schema?.Not) : null; + Required = schema?.Required != null ? new HashSet(schema.Required) : null; + Items = schema?.Items != null ? new(schema?.Items) : null; + MaxItems = schema?.MaxItems ?? MaxItems; + MinItems = schema?.MinItems ?? MinItems; + UniqueItems = schema?.UniqueItems ?? UniqueItems; + Properties = schema?.Properties != null ? new Dictionary(schema.Properties) : null; + MaxProperties = schema?.MaxProperties ?? MaxProperties; + MinProperties = schema?.MinProperties ?? MinProperties; + AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? AdditionalPropertiesAllowed; AdditionalProperties = new(schema?.AdditionalProperties); - Discriminator = new(schema?.Discriminator); + Discriminator = schema?.Discriminator != null ? new(schema?.Discriminator) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema?.Example); - Enum = schema?.Enum != null ? new List(schema?.Enum) : schema?.Enum; - Nullable = schema?.Nullable ?? false; - ExternalDocs = new(schema?.ExternalDocs); - Deprecated = schema?.Deprecated ?? false; - Xml = new(schema?.Xml); - UnresolvedReference = schema?.UnresolvedReference ?? false; - Reference = new(schema?.Reference); + Enum = schema?.Enum != null ? new List(schema.Enum) : null; + Nullable = schema?.Nullable ?? Nullable; + ExternalDocs = schema?.ExternalDocs != null ? new(schema?.ExternalDocs) : null; + Deprecated = schema?.Deprecated ?? Deprecated; + Xml = schema?.Xml != null ? new(schema?.Xml) : null; + UnresolvedReference = schema?.UnresolvedReference ?? UnresolvedReference; + Reference = schema?.Reference != null ? new(schema?.Reference) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 8b85e4575..913e70441 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -84,17 +84,17 @@ public OpenApiSecurityScheme() {} /// public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) { - Type = securityScheme?.Type ?? default; - Description = securityScheme?.Description; - Name = securityScheme?.Name; - In = securityScheme?.In ?? default; - Scheme = securityScheme?.Scheme; - BearerFormat = securityScheme?.BearerFormat; - Flows = new(securityScheme?.Flows); - OpenIdConnectUrl = new Uri(securityScheme?.OpenIdConnectUrl?.OriginalString); - Extensions = securityScheme?.Extensions != null ? new Dictionary(securityScheme?.Extensions) : securityScheme?.Extensions; - UnresolvedReference = securityScheme?.UnresolvedReference ?? false; - Reference = new(securityScheme?.Reference); + Type = securityScheme?.Type ?? Type; + Description = securityScheme?.Description ?? Description; + Name = securityScheme?.Name ?? Name; + In = securityScheme?.In ?? In; + Scheme = securityScheme?.Scheme ?? Scheme; + BearerFormat = securityScheme?.BearerFormat ?? BearerFormat; + Flows = securityScheme?.Flows != null ? new(securityScheme?.Flows) : null; + OpenIdConnectUrl = securityScheme?.OpenIdConnectUrl != null ? new Uri(securityScheme.OpenIdConnectUrl.OriginalString) : null; + Extensions = securityScheme?.Extensions != null ? new Dictionary(securityScheme.Extensions) : null; + UnresolvedReference = securityScheme?.UnresolvedReference ?? UnresolvedReference; + Reference = securityScheme?.Reference != null ? new(securityScheme?.Reference) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index c0ec7114a..b3b1d1287 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -46,10 +46,10 @@ public OpenApiServer() {} /// public OpenApiServer(OpenApiServer server) { - Description = server?.Description; - Url = server?.Url; - Variables = server?.Variables != null ? new Dictionary(server?.Variables) : server?.Variables; - Extensions = server?.Extensions != null ? new Dictionary(server?.Extensions) : server?.Extensions; + Description = server?.Description ?? Description; + Url = server?.Url ?? Url; + Variables = server?.Variables != null ? new Dictionary(server.Variables) : null; + Extensions = server?.Extensions != null ? new Dictionary(server.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index 4e3785d4e..ba4129142 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -53,12 +53,12 @@ public OpenApiTag() {} /// public OpenApiTag(OpenApiTag tag) { - Name = tag?.Name; - Description = tag?.Description; - ExternalDocs = new(tag?.ExternalDocs); - Extensions = tag?.Extensions != null ? new Dictionary(tag?.Extensions) : tag?.Extensions; - UnresolvedReference = tag?.UnresolvedReference ?? false; - Reference = new(tag?.Reference); + Name = tag?.Name ?? Name; + Description = tag?.Description ?? Description; + ExternalDocs = tag?.ExternalDocs != null ? new(tag?.ExternalDocs) : null; + Extensions = tag?.Extensions != null ? new Dictionary(tag.Extensions) : null; + UnresolvedReference = tag?.UnresolvedReference ?? UnresolvedReference; + Reference = tag?.Reference != null ? new(tag?.Reference) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index 19e231dea..c6719d85e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -56,12 +56,12 @@ public OpenApiXml() {} /// public OpenApiXml(OpenApiXml xml) { - Name = xml?.Name; - Namespace = xml?.Namespace; - Prefix = xml?.Prefix; - Attribute = xml?.Attribute ?? false; - Wrapped = xml?.Wrapped ?? false; - Extensions = xml?.Extensions != null ? new Dictionary(xml?.Extensions) : xml?.Extensions; + Name = xml?.Name ?? Name; + Namespace = xml?.Namespace ?? Namespace; + Prefix = xml?.Prefix ?? Prefix; + Attribute = xml?.Attribute ?? Attribute; + Wrapped = xml?.Wrapped ?? Wrapped; + Extensions = xml?.Extensions != null ? new Dictionary(xml.Extensions) : null; } /// From cefe10d380ef5b1afafa1b44a82d6950fb996cca Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Aug 2022 21:11:30 +0000 Subject: [PATCH 182/855] Bump Microsoft.OData.Edm from 7.12.1 to 7.12.2 Bumps Microsoft.OData.Edm from 7.12.1 to 7.12.2. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index c35c40209..eda11732d 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From afdc0a430011c2ce3f9ae157aadc34b60610eaa6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Aug 2022 21:11:35 +0000 Subject: [PATCH 183/855] Bump Verify.Xunit from 17.8.1 to 17.9.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.8.1 to 17.9.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.8.1...17.9.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 1d8d8c45b..022b0e5dc 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From c2a23a0561b873272230eaf4faaa0d1f050920fa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Aug 2022 22:15:59 +0000 Subject: [PATCH 184/855] Bump SharpYaml from 1.9.2 to 2.1.0 Bumps [SharpYaml](https://github.com/xoofx/SharpYaml) from 1.9.2 to 2.1.0. - [Release notes](https://github.com/xoofx/SharpYaml/releases) - [Changelog](https://github.com/xoofx/SharpYaml/blob/master/changelog.md) - [Commits](https://github.com/xoofx/SharpYaml/compare/1.9.2...2.1.0) --- updated-dependencies: - dependency-name: SharpYaml dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 1ff5b99e9..94a5b7335 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -34,7 +34,7 @@ - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 83e5482a7..4faadc3f6 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -255,7 +255,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 022b0e5dc..6cac42c5d 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -19,7 +19,7 @@ - + From ffc7c1b823c846c15fb04d417d870968200c777e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Sun, 14 Aug 2022 01:21:01 +0300 Subject: [PATCH 185/855] Remove unnecessary info --- .github/ISSUE_TEMPLATE/bug_report.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 2c10124b0..c5b4cab90 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -18,13 +18,7 @@ A clear and concise description of what you expected to happen. **Screenshots/Code Snippets** If applicable, add screenshots of the stack trace or a code snippet to help explain your problem. - -**Your environment:** - - OS: [e.g. iOS] - - Browser [e.g. chrome, safari] - - Version [e.g. 22] - - Desktop or mobile - - If applicable, Link to your project +If applicable, add a link to your project **Additional context** Add any other context about the problem here. From aa503ff00e8a75f12ecc8628162744887424245a Mon Sep 17 00:00:00 2001 From: Millicent Achieng Date: Sun, 14 Aug 2022 02:20:59 +0300 Subject: [PATCH 186/855] Fix anyOf and oneOf serialization by checking for null first before writing either as allOf --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index d43756887..e50c49d1c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -700,12 +700,12 @@ internal void WriteAsSchemaProperties( if (AllOf == null || AllOf.Count == 0) { // anyOf (Not Supported in V2) - Write the first schema only as an allOf. - writer.WriteOptionalCollection(OpenApiConstants.AllOf, AnyOf.Take(1), (w, s) => s.SerializeAsV2(w)); + writer.WriteOptionalCollection(OpenApiConstants.AllOf, AnyOf?.Take(1), (w, s) => s.SerializeAsV2(w)); if (AnyOf == null || AnyOf.Count == 0) { // oneOf (Not Supported in V2) - Write the first schema only as an allOf. - writer.WriteOptionalCollection(OpenApiConstants.AllOf, OneOf.Take(1), (w, s) => s.SerializeAsV2(w)); + writer.WriteOptionalCollection(OpenApiConstants.AllOf, OneOf?.Take(1), (w, s) => s.SerializeAsV2(w)); } } From 19d9edc216236dba862158f9ffb107bd872146ea Mon Sep 17 00:00:00 2001 From: Millicent Achieng Date: Sun, 14 Aug 2022 03:51:07 +0300 Subject: [PATCH 187/855] Remove unused method --- .../V2/OpenApiOperationDeserializer.cs | 2 +- .../V2/OpenApiV2VersionService.cs | 24 ------------------- 2 files changed, 1 insertion(+), 25 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index a3bda05e1..1cf5b7ae8 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -60,7 +60,7 @@ internal static partial class OpenApiV2Deserializer "consumes", (o, n) => { var consumes = n.CreateSimpleList(s => s.GetScalarValue()); if (consumes.Count > 0) { - n.Context.SetTempStorage(TempStorageKeys.OperationConsumes,consumes); + n.Context.SetTempStorage(TempStorageKeys.OperationConsumes,consumes); } } }, diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index 718dcec04..33c9d7c6f 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -107,30 +107,6 @@ private static ReferenceType ParseReferenceType(string referenceTypeName) } } - private static string GetReferenceTypeV2Name(ReferenceType referenceType) - { - switch (referenceType) - { - case ReferenceType.Schema: - return "definitions"; - - case ReferenceType.Parameter: - return "parameters"; - - case ReferenceType.Response: - return "responses"; - - case ReferenceType.Tag: - return "tags"; - - case ReferenceType.SecurityScheme: - return "securityDefinitions"; - - default: - throw new ArgumentException(); - } - } - private static ReferenceType GetReferenceTypeV2FromName(string referenceType) { switch (referenceType) From 387e7f3d0acea98ddab11f4cf3bd53e9b68b9234 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 15 Aug 2022 12:42:27 +0300 Subject: [PATCH 188/855] Bumps up lib versions --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 1ff5b99e9..c92eaf766 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.4.0-preview1 + 1.4.0-preview2 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index a11622ec1..a768312e6 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.0-preview1 + 1.4.0-preview2 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From e0b30619c15a02d6d009a9a095df891dcc3e961e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 15 Aug 2022 20:03:04 +0300 Subject: [PATCH 189/855] Publish release notes and .exe before pushing to Nuget --- .azure-pipelines/ci-build.yml | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 5e8ddbd3b..44606bf01 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -266,14 +266,6 @@ stages: echo "$artifactName" echo "$artifactVersion" displayName: 'Fetch Artifact Name' - - - task: NuGetCommand@2 - displayName: 'NuGet push' - inputs: - command: push - packagesToPush: '$(Pipeline.Workspace)/Nugets/Microsoft.OpenApi.Hidi.*.nupkg' - nuGetFeedType: external - publishFeedCredentials: 'OpenAPI Nuget Connection' - task: GitHubRelease@1 displayName: 'GitHub release (edit)' inputs: @@ -285,6 +277,13 @@ stages: releaseNotesSource: inline assets: '$(Pipeline.Workspace)\**\*.exe' changeLogType: issueBased + - task: NuGetCommand@2 + displayName: 'NuGet push' + inputs: + command: push + packagesToPush: '$(Pipeline.Workspace)/Nugets/Microsoft.OpenApi.Hidi.*.nupkg' + nuGetFeedType: external + publishFeedCredentials: 'OpenAPI Nuget Connection' - deployment: deploy_lib dependsOn: [] From 5938d425c55ad4580e16fdba23ac12fbdca344e7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 15 Aug 2022 20:14:10 +0300 Subject: [PATCH 190/855] Add a condition that triggers this task to run whether or not the preceding step has failed --- .azure-pipelines/ci-build.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 44606bf01..3e1b04fca 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -266,8 +266,16 @@ stages: echo "$artifactName" echo "$artifactVersion" displayName: 'Fetch Artifact Name' + - task: NuGetCommand@2 + displayName: 'NuGet push' + inputs: + command: push + packagesToPush: '$(Pipeline.Workspace)/Nugets/Microsoft.OpenApi.Hidi.*.nupkg' + nuGetFeedType: external + publishFeedCredentials: 'OpenAPI Nuget Connection' - task: GitHubRelease@1 displayName: 'GitHub release (edit)' + condition: succeededOrFailed() inputs: gitHubConnection: 'Github-MaggieKimani1' action: edit @@ -277,13 +285,6 @@ stages: releaseNotesSource: inline assets: '$(Pipeline.Workspace)\**\*.exe' changeLogType: issueBased - - task: NuGetCommand@2 - displayName: 'NuGet push' - inputs: - command: push - packagesToPush: '$(Pipeline.Workspace)/Nugets/Microsoft.OpenApi.Hidi.*.nupkg' - nuGetFeedType: external - publishFeedCredentials: 'OpenAPI Nuget Connection' - deployment: deploy_lib dependsOn: [] From 3b260ad3c8e3a03dc258b3495bfa747dc380d67a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 15 Aug 2022 21:10:39 +0000 Subject: [PATCH 191/855] Bump Verify.Xunit from 17.9.0 to 17.10.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.9.0 to 17.10.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.9.0...17.10.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 6cac42c5d..4ef308a15 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 529400d0216d7147142dfbbcc6d5dc947e4d5bb3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 16 Aug 2022 21:07:14 +0000 Subject: [PATCH 192/855] Bump Verify.Xunit from 17.10.0 to 17.10.2 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.10.0 to 17.10.2. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.10.0...17.10.2) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 4ef308a15..a6ba76259 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 0636e4a7e60f1bd8244333b756fb0a85a428e847 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 17 Aug 2022 13:18:26 +0300 Subject: [PATCH 193/855] Add a hashCode field to the diagnostics object to keep track of the hash value --- src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs | 5 +++++ src/Microsoft.OpenApi.Readers/ParsingContext.cs | 1 + 2 files changed, 6 insertions(+) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs index c3178ccfb..937a13891 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs @@ -26,5 +26,10 @@ public class OpenApiDiagnostic : IDiagnostic /// Open API specification version of the document parsed. /// public OpenApiSpecVersion SpecificationVersion { get; set; } + + /// + /// The unique hash code of the generated OpenAPI document + /// + public int HashCode { get; set; } } } diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index 6c4dece2f..537a981b8 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -75,6 +75,7 @@ internal OpenApiDocument Parse(YamlDocument yamlDocument) throw new OpenApiUnsupportedSpecVersionException(inputVersion); } + Diagnostic.HashCode = doc.GetHashCode(); return doc; } From 500f0c7f45a81a13d51cafc9a74208d0280585a0 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 17 Aug 2022 13:19:21 +0300 Subject: [PATCH 194/855] Override the base GetHashCode() to compute the hash value for an OpenApi document and its property values --- .../Models/OpenApiDocument.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 44cbc71ab..9058dc7ba 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -375,6 +375,27 @@ public IOpenApiReferenceable ResolveReference(OpenApiReference reference) return ResolveReference(reference, false); } + /// + /// Computes the hash code for an OpenApiDocument and its property values. + /// + /// The hash code. + public override int GetHashCode() + { + // select two random prime numbers e.g 1 and 3 and use them to compute hash codes + int hash = 1; + hash = hash * 3 + (Workspace == null ? 0 : Workspace.GetHashCode()); + hash = hash * 3 + (Info == null ? 0 : Info.GetHashCode()); + hash = hash * 3 + (Servers == null ? 0 : Servers.GetHashCode()); + hash = hash * 3 + (Paths == null ? 0 : Paths.GetHashCode()); + hash = hash * 3 + (Components == null ? 0 : Components.GetHashCode()); + hash = hash * 3 + (SecurityRequirements == null ? 0 : SecurityRequirements.GetHashCode()); + hash = hash * 3 + (Tags == null ? 0 : Tags.GetHashCode()); + hash = hash * 3 + (ExternalDocs == null ? 0 : ExternalDocs.GetHashCode()); + hash = hash * 3 + (Extensions == null ? 0 : Extensions.GetHashCode()); + + return hash; + } + /// /// Load the referenced object from a object /// From 7a58221b10c43bb7f42a01f679b12c46c5866cc9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 17 Aug 2022 13:20:44 +0300 Subject: [PATCH 195/855] Simplify using statement, add tests, test file and cleanup --- .../OpenApiYamlDocumentReader.cs | 1 - .../Microsoft.OpenApi.Readers.Tests.csproj | 5 +- .../V3Tests/OpenApiDocumentTests.cs | 59 ++++++++++++++----- .../minimalDocumentWithWhitespace.yaml | 9 +++ 4 files changed, 57 insertions(+), 17 deletions(-) create mode 100644 test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/minimalDocumentWithWhitespace.yaml diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index aae09ec86..3aedafbf1 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -79,7 +79,6 @@ public OpenApiDocument Read(YamlDocument input, out OpenApiDiagnostic diagnostic { diagnostic.Warnings.Add(item); } - } return document; diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index e89e47745..98f228850 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -1,4 +1,4 @@ - + net6.0 false @@ -137,6 +137,9 @@ Never + + Never + Never diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index f1d8b805f..b77fe8537 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -243,26 +243,55 @@ public void ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() [Fact] public void ParseMinimalDocumentShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument + { + Info = new OpenApiInfo { - Info = new OpenApiInfo - { - Title = "Simple Document", - Version = "0.9.1" - }, - Paths = new OpenApiPaths() - }); + Title = "Simple Document", + Version = "0.9.1" + }, + Paths = new OpenApiPaths() + }); - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - } + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } + [Fact] + public void TestHashCodesForSimilarOpenApiDocuments() + { + // Arrange + using var stream1 = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml")); + using var stream2 = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml")); + using var stream3 = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocumentWithWhitespace.yaml")); + + // Act + /* + Test whether reading in the same document twice yields the same hash code, + And reading in similar documents but one has a whitespace yields the same hash code + */ + var openApiDoc1 = new OpenApiStreamReader().Read(stream1, out var diagnostic1); + var openApiDoc2 = new OpenApiStreamReader().Read(stream2, out var diagnostic2); + var openApiDoc3 = new OpenApiStreamReader().Read(stream3, out var diagnostic3); + + // Assert + /* The assumption is, if doc1.Equals(doc2), then doc1.GetHashCode().Equals(doc2.GetHashCode())*/ + if (openApiDoc1.Equals(openApiDoc2) && openApiDoc2.Equals(openApiDoc3)) + { + Assert.Equal(diagnostic1.HashCode, diagnostic2.HashCode); + Assert.Equal(diagnostic2.HashCode, diagnostic3.HashCode); + } + + /*Adding a server object to the original doc to check whether the hash code changes*/ + openApiDoc1.Servers = new List(); + var hash = openApiDoc1.GetHashCode(); + Assert.NotEqual(diagnostic1.HashCode, hash); + } + [Fact] public void ParseStandardPetStoreDocumentShouldSucceed() { diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/minimalDocumentWithWhitespace.yaml b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/minimalDocumentWithWhitespace.yaml new file mode 100644 index 000000000..a68eb2fee --- /dev/null +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/minimalDocumentWithWhitespace.yaml @@ -0,0 +1,9 @@ +openapi : 3.0.0 +info: + title: Simple Document + version: 0.9.1 + +paths: {} + + + From f9a32fa9233a982d690520d6cf2a4d5319fded9e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 17 Aug 2022 14:24:12 +0300 Subject: [PATCH 196/855] Refactor failing tests --- .../V2Tests/OpenApiDocumentTests.cs | 4 +- .../V2Tests/OpenApiServerTests.cs | 12 +- .../V3Tests/OpenApiCallbackTests.cs | 155 +++++++++--------- .../V3Tests/OpenApiDocumentTests.cs | 101 ++++++------ .../V3Tests/OpenApiSchemaTests.cs | 15 +- 5 files changed, 141 insertions(+), 146 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index 39bc0db80..b3f3033ac 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -150,9 +150,9 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) }, Paths = new OpenApiPaths() }); + var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi2_0 }; - context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi2_0 }); + Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs index c87b491ab..3e2cde88d 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs @@ -280,14 +280,12 @@ public void InvalidHostShouldYieldError() var doc = reader.Read(input, out var diagnostic); doc.Servers.Count.Should().Be(0); - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic + + Assert.Equal(OpenApiSpecVersion.OpenApi2_0, diagnostic.SpecificationVersion); + diagnostic.Errors.Should().BeEquivalentTo( + new List { - Errors = - { - new OpenApiError("#/", "Invalid host") - }, - SpecificationVersion = OpenApiSpecVersion.OpenApi2_0 + new OpenApiError("#/", "Invalid host") }); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs index 320f01fae..a89c087ef 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs @@ -21,29 +21,28 @@ public class OpenApiCallbackTests [Fact] public void ParseBasicCallbackShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicCallback.yaml"))) - { - // Arrange - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicCallback.yaml")); + // Arrange + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var callback = OpenApiV3Deserializer.LoadCallback(node); + // Act + var callback = OpenApiV3Deserializer.LoadCallback(node); - // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - callback.Should().BeEquivalentTo( - new OpenApiCallback + callback.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { [RuntimeExpression.Build("$request.body#/url")] = new OpenApiPathItem { @@ -69,33 +68,31 @@ public void ParseBasicCallbackShouldSucceed() } } } - } - }); - } + } + }); } [Fact] public void ParseCallbackWithReferenceShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "callbackWithReference.yaml"))) - { - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "callbackWithReference.yaml")); + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - // Assert - var path = openApiDoc.Paths.First().Value; - var subscribeOperation = path.Operations[OperationType.Post]; + // Assert + var path = openApiDoc.Paths.First().Value; + var subscribeOperation = path.Operations[OperationType.Post]; - var callback = subscribeOperation.Callbacks["simpleHook"]; + var callback = subscribeOperation.Callbacks["simpleHook"]; + var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); - callback.Should().BeEquivalentTo( - new OpenApiCallback + callback.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation() @@ -122,39 +119,38 @@ public void ParseCallbackWithReferenceShouldSucceed() } } } - }, - Reference = new OpenApiReference - { - Type = ReferenceType.Callback, - Id = "simpleHook", - HostDocument = openApiDoc - } - }); - } + }, + Reference = new OpenApiReference + { + Type = ReferenceType.Callback, + Id = "simpleHook", + HostDocument = openApiDoc + } + }); } [Fact] public void ParseMultipleCallbacksWithReferenceShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleCallbacksWithReference.yaml"))) - { - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleCallbacksWithReference.yaml")); + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + + // Assert + var path = openApiDoc.Paths.First().Value; + var subscribeOperation = path.Operations[OperationType.Post]; - // Assert - var path = openApiDoc.Paths.First().Value; - var subscribeOperation = path.Operations[OperationType.Post]; + var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); - var callback1 = subscribeOperation.Callbacks["simpleHook"]; + var callback1 = subscribeOperation.Callbacks["simpleHook"]; - callback1.Should().BeEquivalentTo( - new OpenApiCallback + callback1.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation() @@ -181,21 +177,21 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } } } - }, - Reference = new OpenApiReference - { - Type = ReferenceType.Callback, - Id = "simpleHook", - HostDocument = openApiDoc - } - }); + }, + Reference = new OpenApiReference + { + Type = ReferenceType.Callback, + Id = "simpleHook", + HostDocument = openApiDoc + } + }); - var callback2 = subscribeOperation.Callbacks["callback2"]; - callback2.Should().BeEquivalentTo( - new OpenApiCallback + var callback2 = subscribeOperation.Callbacks["callback2"]; + callback2.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { [RuntimeExpression.Build("/simplePath")]= new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation() @@ -223,15 +219,15 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } }, } - } - }); + } + }); - var callback3 = subscribeOperation.Callbacks["callback3"]; - callback3.Should().BeEquivalentTo( - new OpenApiCallback + var callback3 = subscribeOperation.Callbacks["callback3"]; + callback3.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { [RuntimeExpression.Build(@"http://example.com?transactionId={$request.body#/id}&email={$request.body#/email}")] = new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation() @@ -266,9 +262,8 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } } } - } - }); - } + } + }); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index b77fe8537..9ea3cfa4f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -99,8 +99,9 @@ public void ParseDocumentFromInlineStringShouldSucceed() Paths = new OpenApiPaths() }); - context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + + Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); } [Theory] @@ -170,31 +171,30 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) }, Paths = new OpenApiPaths() }); + var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); } [Fact] public void ParseBasicDocumentWithMultipleServersShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDocumentWithMultipleServers.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDocumentWithMultipleServers.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument + { + Info = new OpenApiInfo + { + Title = "The API", + Version = "0.9.1", + }, + Servers = { - Info = new OpenApiInfo - { - Title = "The API", - Version = "0.9.1", - }, - Servers = - { new OpenApiServer { Url = new Uri("http://www.example.org/api").ToString(), @@ -205,39 +205,34 @@ public void ParseBasicDocumentWithMultipleServersShouldSucceed() Url = new Uri("https://www.example.org/api").ToString(), Description = "The https endpoint" } - }, - Paths = new OpenApiPaths() - }); - } + }, + Paths = new OpenApiPaths() + }); } [Fact] public void ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "brokenMinimalDocument.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "brokenMinimalDocument.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument + { + Info = new OpenApiInfo { - Info = new OpenApiInfo - { - Version = "0.9" - }, - Paths = new OpenApiPaths() - }); + Version = "0.9" + }, + Paths = new OpenApiPaths() + }); - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic - { - Errors = - { - new OpenApiValidatorError(nameof(OpenApiInfoRules.InfoRequiredFields),"#/info/title", "The field 'title' in 'info' object is REQUIRED.") - }, - SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 - }); - } + diagnostic.Errors.Should().BeEquivalentTo( + new List + { + new OpenApiValidatorError(nameof(OpenApiInfoRules.InfoRequiredFields),"#/info/title", "The field 'title' in 'info' object is REQUIRED.") + }); + + Assert.Equal(OpenApiSpecVersion.OpenApi3_0, diagnostic.SpecificationVersion); } [Fact] @@ -257,8 +252,9 @@ public void ParseMinimalDocumentShouldSucceed() Paths = new OpenApiPaths() }); - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + + Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); } [Fact] @@ -718,8 +714,9 @@ public void ParseStandardPetStoreDocumentShouldSucceed() actual.Should().BeEquivalentTo(expected); } - context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + + Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); } [Fact] @@ -1251,8 +1248,9 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() actual.Should().BeEquivalentTo(expected, options => options.Excluding(m => m.Name == "HostDocument")); } - context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + + Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); } [Fact] @@ -1267,8 +1265,9 @@ public void ParsePetStoreExpandedShouldSucceed() // TODO: Create the object in memory and compare with the one read from YAML file. } - context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + + Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index 9bdafeba6..63d7894c5 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -332,8 +332,9 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() // Assert var components = openApiDoc.Components; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + + Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); components.Should().BeEquivalentTo( new OpenApiComponents @@ -438,8 +439,9 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() // Assert var components = openApiDoc.Components; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + + Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); components.Should().BeEquivalentTo( new OpenApiComponents @@ -619,8 +621,9 @@ public void ParseSelfReferencingSchemaShouldNotStackOverflow() // Assert var components = openApiDoc.Components; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + + Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); var schemaExtension = new OpenApiSchema() { From c7e3ed81e1bce61a19b2ca7fa236f162adeaf5b9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 22 Aug 2022 14:01:30 +0300 Subject: [PATCH 197/855] Compute hash value using hashing algorithm during serialization --- src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs | 2 +- .../OpenApiStreamReader.cs | 13 +++++++++++++ src/Microsoft.OpenApi.Readers/ParsingContext.cs | 1 - 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs index 937a13891..d634fe804 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs @@ -30,6 +30,6 @@ public class OpenApiDiagnostic : IDiagnostic /// /// The unique hash code of the generated OpenAPI document /// - public int HashCode { get; set; } + public string HashCode { get; set; } } } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index 13bdbdef8..d4dc709cf 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -3,6 +3,8 @@ using System; using System.IO; +using System.Security.Cryptography; +using System.Text; using System.Threading.Tasks; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; @@ -42,6 +44,17 @@ public OpenApiDocument Read(Stream input, out OpenApiDiagnostic diagnostic) { var reader = new StreamReader(input); var result = new OpenApiTextReaderReader(_settings).Read(reader, out diagnostic); + + HashAlgorithm sha = SHA512.Create(); + byte[] data = sha.ComputeHash(input); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < data.Length; i++) + { + sb.Append(data[i].ToString("X2")); + } + + diagnostic.HashCode = sb.ToString(); + if (!_settings.LeaveStreamOpen) { reader.Dispose(); diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index 537a981b8..6c4dece2f 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -75,7 +75,6 @@ internal OpenApiDocument Parse(YamlDocument yamlDocument) throw new OpenApiUnsupportedSpecVersionException(inputVersion); } - Diagnostic.HashCode = doc.GetHashCode(); return doc; } From 8d20075393b9c46e686580cead3b685c6d7027f2 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 22 Aug 2022 14:21:51 +0300 Subject: [PATCH 198/855] Clean up test --- .../Models/OpenApiDocument.cs | 60 +++++++++++++------ .../V3Tests/OpenApiDocumentTests.cs | 15 +---- 2 files changed, 43 insertions(+), 32 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 6ad301cc0..6b9d3af59 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -3,7 +3,11 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Runtime.Serialization.Formatters.Binary; +using System.Security.Cryptography; +using System.Text; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Services; @@ -62,6 +66,8 @@ public class OpenApiDocument : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + private static readonly object locker = new(); + /// /// Parameter-less constructor /// @@ -375,26 +381,42 @@ public IOpenApiReferenceable ResolveReference(OpenApiReference reference) return ResolveReference(reference, false); } - /// - /// Computes the hash code for an OpenApiDocument and its property values. - /// - /// The hash code. - public override int GetHashCode() + ///// + ///// Computes the hash code for an OpenApiDocument and its property values. + ///// + ///// The hash code. + //public override int GetHashCode() + //{ + // // select two random prime numbers e.g 1 and 3 and use them to compute hash codes + // int hash = 1; + // hash = hash * 3 + (Workspace == null ? 0 : Workspace.GetHashCode()); + // hash = hash * 3 + (Info == null ? 0 : Info.GetHashCode()); + // hash = hash * 3 + (Servers == null ? 0 : Servers.GetHashCode()); + // hash = hash * 3 + (Paths == null ? 0 : Paths.GetHashCode()); + // hash = hash * 3 + (Components == null ? 0 : Components.GetHashCode()); + // hash = hash * 3 + (SecurityRequirements == null ? 0 : SecurityRequirements.GetHashCode()); + // hash = hash * 3 + (Tags == null ? 0 : Tags.GetHashCode()); + // hash = hash * 3 + (ExternalDocs == null ? 0 : ExternalDocs.GetHashCode()); + // hash = hash * 3 + (Extensions == null ? 0 : Extensions.GetHashCode()); + + // return hash; + //} + + public static string GenerateHashValue(Stream input) { - // select two random prime numbers e.g 1 and 3 and use them to compute hash codes - int hash = 1; - hash = hash * 3 + (Workspace == null ? 0 : Workspace.GetHashCode()); - hash = hash * 3 + (Info == null ? 0 : Info.GetHashCode()); - hash = hash * 3 + (Servers == null ? 0 : Servers.GetHashCode()); - hash = hash * 3 + (Paths == null ? 0 : Paths.GetHashCode()); - hash = hash * 3 + (Components == null ? 0 : Components.GetHashCode()); - hash = hash * 3 + (SecurityRequirements == null ? 0 : SecurityRequirements.GetHashCode()); - hash = hash * 3 + (Tags == null ? 0 : Tags.GetHashCode()); - hash = hash * 3 + (ExternalDocs == null ? 0 : ExternalDocs.GetHashCode()); - hash = hash * 3 + (Extensions == null ? 0 : Extensions.GetHashCode()); - - return hash; - } + HashAlgorithm sha = SHA512.Create(); + byte[] result = sha.ComputeHash(input); + + // Build the final string by converting each byte + // into hex and appending it to a StringBuilder + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < result.Length; i++) + { + sb.Append(result[i].ToString("X2")); + } + + return sb.ToString(); + } /// /// Load the referenced object from a object diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 9ea3cfa4f..242dc6b74 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -9,13 +9,11 @@ using System.Threading; using FluentAssertions; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Validations; using Microsoft.OpenApi.Validations.Rules; using Microsoft.OpenApi.Writers; -using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; @@ -275,17 +273,8 @@ And reading in similar documents but one has a whitespace yields the same hash c var openApiDoc3 = new OpenApiStreamReader().Read(stream3, out var diagnostic3); // Assert - /* The assumption is, if doc1.Equals(doc2), then doc1.GetHashCode().Equals(doc2.GetHashCode())*/ - if (openApiDoc1.Equals(openApiDoc2) && openApiDoc2.Equals(openApiDoc3)) - { - Assert.Equal(diagnostic1.HashCode, diagnostic2.HashCode); - Assert.Equal(diagnostic2.HashCode, diagnostic3.HashCode); - } - - /*Adding a server object to the original doc to check whether the hash code changes*/ - openApiDoc1.Servers = new List(); - var hash = openApiDoc1.GetHashCode(); - Assert.NotEqual(diagnostic1.HashCode, hash); + Assert.Equal(diagnostic1.HashCode, diagnostic2.HashCode); + Assert.Equal(diagnostic2.HashCode, diagnostic3.HashCode); } [Fact] From a676e37ede211ea94fe521cd56373d28e2386c68 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 22 Aug 2022 14:22:33 +0300 Subject: [PATCH 199/855] Code cleanup --- .../OpenApiStreamReader.cs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index d4dc709cf..0554108b2 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -45,15 +45,17 @@ public OpenApiDocument Read(Stream input, out OpenApiDiagnostic diagnostic) var reader = new StreamReader(input); var result = new OpenApiTextReaderReader(_settings).Read(reader, out diagnostic); - HashAlgorithm sha = SHA512.Create(); - byte[] data = sha.ComputeHash(input); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < data.Length; i++) - { - sb.Append(data[i].ToString("X2")); - } + //HashAlgorithm sha = SHA512.Create(); + //byte[] data = sha.ComputeHash(input); + //StringBuilder sb = new StringBuilder(); + //for (int i = 0; i < data.Length; i++) + //{ + // sb.Append(data[i].ToString("X2")); + //} + - diagnostic.HashCode = sb.ToString(); + //diagnostic.HashCode = sb.ToString(); + diagnostic.HashCode = OpenApiDocument.GenerateHashValue(input); if (!_settings.LeaveStreamOpen) { From 96f060bce9cea7867bdc3d8bcd014bdeae49b5dc Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 22 Aug 2022 15:33:33 +0300 Subject: [PATCH 200/855] Code cleanup --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 80 +------------------ .../OpenApiStreamReader.cs | 10 --- .../Models/OpenApiDocument.cs | 29 ++----- 3 files changed, 6 insertions(+), 113 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index c37c9479d..461ca50be 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -356,57 +356,7 @@ public static OpenApiDocument FixReferences(OpenApiDocument document) return doc; } - - private static async Task GetStream(string input, ILogger logger) - { - var stopwatch = new Stopwatch(); - stopwatch.Start(); - - Stream stream; - if (input.StartsWith("http")) - { - try - { - var httpClientHandler = new HttpClientHandler() - { - SslProtocols = System.Security.Authentication.SslProtocols.Tls12, - }; - using var httpClient = new HttpClient(httpClientHandler) - { - DefaultRequestVersion = HttpVersion.Version20 - }; - stream = await httpClient.GetStreamAsync(input); - } - catch (HttpRequestException ex) - { - logger.LogError($"Could not download the file at {input}, reason{ex}"); - return null; - } - } - else - { - try - { - var fileInput = new FileInfo(input); - stream = fileInput.OpenRead(); - } - catch (Exception ex) when (ex is FileNotFoundException || - ex is PathTooLongException || - ex is DirectoryNotFoundException || - ex is IOException || - ex is UnauthorizedAccessException || - ex is SecurityException || - ex is NotSupportedException) - { - logger.LogError($"Could not open the file at {input}, reason: {ex.Message}"); - return null; - } - } - stopwatch.Stop(); - logger.LogTrace("{timestamp}ms: Read file {input}", stopwatch.ElapsedMilliseconds, input); - return stream; - } - + /// /// Takes in a file stream, parses the stream into a JsonDocument and gets a list of paths and Http methods /// @@ -462,34 +412,6 @@ private static Dictionary> EnumerateJsonDocument(JsonElemen return paths; } - /// - /// Fixes the references in the resulting OpenApiDocument. - /// - /// The converted OpenApiDocument. - /// A valid OpenApiDocument instance. - // private static OpenApiDocument FixReferences2(OpenApiDocument document) - // { - // // This method is only needed because the output of ConvertToOpenApi isn't quite a valid OpenApiDocument instance. - // // So we write it out, and read it back in again to fix it up. - - // OpenApiDocument document; - // logger.LogTrace("Parsing the OpenApi file"); - // var result = await new OpenApiStreamReader(new OpenApiReaderSettings - // { - // RuleSet = ValidationRuleSet.GetDefaultRuleSet(), - // BaseUrl = new Uri(openapi) - // } - // ).ReadAsync(stream); - - // document = result.OpenApiDocument; - // var context = result.OpenApiDiagnostic; - // var sb = new StringBuilder(); - // document.SerializeAsV3(new OpenApiYamlWriter(new StringWriter(sb))); - // var doc = new OpenApiStringReader().Read(sb.ToString(), out _); - - // return doc; - // } - /// /// Reads stream from file system or makes HTTP request depending on the input string /// diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index 0554108b2..6d21a692f 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -45,16 +45,6 @@ public OpenApiDocument Read(Stream input, out OpenApiDiagnostic diagnostic) var reader = new StreamReader(input); var result = new OpenApiTextReaderReader(_settings).Read(reader, out diagnostic); - //HashAlgorithm sha = SHA512.Create(); - //byte[] data = sha.ComputeHash(input); - //StringBuilder sb = new StringBuilder(); - //for (int i = 0; i < data.Length; i++) - //{ - // sb.Append(data[i].ToString("X2")); - //} - - - //diagnostic.HashCode = sb.ToString(); diagnostic.HashCode = OpenApiDocument.GenerateHashValue(input); if (!_settings.LeaveStreamOpen) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 6b9d3af59..ccdb65092 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; using System.Text; using Microsoft.OpenApi.Exceptions; @@ -66,8 +65,6 @@ public class OpenApiDocument : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); - private static readonly object locker = new(); - /// /// Parameter-less constructor /// @@ -381,27 +378,11 @@ public IOpenApiReferenceable ResolveReference(OpenApiReference reference) return ResolveReference(reference, false); } - ///// - ///// Computes the hash code for an OpenApiDocument and its property values. - ///// - ///// The hash code. - //public override int GetHashCode() - //{ - // // select two random prime numbers e.g 1 and 3 and use them to compute hash codes - // int hash = 1; - // hash = hash * 3 + (Workspace == null ? 0 : Workspace.GetHashCode()); - // hash = hash * 3 + (Info == null ? 0 : Info.GetHashCode()); - // hash = hash * 3 + (Servers == null ? 0 : Servers.GetHashCode()); - // hash = hash * 3 + (Paths == null ? 0 : Paths.GetHashCode()); - // hash = hash * 3 + (Components == null ? 0 : Components.GetHashCode()); - // hash = hash * 3 + (SecurityRequirements == null ? 0 : SecurityRequirements.GetHashCode()); - // hash = hash * 3 + (Tags == null ? 0 : Tags.GetHashCode()); - // hash = hash * 3 + (ExternalDocs == null ? 0 : ExternalDocs.GetHashCode()); - // hash = hash * 3 + (Extensions == null ? 0 : Extensions.GetHashCode()); - - // return hash; - //} - + /// + /// Uses the stream input to generate the hash value of an OpenApi document + /// + /// Stream containing OpenAPI description to hash. + /// The hash value. public static string GenerateHashValue(Stream input) { HashAlgorithm sha = SHA512.Create(); From 9772ad07a467e365f925b2fbcf5d921e9b1cb637 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 22 Aug 2022 16:12:41 +0300 Subject: [PATCH 201/855] Update public Api interface --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index b320f8b10..11ed58e88 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1,7 +1,7 @@ [assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/Microsoft/OpenAPI.NET")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Readers.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] -[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName="")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName=".NET Standard 2.0")] namespace Microsoft.OpenApi.Any { public enum AnyType @@ -535,6 +535,7 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IEnumerable ResolveReferences() { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } + public static string GenerateHashValue(System.IO.Stream input) { } } public class OpenApiEncoding : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { From d50f8577ccb2f2b54683a9c6026f73037f5905b1 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 22 Aug 2022 16:12:41 +0300 Subject: [PATCH 202/855] Revert "Update public Api interface" This reverts commit 9772ad07a467e365f925b2fbcf5d921e9b1cb637. --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 11ed58e88..b320f8b10 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1,7 +1,7 @@ [assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/Microsoft/OpenAPI.NET")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Readers.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] -[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName=".NET Standard 2.0")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName="")] namespace Microsoft.OpenApi.Any { public enum AnyType @@ -535,7 +535,6 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IEnumerable ResolveReferences() { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } - public static string GenerateHashValue(System.IO.Stream input) { } } public class OpenApiEncoding : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { From df65299b34981e45798160cb0fcbca413c243898 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 24 Aug 2022 12:05:08 +0300 Subject: [PATCH 203/855] Cater for file content transferred with base64 encoding --- src/Microsoft.OpenApi/Models/OpenApiOperation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index ba0af7317..9b32934c2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -255,7 +255,7 @@ public void SerializeAsV2(IOpenApiWriter writer) { var paramName = property.Key; var paramSchema = property.Value; - if (paramSchema.Type == "string" && paramSchema.Format == "binary") { + if (paramSchema.Type == "string" && paramSchema.Format == "binary" || paramSchema.Format == "base64") { paramSchema.Type = "file"; paramSchema.Format = null; } From 9b8e16b5d19f8fae7fb7b08b953276a0e6dfba4f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 24 Aug 2022 14:58:02 +0300 Subject: [PATCH 204/855] Add braces to the conditional statement --- src/Microsoft.OpenApi/Models/OpenApiOperation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 9b32934c2..d2f8dec07 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -255,7 +255,7 @@ public void SerializeAsV2(IOpenApiWriter writer) { var paramName = property.Key; var paramSchema = property.Value; - if (paramSchema.Type == "string" && paramSchema.Format == "binary" || paramSchema.Format == "base64") { + if (paramSchema.Type == "string" && (paramSchema.Format == "binary" || paramSchema.Format == "base64")) { paramSchema.Type = "file"; paramSchema.Format = null; } From 8674fe332aa83d44c25427e3d047bc9d3fd9a2dd Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 26 Aug 2022 12:32:08 +0300 Subject: [PATCH 205/855] Revert previous changes --- .../OpenApiDiagnostic.cs | 5 - .../OpenApiStreamReader.cs | 2 - .../Microsoft.OpenApi.Readers.Tests.csproj | 3 - .../V2Tests/OpenApiDocumentTests.cs | 8 +- .../V2Tests/OpenApiServerTests.cs | 12 +- .../V3Tests/OpenApiCallbackTests.cs | 155 ++++++++--------- .../V3Tests/OpenApiDocumentTests.cs | 157 ++++++++---------- .../V3Tests/OpenApiSchemaTests.cs | 17 +- 8 files changed, 169 insertions(+), 190 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs index d634fe804..c3178ccfb 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs @@ -26,10 +26,5 @@ public class OpenApiDiagnostic : IDiagnostic /// Open API specification version of the document parsed. /// public OpenApiSpecVersion SpecificationVersion { get; set; } - - /// - /// The unique hash code of the generated OpenAPI document - /// - public string HashCode { get; set; } } } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index 6d21a692f..f6c9e7613 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -45,8 +45,6 @@ public OpenApiDocument Read(Stream input, out OpenApiDiagnostic diagnostic) var reader = new StreamReader(input); var result = new OpenApiTextReaderReader(_settings).Read(reader, out diagnostic); - diagnostic.HashCode = OpenApiDocument.GenerateHashValue(input); - if (!_settings.LeaveStreamOpen) { reader.Dispose(); diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 597302062..94432db9a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -137,9 +137,6 @@ Never - - Never - Never diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index b3f3033ac..fcf0471ea 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -150,9 +150,9 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) }, Paths = new OpenApiPaths() }); - var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi2_0 }; - Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); + context.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi2_0 }); } [Fact] @@ -208,7 +208,7 @@ public void ShouldParseProducesInAnyOrder() { Type = ReferenceType.Schema, Id = "Error", - HostDocument= doc + HostDocument = doc }, Properties = new Dictionary() { @@ -407,7 +407,7 @@ public void ShouldAssignSchemaToAllResponses() { Id = "Error", Type = ReferenceType.Schema, - HostDocument= document + HostDocument = document } }; var responses = document.Paths["/items"].Operations[OperationType.Get].Responses; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs index 3e2cde88d..c87b491ab 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs @@ -280,12 +280,14 @@ public void InvalidHostShouldYieldError() var doc = reader.Read(input, out var diagnostic); doc.Servers.Count.Should().Be(0); - - Assert.Equal(OpenApiSpecVersion.OpenApi2_0, diagnostic.SpecificationVersion); - diagnostic.Errors.Should().BeEquivalentTo( - new List + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic { - new OpenApiError("#/", "Invalid host") + Errors = + { + new OpenApiError("#/", "Invalid host") + }, + SpecificationVersion = OpenApiSpecVersion.OpenApi2_0 }); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs index a89c087ef..320f01fae 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs @@ -21,28 +21,29 @@ public class OpenApiCallbackTests [Fact] public void ParseBasicCallbackShouldSucceed() { - using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicCallback.yaml")); - // Arrange - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicCallback.yaml"))) + { + // Arrange + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var callback = OpenApiV3Deserializer.LoadCallback(node); + // Act + var callback = OpenApiV3Deserializer.LoadCallback(node); - // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - callback.Should().BeEquivalentTo( - new OpenApiCallback - { - PathItems = + callback.Should().BeEquivalentTo( + new OpenApiCallback { + PathItems = + { [RuntimeExpression.Build("$request.body#/url")] = new OpenApiPathItem { @@ -68,31 +69,33 @@ public void ParseBasicCallbackShouldSucceed() } } } - } - }); + } + }); + } } [Fact] public void ParseCallbackWithReferenceShouldSucceed() { - using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "callbackWithReference.yaml")); - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "callbackWithReference.yaml"))) + { + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - // Assert - var path = openApiDoc.Paths.First().Value; - var subscribeOperation = path.Operations[OperationType.Post]; + // Assert + var path = openApiDoc.Paths.First().Value; + var subscribeOperation = path.Operations[OperationType.Post]; - var callback = subscribeOperation.Callbacks["simpleHook"]; - var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + var callback = subscribeOperation.Callbacks["simpleHook"]; - Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - callback.Should().BeEquivalentTo( - new OpenApiCallback - { - PathItems = + callback.Should().BeEquivalentTo( + new OpenApiCallback { + PathItems = + { [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation() @@ -119,38 +122,39 @@ public void ParseCallbackWithReferenceShouldSucceed() } } } - }, - Reference = new OpenApiReference - { - Type = ReferenceType.Callback, - Id = "simpleHook", - HostDocument = openApiDoc - } - }); + }, + Reference = new OpenApiReference + { + Type = ReferenceType.Callback, + Id = "simpleHook", + HostDocument = openApiDoc + } + }); + } } [Fact] public void ParseMultipleCallbacksWithReferenceShouldSucceed() { - using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleCallbacksWithReference.yaml")); - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - - // Assert - var path = openApiDoc.Paths.First().Value; - var subscribeOperation = path.Operations[OperationType.Post]; + using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleCallbacksWithReference.yaml"))) + { + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + // Assert + var path = openApiDoc.Paths.First().Value; + var subscribeOperation = path.Operations[OperationType.Post]; - Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - var callback1 = subscribeOperation.Callbacks["simpleHook"]; + var callback1 = subscribeOperation.Callbacks["simpleHook"]; - callback1.Should().BeEquivalentTo( - new OpenApiCallback - { - PathItems = + callback1.Should().BeEquivalentTo( + new OpenApiCallback { + PathItems = + { [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation() @@ -177,21 +181,21 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } } } - }, - Reference = new OpenApiReference - { - Type = ReferenceType.Callback, - Id = "simpleHook", - HostDocument = openApiDoc - } - }); + }, + Reference = new OpenApiReference + { + Type = ReferenceType.Callback, + Id = "simpleHook", + HostDocument = openApiDoc + } + }); - var callback2 = subscribeOperation.Callbacks["callback2"]; - callback2.Should().BeEquivalentTo( - new OpenApiCallback - { - PathItems = + var callback2 = subscribeOperation.Callbacks["callback2"]; + callback2.Should().BeEquivalentTo( + new OpenApiCallback { + PathItems = + { [RuntimeExpression.Build("/simplePath")]= new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation() @@ -219,15 +223,15 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } }, } - } - }); + } + }); - var callback3 = subscribeOperation.Callbacks["callback3"]; - callback3.Should().BeEquivalentTo( - new OpenApiCallback - { - PathItems = + var callback3 = subscribeOperation.Callbacks["callback3"]; + callback3.Should().BeEquivalentTo( + new OpenApiCallback { + PathItems = + { [RuntimeExpression.Build(@"http://example.com?transactionId={$request.body#/id}&email={$request.body#/email}")] = new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation() @@ -262,8 +266,9 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } } } - } - }); + } + }); + } } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 242dc6b74..6fbb7065a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -9,11 +9,13 @@ using System.Threading; using FluentAssertions; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Validations; using Microsoft.OpenApi.Validations.Rules; using Microsoft.OpenApi.Writers; +using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; @@ -32,8 +34,10 @@ public T Clone(T element) where T : IOpenApiSerializable { IOpenApiWriter writer; var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); - writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() { - InlineLocalReferences = true}); + writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() + { + InlineLocalReferences = true + }); element.SerializeAsV3(writer); writer.Flush(); stream.Position = 0; @@ -46,7 +50,7 @@ public T Clone(T element) where T : IOpenApiSerializable } } - public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) + public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) { using (var stream = new MemoryStream()) { @@ -97,9 +101,8 @@ public void ParseDocumentFromInlineStringShouldSucceed() Paths = new OpenApiPaths() }); - var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - - Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); + context.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Theory] @@ -169,30 +172,31 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) }, Paths = new OpenApiPaths() }); - var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); + context.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] public void ParseBasicDocumentWithMultipleServersShouldSucceed() { - using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDocumentWithMultipleServers.yaml")); - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDocumentWithMultipleServers.yaml"))) + { + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument - { - Info = new OpenApiInfo - { - Title = "The API", - Version = "0.9.1", - }, - Servers = + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument { + Info = new OpenApiInfo + { + Title = "The API", + Version = "0.9.1", + }, + Servers = + { new OpenApiServer { Url = new Uri("http://www.example.org/api").ToString(), @@ -203,80 +207,64 @@ public void ParseBasicDocumentWithMultipleServersShouldSucceed() Url = new Uri("https://www.example.org/api").ToString(), Description = "The https endpoint" } - }, - Paths = new OpenApiPaths() - }); + }, + Paths = new OpenApiPaths() + }); + } } [Fact] public void ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() { - using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "brokenMinimalDocument.yaml")); - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "brokenMinimalDocument.yaml"))) + { + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument - { - Info = new OpenApiInfo + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument { - Version = "0.9" - }, - Paths = new OpenApiPaths() - }); - - diagnostic.Errors.Should().BeEquivalentTo( - new List - { - new OpenApiValidatorError(nameof(OpenApiInfoRules.InfoRequiredFields),"#/info/title", "The field 'title' in 'info' object is REQUIRED.") - }); + Info = new OpenApiInfo + { + Version = "0.9" + }, + Paths = new OpenApiPaths() + }); - Assert.Equal(OpenApiSpecVersion.OpenApi3_0, diagnostic.SpecificationVersion); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic + { + Errors = + { + new OpenApiValidatorError(nameof(OpenApiInfoRules.InfoRequiredFields),"#/info/title", "The field 'title' in 'info' object is REQUIRED.") + }, + SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 + }); + } } [Fact] public void ParseMinimalDocumentShouldSucceed() { - using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml")); - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml"))) + { + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument - { - Info = new OpenApiInfo + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument { - Title = "Simple Document", - Version = "0.9.1" - }, - Paths = new OpenApiPaths() - }); - - var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; + Info = new OpenApiInfo + { + Title = "Simple Document", + Version = "0.9.1" + }, + Paths = new OpenApiPaths() + }); - Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + } } - [Fact] - public void TestHashCodesForSimilarOpenApiDocuments() - { - // Arrange - using var stream1 = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml")); - using var stream2 = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml")); - using var stream3 = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocumentWithWhitespace.yaml")); - - // Act - /* - Test whether reading in the same document twice yields the same hash code, - And reading in similar documents but one has a whitespace yields the same hash code - */ - var openApiDoc1 = new OpenApiStreamReader().Read(stream1, out var diagnostic1); - var openApiDoc2 = new OpenApiStreamReader().Read(stream2, out var diagnostic2); - var openApiDoc3 = new OpenApiStreamReader().Read(stream3, out var diagnostic3); - - // Assert - Assert.Equal(diagnostic1.HashCode, diagnostic2.HashCode); - Assert.Equal(diagnostic2.HashCode, diagnostic3.HashCode); - } - [Fact] public void ParseStandardPetStoreDocumentShouldSucceed() { @@ -703,9 +691,8 @@ public void ParseStandardPetStoreDocumentShouldSucceed() actual.Should().BeEquivalentTo(expected); } - var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - - Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); + context.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] @@ -1237,9 +1224,8 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() actual.Should().BeEquivalentTo(expected, options => options.Excluding(m => m.Name == "HostDocument")); } - var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - - Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); + context.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] @@ -1254,9 +1240,8 @@ public void ParsePetStoreExpandedShouldSucceed() // TODO: Create the object in memory and compare with the one read from YAML file. } - var context2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - - Assert.Equal(context.SpecificationVersion, context2.SpecificationVersion); + context.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index 63d7894c5..0101d9c6e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -332,9 +332,8 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() // Assert var components = openApiDoc.Components; - var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - - Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); components.Should().BeEquivalentTo( new OpenApiComponents @@ -424,7 +423,7 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() } } } - },options => options.Excluding(m => m.Name == "HostDocument")); + }, options => options.Excluding(m => m.Name == "HostDocument")); } } @@ -439,9 +438,8 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() // Assert var components = openApiDoc.Components; - var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - - Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); components.Should().BeEquivalentTo( new OpenApiComponents @@ -621,9 +619,8 @@ public void ParseSelfReferencingSchemaShouldNotStackOverflow() // Assert var components = openApiDoc.Components; - var diagnostic2 = new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }; - - Assert.Equal(diagnostic.SpecificationVersion, diagnostic2.SpecificationVersion); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); var schemaExtension = new OpenApiSchema() { From ba7377748d9560b6fd8160ebfbb0bd66ed6d3db2 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 26 Aug 2022 12:33:05 +0300 Subject: [PATCH 206/855] Refactor hashing logic and add test cases --- .../Models/OpenApiDocument.cs | 33 +++++++++++++++---- .../Microsoft.OpenApi.Tests.csproj | 14 ++++++++ .../Models/OpenApiDocumentTests.cs | 30 ++++++++++++++++- .../Models/Samples/sampleDocument.yaml | 5 +++ .../sampleDocumentWithWhiteSpaces.yaml} | 6 ++-- 5 files changed, 77 insertions(+), 11 deletions(-) create mode 100644 test/Microsoft.OpenApi.Tests/Models/Samples/sampleDocument.yaml rename test/{Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/minimalDocumentWithWhitespace.yaml => Microsoft.OpenApi.Tests/Models/Samples/sampleDocumentWithWhiteSpaces.yaml} (100%) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index ccdb65092..09a183811 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.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; @@ -65,6 +65,11 @@ public class OpenApiDocument : IOpenApiSerializable, IOpenApiExtensible /// public IDictionary Extensions { get; set; } = new Dictionary(); + /// + /// The unique hash code of the generated OpenAPI document + /// + public string HashCode => GenerateHashValue(this); + /// /// Parameter-less constructor /// @@ -379,21 +384,35 @@ public IOpenApiReferenceable ResolveReference(OpenApiReference reference) } /// - /// Uses the stream input to generate the hash value of an OpenApi document + /// Takes in an OpenApi document instance and generates its hash value /// - /// Stream containing OpenAPI description to hash. + /// The OpenAPI description to hash. /// The hash value. - public static string GenerateHashValue(Stream input) + public static string GenerateHashValue(OpenApiDocument doc) { HashAlgorithm sha = SHA512.Create(); - byte[] result = sha.ComputeHash(input); + using var memoryStream = new MemoryStream(); + + using var cryptoStream = new CryptoStream(memoryStream, sha, CryptoStreamMode.Write); + using var streamWriter = new StreamWriter(cryptoStream); + + var openApiJsonWriter = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings { Terse = true }); + doc.SerializeAsV3(openApiJsonWriter); + openApiJsonWriter.Flush(); + var hash = memoryStream.ToArray(); + + return ConvertByteArrayToString(hash); + } + + private static string ConvertByteArrayToString(byte[] hash) + { // Build the final string by converting each byte // into hex and appending it to a StringBuilder StringBuilder sb = new StringBuilder(); - for (int i = 0; i < result.Length; i++) + for (int i = 0; i < hash.Length; i++) { - sb.Append(result[i].ToString("X2")); + sb.Append(hash[i].ToString("X2")); } return sb.ToString(); diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index a6ba76259..872447cc9 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -36,6 +36,20 @@ + + Always + + + Always + + + + + + + + + \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 10cadd597..cd4cc2b5a 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.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; @@ -10,6 +10,7 @@ using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Readers; using Microsoft.OpenApi.Writers; using VerifyXunit; using Xunit; @@ -1314,5 +1315,32 @@ public void SerializeRelativeRootPathWithHostAsV2JsonWorks() actual.Should().Be(expected); } + [Fact] + public void TestHashCodesForSimilarOpenApiDocuments() + { + // Arrange + var sampleFolderPath = "Models/Samples/"; + + var doc1 = ParseInputFile(Path.Combine(sampleFolderPath, "sampleDocument.yaml")); + var doc2 = ParseInputFile(Path.Combine(sampleFolderPath, "sampleDocument.yaml")); + var doc3 = ParseInputFile(Path.Combine(sampleFolderPath, "sampleDocumentWithWhiteSpaces.yaml")); + + // Act && Assert + /* + Test whether reading in two similar documents yield the same hash code, + And reading in similar documents(one has a whitespace) yields the same hash code as the result is terse + */ + Assert.True(doc1.HashCode != null && doc2.HashCode != null && doc1.HashCode.Equals(doc2.HashCode)); + Assert.Equal(doc1.HashCode, doc3.HashCode); + } + + private static OpenApiDocument ParseInputFile(string filePath) + { + // Read in the input yaml file + using FileStream stream = File.OpenRead(filePath); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + + return openApiDoc; + } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/Samples/sampleDocument.yaml b/test/Microsoft.OpenApi.Tests/Models/Samples/sampleDocument.yaml new file mode 100644 index 000000000..34153a5f5 --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Models/Samples/sampleDocument.yaml @@ -0,0 +1,5 @@ +openapi : 3.0.0 +info: + title: Simple Document + version: 0.9.1 +paths: {} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/minimalDocumentWithWhitespace.yaml b/test/Microsoft.OpenApi.Tests/Models/Samples/sampleDocumentWithWhiteSpaces.yaml similarity index 100% rename from test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/minimalDocumentWithWhitespace.yaml rename to test/Microsoft.OpenApi.Tests/Models/Samples/sampleDocumentWithWhiteSpaces.yaml index a68eb2fee..5f31baa0e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/minimalDocumentWithWhitespace.yaml +++ b/test/Microsoft.OpenApi.Tests/Models/Samples/sampleDocumentWithWhiteSpaces.yaml @@ -1,9 +1,9 @@ openapi : 3.0.0 + info: title: Simple Document - version: 0.9.1 -paths: {} - + version: 0.9.1 +paths: {} From 2bb383cd0630fd86967fb08aa48238a7c6ecd59a Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 26 Aug 2022 12:54:26 +0300 Subject: [PATCH 207/855] Update public API interface --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index b320f8b10..823ddab81 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1,7 +1,7 @@ [assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/Microsoft/OpenAPI.NET")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Readers.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] -[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName="")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName=".NET Standard 2.0")] namespace Microsoft.OpenApi.Any { public enum AnyType @@ -525,6 +525,7 @@ namespace Microsoft.OpenApi.Models public Microsoft.OpenApi.Models.OpenApiComponents Components { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public Microsoft.OpenApi.Models.OpenApiExternalDocs ExternalDocs { get; set; } + public string HashCode { get; } public Microsoft.OpenApi.Models.OpenApiInfo Info { get; set; } public Microsoft.OpenApi.Models.OpenApiPaths Paths { get; set; } public System.Collections.Generic.IList SecurityRequirements { get; set; } @@ -535,6 +536,7 @@ namespace Microsoft.OpenApi.Models public System.Collections.Generic.IEnumerable ResolveReferences() { } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } + public static string GenerateHashValue(Microsoft.OpenApi.Models.OpenApiDocument doc) { } } public class OpenApiEncoding : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { From feebffc73295355c80588e4d805a20fb4d1ce5ff Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 26 Aug 2022 13:04:57 +0300 Subject: [PATCH 208/855] Remove framework display name from interface --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 823ddab81..745d91d43 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1,7 +1,7 @@ [assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/Microsoft/OpenAPI.NET")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Readers.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] -[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName=".NET Standard 2.0")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName="")] namespace Microsoft.OpenApi.Any { public enum AnyType From 25395760922737cef9efd8c54f55af26bb16ca67 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 26 Aug 2022 16:28:10 +0300 Subject: [PATCH 209/855] Address PR feedback --- src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs | 3 --- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 9 ++++----- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index f6c9e7613..13bdbdef8 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -3,8 +3,6 @@ using System; using System.IO; -using System.Security.Cryptography; -using System.Text; using System.Threading.Tasks; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; @@ -44,7 +42,6 @@ public OpenApiDocument Read(Stream input, out OpenApiDiagnostic diagnostic) { var reader = new StreamReader(input); var result = new OpenApiTextReaderReader(_settings).Read(reader, out diagnostic); - if (!_settings.LeaveStreamOpen) { reader.Dispose(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 09a183811..836e45dd8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -390,17 +390,16 @@ public IOpenApiReferenceable ResolveReference(OpenApiReference reference) /// The hash value. public static string GenerateHashValue(OpenApiDocument doc) { - HashAlgorithm sha = SHA512.Create(); - using var memoryStream = new MemoryStream(); - - using var cryptoStream = new CryptoStream(memoryStream, sha, CryptoStreamMode.Write); + using HashAlgorithm sha = SHA512.Create(); + using var cryptoStream = new CryptoStream(Stream.Null, sha, CryptoStreamMode.Write); using var streamWriter = new StreamWriter(cryptoStream); var openApiJsonWriter = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings { Terse = true }); doc.SerializeAsV3(openApiJsonWriter); openApiJsonWriter.Flush(); - var hash = memoryStream.ToArray(); + cryptoStream.FlushFinalBlock(); + var hash = sha.Hash; return ConvertByteArrayToString(hash); } From 6d7f73592af60e598a322d37db07259691986954 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 29 Aug 2022 10:40:52 +0300 Subject: [PATCH 210/855] Update string comparison logic --- src/Microsoft.OpenApi/Models/OpenApiOperation.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index d2f8dec07..7983a243e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -253,9 +253,11 @@ public void SerializeAsV2(IOpenApiWriter writer) { foreach (var property in RequestBody.Content.First().Value.Schema.Properties) { - var paramName = property.Key; var paramSchema = property.Value; - if (paramSchema.Type == "string" && (paramSchema.Format == "binary" || paramSchema.Format == "base64")) { + if ("string".Equals(paramSchema.Type, StringComparison.OrdinalIgnoreCase) + && ("binary".Equals(paramSchema.Format, StringComparison.OrdinalIgnoreCase) + || "base64".Equals(paramSchema.Format, StringComparison.OrdinalIgnoreCase))) + { paramSchema.Type = "file"; paramSchema.Format = null; } From 5c6d17f7e2835c2a31aea9c550bd2a1462937e6f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 29 Aug 2022 17:00:10 +0300 Subject: [PATCH 211/855] Attach changelog labels for improved release notes experience --- .azure-pipelines/ci-build.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 3e1b04fca..2f1b6b9b5 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -285,6 +285,12 @@ stages: releaseNotesSource: inline assets: '$(Pipeline.Workspace)\**\*.exe' changeLogType: issueBased + changeLogLabels: '[ + { "label" : "feature-work", "feature", "displayName" : "New Features", "state" : "closed" }, + { "label" : "enhancement", "V2-Enhancement", "displayName" : "Enhancements", "state" : "closed" }, + { "label" : "bug", "bug-fix", "displayName" : "Bugs", "state" : "closed" }, + { "label" : "documentation", "doc", "displayName" : "Documentation", "state" : "closed"}, + { "label" : "dependencies", "displayName" : "Package Updates", "state" : "closed" }]' - deployment: deploy_lib dependsOn: [] From 7bbb331124c3fa2515e461076d89790b4d608c91 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 30 Aug 2022 20:26:30 +0300 Subject: [PATCH 212/855] Create a backing parameter style and set the default based on In value --- .../Models/OpenApiParameter.cs | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index c6f06b1f6..e0e472721 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -16,6 +16,7 @@ namespace Microsoft.OpenApi.Models public class OpenApiParameter : IOpenApiSerializable, IOpenApiReferenceable, IEffective, IOpenApiExtensible { private bool? _explode; + public ParameterStyle? _style; /// /// Indicates if object is populated with data or is just a reference to the data @@ -73,7 +74,11 @@ public class OpenApiParameter : IOpenApiSerializable, IOpenApiReferenceable, IEf /// Default values (based on value of in): for query - form; for path - simple; for header - simple; /// for cookie - form. /// - public ParameterStyle? Style { get; set; } + public ParameterStyle? Style + { + get => _style ?? SetDefaultStyleValue(); + set => _style = value; + } /// /// When this is true, parameter values of type array or object generate separate parameters @@ -396,6 +401,20 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) writer.WriteEndObject(); } + private ParameterStyle? SetDefaultStyleValue() + { + Style = In switch + { + ParameterLocation.Query => (ParameterStyle?)ParameterStyle.Form, + ParameterLocation.Header => (ParameterStyle?)ParameterStyle.Simple, + ParameterLocation.Path => (ParameterStyle?)ParameterStyle.Simple, + ParameterLocation.Cookie => (ParameterStyle?)ParameterStyle.Form, + _ => (ParameterStyle?)ParameterStyle.Simple, + }; + + return Style; + } + } /// From 4063c43682138d1c7921326d168b9799f4760cd8 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 30 Aug 2022 20:26:39 +0300 Subject: [PATCH 213/855] Add test --- .../Models/OpenApiParameterTests.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index 5dffea57c..1b4cdffcd 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs @@ -184,6 +184,25 @@ public void WhenStyleIsFormTheDefaultValueOfExplodeShouldBeTrueOtherwiseFalse(Pa parameter.Explode.Should().Be(expectedExplode); } + [Theory] + [InlineData(ParameterLocation.Path, ParameterStyle.Simple)] + [InlineData(ParameterLocation.Query, ParameterStyle.Form)] + [InlineData(ParameterLocation.Header, ParameterStyle.Simple)] + [InlineData(ParameterLocation.Cookie, ParameterStyle.Form)] + [InlineData(null, ParameterStyle.Simple)] + public void WhenStyleAndInIsNullTheDefaultValueOfStyleShouldBeSimple(ParameterLocation? inValue, ParameterStyle expectedStyle) + { + // Arrange + var parameter = new OpenApiParameter + { + Name = "name1", + In = inValue, + }; + + // Act & Assert + parameter.Style.Should().Be(expectedStyle); + } + [Fact] public void SerializeBasicParameterAsV3JsonWorks() { From d56a025c830bed1ecf610531e770736edbb2e034 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 30 Aug 2022 21:27:23 +0300 Subject: [PATCH 214/855] Removing the null style value test case since we're setting a default value for style --- test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index 1b4cdffcd..db16a5423 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.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; @@ -169,7 +169,6 @@ public OpenApiParameterTests(ITestOutputHelper output) [Theory] [InlineData(ParameterStyle.Form, true)] [InlineData(ParameterStyle.SpaceDelimited, false)] - [InlineData(null, false)] public void WhenStyleIsFormTheDefaultValueOfExplodeShouldBeTrueOtherwiseFalse(ParameterStyle? style, bool expectedExplode) { // Arrange From b13f08cc720b35c8ee3daea321943f1387b44794 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 30 Aug 2022 21:45:42 +0300 Subject: [PATCH 215/855] Update public api interface and refactor tests --- .../Models/OpenApiOperationTests.cs | 13 +++++++++---- .../Models/OpenApiParameterTests.cs | 5 +++-- .../PublicApi/PublicApi.approved.txt | 1 + 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index a59746214..167383b36 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -334,11 +334,13 @@ public void SerializeOperationWithBodyAsV3JsonWorks() ""parameters"": [ { ""name"": ""parameter1"", - ""in"": ""path"" + ""in"": ""path"", + ""style"": ""simple"" }, { ""name"": ""parameter2"", - ""in"": ""header"" + ""in"": ""header"", + ""style"": ""simple"" } ], ""requestBody"": { @@ -407,11 +409,13 @@ public void SerializeAdvancedOperationWithTagAndSecurityAsV3JsonWorks() ""parameters"": [ { ""name"": ""parameter1"", - ""in"": ""path"" + ""in"": ""path"", + ""style"": ""simple"" }, { ""name"": ""parameter2"", - ""in"": ""header"" + ""in"": ""header"", + ""style"": ""simple"" } ], ""requestBody"": { @@ -501,6 +505,7 @@ public void SerializeOperationWithFormDataAsV3JsonWorks() ""in"": ""path"", ""description"": ""ID of pet that needs to be updated"", ""required"": true, + ""style"": ""simple"", ""schema"": { ""type"": ""string"" } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index db16a5423..6db019be7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.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; @@ -208,7 +208,8 @@ public void SerializeBasicParameterAsV3JsonWorks() // Arrange var expected = @"{ ""name"": ""name1"", - ""in"": ""path"" + ""in"": ""path"", + ""style"": ""simple"" }"; // Act diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index b320f8b10..4887054cc 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -719,6 +719,7 @@ namespace Microsoft.OpenApi.Models } public class OpenApiParameter : Microsoft.OpenApi.Interfaces.IEffective, Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiReferenceable, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { + public Microsoft.OpenApi.Models.ParameterStyle? _style; public OpenApiParameter() { } public OpenApiParameter(Microsoft.OpenApi.Models.OpenApiParameter parameter) { } public bool AllowEmptyValue { get; set; } From 006d1de0a561bf9f3f897b1ad18af5a7208e2d58 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 30 Aug 2022 21:46:32 +0300 Subject: [PATCH 216/855] Update existing .verified.txt files with new changes --- ...umentAsV2JsonWorks_produceTerseOutput=False.verified.txt | 6 ++++-- ...cumentAsV2JsonWorks_produceTerseOutput=True.verified.txt | 2 +- ...umentAsV3JsonWorks_produceTerseOutput=False.verified.txt | 4 ++++ ...cumentAsV3JsonWorks_produceTerseOutput=True.verified.txt | 2 +- ...renceAsV2JsonWorks_produceTerseOutput=False.verified.txt | 6 ++++-- ...erenceAsV2JsonWorks_produceTerseOutput=True.verified.txt | 2 +- ...renceAsV3JsonWorks_produceTerseOutput=False.verified.txt | 4 ++++ ...erenceAsV3JsonWorks_produceTerseOutput=True.verified.txt | 2 +- ...sionsAsV3JsonWorks_produceTerseOutput=False.verified.txt | 2 ++ ...nsionsAsV3JsonWorks_produceTerseOutput=True.verified.txt | 2 +- ...eferenceWorksAsync_produceTerseOutput=False.verified.txt | 3 ++- ...ReferenceWorksAsync_produceTerseOutput=True.verified.txt | 2 +- 12 files changed, 26 insertions(+), 11 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt index 96eff63d4..a991e0761 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt @@ -38,14 +38,16 @@ "type": "array", "items": { "type": "string" - } + }, + "collectionFormat": "multi" }, { "in": "query", "name": "limit", "description": "maximum number of results to return", "type": "integer", - "format": "int32" + "format": "int32", + "collectionFormat": "multi" } ], "responses": { diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt index 903ff33f7..5ce01bf79 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http"],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"query","name":"tags","description":"tags to filter by","type":"array","items":{"type":"string"}},{"in":"query","name":"limit","description":"maximum number of results to return","type":"integer","format":"int32"}],"responses":{"200":{"description":"pet response","schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","consumes":["application/json"],"produces":["application/json","text/html"],"parameters":[{"in":"body","name":"body","description":"Pet to add to the store","required":true,"schema":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}}],"responses":{"200":{"description":"pet response","schema":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to fetch","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"pet response","schema":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","produces":["text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to delete","required":true,"type":"integer","format":"int64"}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}}}},"definitions":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}} \ No newline at end of file +{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http"],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"query","name":"tags","description":"tags to filter by","type":"array","items":{"type":"string"},"collectionFormat":"multi"},{"in":"query","name":"limit","description":"maximum number of results to return","type":"integer","format":"int32","collectionFormat":"multi"}],"responses":{"200":{"description":"pet response","schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","consumes":["application/json"],"produces":["application/json","text/html"],"parameters":[{"in":"body","name":"body","description":"Pet to add to the store","required":true,"schema":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}}],"responses":{"200":{"description":"pet response","schema":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to fetch","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"pet response","schema":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","produces":["text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to delete","required":true,"type":"integer","format":"int64"}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}}}},"definitions":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt index a688f8525..5b27add35 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -30,6 +30,7 @@ "name": "tags", "in": "query", "description": "tags to filter by", + "style": "form", "schema": { "type": "array", "items": { @@ -41,6 +42,7 @@ "name": "limit", "in": "query", "description": "maximum number of results to return", + "style": "form", "schema": { "type": "integer", "format": "int32" @@ -264,6 +266,7 @@ "in": "path", "description": "ID of pet to fetch", "required": true, + "style": "simple", "schema": { "type": "integer", "format": "int64" @@ -375,6 +378,7 @@ "in": "path", "description": "ID of pet to delete", "required": true, + "style": "simple", "schema": { "type": "integer", "format": "int64" diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt index 0bb1c9679..e3abf0e50 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"application/xml":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"application/xml":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file +{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","style":"form","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","style":"form","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"application/xml":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"style":"simple","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"application/xml":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"style":"simple","schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt index 0e3b74125..1ee60de40 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt @@ -38,14 +38,16 @@ "type": "array", "items": { "type": "string" - } + }, + "collectionFormat": "multi" }, { "in": "query", "name": "limit", "description": "maximum number of results to return", "type": "integer", - "format": "int32" + "format": "int32", + "collectionFormat": "multi" } ], "responses": { diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt index b54e2ac86..682b253b7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http"],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"query","name":"tags","description":"tags to filter by","type":"array","items":{"type":"string"}},{"in":"query","name":"limit","description":"maximum number of results to return","type":"integer","format":"int32"}],"responses":{"200":{"description":"pet response","schema":{"type":"array","items":{"$ref":"#/definitions/pet"}}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","consumes":["application/json"],"produces":["application/json","text/html"],"parameters":[{"in":"body","name":"body","description":"Pet to add to the store","required":true,"schema":{"$ref":"#/definitions/newPet"}}],"responses":{"200":{"description":"pet response","schema":{"$ref":"#/definitions/pet"}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to fetch","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"pet response","schema":{"$ref":"#/definitions/pet"}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","produces":["text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to delete","required":true,"type":"integer","format":"int64"}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}}}},"definitions":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}} \ No newline at end of file +{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http"],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"query","name":"tags","description":"tags to filter by","type":"array","items":{"type":"string"},"collectionFormat":"multi"},{"in":"query","name":"limit","description":"maximum number of results to return","type":"integer","format":"int32","collectionFormat":"multi"}],"responses":{"200":{"description":"pet response","schema":{"type":"array","items":{"$ref":"#/definitions/pet"}}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","consumes":["application/json"],"produces":["application/json","text/html"],"parameters":[{"in":"body","name":"body","description":"Pet to add to the store","required":true,"schema":{"$ref":"#/definitions/newPet"}}],"responses":{"200":{"description":"pet response","schema":{"$ref":"#/definitions/pet"}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to fetch","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"pet response","schema":{"$ref":"#/definitions/pet"}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","produces":["text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to delete","required":true,"type":"integer","format":"int64"}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}}}},"definitions":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=False.verified.txt index f1da0b354..f272b26eb 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -30,6 +30,7 @@ "name": "tags", "in": "query", "description": "tags to filter by", + "style": "form", "schema": { "type": "array", "items": { @@ -41,6 +42,7 @@ "name": "limit", "in": "query", "description": "maximum number of results to return", + "style": "form", "schema": { "type": "integer", "format": "int32" @@ -149,6 +151,7 @@ "in": "path", "description": "ID of pet to fetch", "required": true, + "style": "simple", "schema": { "type": "integer", "format": "int64" @@ -202,6 +205,7 @@ "in": "path", "description": "ID of pet to delete", "required": true, + "style": "simple", "schema": { "type": "integer", "format": "int64" diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=True.verified.txt index be8dcc627..2ac8e39bb 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/pet"}}},"application/xml":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/pet"}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/newPet"}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/pet"}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/pet"}},"application/xml":{"schema":{"$ref":"#/components/schemas/pet"}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file +{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","style":"form","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","style":"form","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/pet"}}},"application/xml":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/pet"}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/newPet"}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/pet"}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"style":"simple","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/pet"}},"application/xml":{"schema":{"$ref":"#/components/schemas/pet"}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"style":"simple","schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=False.verified.txt index c2e9f5312..8b90dd0ee 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -20,6 +20,7 @@ "in": "path", "description": "The first operand", "required": true, + "style": "simple", "schema": { "type": "integer", "my-extension": 4 @@ -31,6 +32,7 @@ "in": "path", "description": "The second operand", "required": true, + "style": "simple", "schema": { "type": "integer", "my-extension": 4 diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=True.verified.txt index da61a8817..c1eca99f6 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/add/{operand1}/{operand2}":{"get":{"operationId":"addByOperand1AndByOperand2","parameters":[{"name":"operand1","in":"path","description":"The first operand","required":true,"schema":{"type":"integer","my-extension":4},"my-extension":4},{"name":"operand2","in":"path","description":"The second operand","required":true,"schema":{"type":"integer","my-extension":4},"my-extension":4}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}}}}}}} \ No newline at end of file +{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/add/{operand1}/{operand2}":{"get":{"operationId":"addByOperand1AndByOperand2","parameters":[{"name":"operand1","in":"path","description":"The first operand","required":true,"style":"simple","schema":{"type":"integer","my-extension":4},"my-extension":4},{"name":"operand2","in":"path","description":"The second operand","required":true,"style":"simple","schema":{"type":"integer","my-extension":4},"my-extension":4}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}}}}}}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=False.verified.txt index 5275532e8..f4424fa30 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=False.verified.txt @@ -1,4 +1,5 @@ { "name": "name1", - "in": "path" + "in": "path", + "style": "simple" } \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=True.verified.txt index ec654beb0..703bc6613 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"name":"name1","in":"path"} \ No newline at end of file +{"name":"name1","in":"path","style":"simple"} \ No newline at end of file From f0a3fde93ebe7c3e23c6aba41fabb7c1ef3665f7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 21:14:34 +0000 Subject: [PATCH 217/855] Bump Microsoft.NET.Test.Sdk from 17.3.0 to 17.3.1 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.3.0 to 17.3.1. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v17.3.0...v17.3.1) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 6045d85b6..084738bac 100644 --- a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 94432db9a..63b7a2a1f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -250,7 +250,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index ef9886bb9..114ba749c 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -8,7 +8,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 872447cc9..5b476500c 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -16,7 +16,7 @@ - + From 4ecd027f3ffffdbd224c5a99268a4483ff48ad4f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 1 Sep 2022 20:12:38 +0300 Subject: [PATCH 218/855] Add child schema format to parent schema when serializing as V2 --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 6 ++ .../Models/OpenApiSchemaTests.cs | 63 +++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 7482b6baf..95fe873ab 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -707,6 +707,12 @@ internal void WriteAsSchemaProperties( // oneOf (Not Supported in V2) - Write the first schema only as an allOf. writer.WriteOptionalCollection(OpenApiConstants.AllOf, OneOf?.Take(1), (w, s) => s.SerializeAsV2(w)); } + if (OneOf?.Count > 0) + { + // Take the format and set it at the root + var oneOfFormat = OneOf.Select(x => x.Format.ToString()).FirstOrDefault(); + this.Format = oneOfFormat; + } } // properties diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index ae13944e6..26e8df5f8 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -422,5 +422,68 @@ public async Task SerializeSchemaWRequiredPropertiesAsV2JsonWorksAsync(bool prod // Assert await Verifier.Verify(actual).UseParameters(produceTerseOutput); } + + [Fact] + public void SerializeSchemaPrimitiveTypeShouldRemoveFormatInRootIfPresentInChildrenSchema() + { + // 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();//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n",""); + + // Serialize as V3 + //schema.SerializeAsV3(openApiJsonWriter); + //openApiJsonWriter.Flush(); + + //var v3Schema = outputStringWriter.GetStringBuilder().ToString();//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n", ""); + + var expectedV2Schema = @"{ +""allOf"": [ +{ + ""format"": ""decimal"", + ""type"": ""number"" +}], +""format"": ""decimal"" +}".Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n",""); + + + var expectedV3Schema = @"{ +""allOf"": [ +{ + ""format"": ""decimal"", + ""type"": ""number"" +}]} +{""oneOf"": [ +{ + ""type"": ""number"", + ""format"": ""decimal"" +}, +{""type"" : ""string""} + +]}}";//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n", ""); + + // Assert + Assert.Equal(expectedV2Schema, v2Schema); // Assert that v2 schema has the root schema Format defined + //Assert.Equal(expectedV3Schema, v3Schema); + } } } From 00fe8db93bce4e449af3b505dfeaf8d2cd0d05ee Mon Sep 17 00:00:00 2001 From: Irvine Date: Thu, 1 Sep 2022 21:21:40 +0300 Subject: [PATCH 219/855] Retrieve Format property --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 14 ++++++-------- .../Models/OpenApiSchemaTests.cs | 17 +++++++++-------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 95fe873ab..c3b36c4f2 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(x => x.Format != null)?.Format ?? + AnyOf?.FirstOrDefault(x => x.Format != null)?.Format ?? + OneOf?.FirstOrDefault(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) { @@ -707,12 +711,6 @@ internal void WriteAsSchemaProperties( // oneOf (Not Supported in V2) - Write the first schema only as an allOf. writer.WriteOptionalCollection(OpenApiConstants.AllOf, OneOf?.Take(1), (w, s) => s.SerializeAsV2(w)); } - if (OneOf?.Count > 0) - { - // Take the format and set it at the root - var oneOfFormat = OneOf.Select(x => x.Format.ToString()).FirstOrDefault(); - this.Format = oneOfFormat; - } } // properties diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index 26e8df5f8..a2e991e75 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -448,7 +448,7 @@ public void SerializeSchemaPrimitiveTypeShouldRemoveFormatInRootIfPresentInChild schema.SerializeAsV2(openApiJsonWriter); openApiJsonWriter.Flush(); - var v2Schema = outputStringWriter.GetStringBuilder().ToString();//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n",""); + var v2Schema = outputStringWriter.GetStringBuilder().ToString().MakeLineBreaksEnvironmentNeutral();//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n",""); // Serialize as V3 //schema.SerializeAsV3(openApiJsonWriter); @@ -457,13 +457,14 @@ public void SerializeSchemaPrimitiveTypeShouldRemoveFormatInRootIfPresentInChild //var v3Schema = outputStringWriter.GetStringBuilder().ToString();//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n", ""); var expectedV2Schema = @"{ -""allOf"": [ -{ - ""format"": ""decimal"", - ""type"": ""number"" -}], -""format"": ""decimal"" -}".Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n",""); + ""format"": ""decimal"", + ""allOf"": [ + { + ""format"": ""decimal"", + ""type"": ""number"" + } + ] +}".MakeLineBreaksEnvironmentNeutral(); var expectedV3Schema = @"{ From 0818fb742bca9c330dcd066b37aed8c0288b7ac7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 1 Sep 2022 23:27:34 +0300 Subject: [PATCH 220/855] Clean up code --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 6 ++-- .../Models/OpenApiSchemaTests.cs | 29 ++----------------- 2 files changed, 6 insertions(+), 29 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index c3b36c4f2..8734c19a2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -630,9 +630,9 @@ internal void WriteAsSchemaProperties( } // format - Format ??= AllOf?.FirstOrDefault(x => x.Format != null)?.Format ?? - AnyOf?.FirstOrDefault(x => x.Format != null)?.Format ?? - OneOf?.FirstOrDefault(x => x.Format != null)?.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); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index a2e991e75..429129c1e 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -424,7 +424,7 @@ public async Task SerializeSchemaWRequiredPropertiesAsV2JsonWorksAsync(bool prod } [Fact] - public void SerializeSchemaPrimitiveTypeShouldRemoveFormatInRootIfPresentInChildrenSchema() + public void SerializeAsV2ShouldSetFormatPropertyInParentSchemaIfPresentInChildrenSchema() { // Arrange var schema = new OpenApiSchema() @@ -448,13 +448,7 @@ public void SerializeSchemaPrimitiveTypeShouldRemoveFormatInRootIfPresentInChild schema.SerializeAsV2(openApiJsonWriter); openApiJsonWriter.Flush(); - var v2Schema = outputStringWriter.GetStringBuilder().ToString().MakeLineBreaksEnvironmentNeutral();//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n",""); - - // Serialize as V3 - //schema.SerializeAsV3(openApiJsonWriter); - //openApiJsonWriter.Flush(); - - //var v3Schema = outputStringWriter.GetStringBuilder().ToString();//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n", ""); + var v2Schema = outputStringWriter.GetStringBuilder().ToString().MakeLineBreaksEnvironmentNeutral(); var expectedV2Schema = @"{ ""format"": ""decimal"", @@ -466,25 +460,8 @@ public void SerializeSchemaPrimitiveTypeShouldRemoveFormatInRootIfPresentInChild ] }".MakeLineBreaksEnvironmentNeutral(); - - var expectedV3Schema = @"{ -""allOf"": [ -{ - ""format"": ""decimal"", - ""type"": ""number"" -}]} -{""oneOf"": [ -{ - ""type"": ""number"", - ""format"": ""decimal"" -}, -{""type"" : ""string""} - -]}}";//.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\n", ""); - // Assert - Assert.Equal(expectedV2Schema, v2Schema); // Assert that v2 schema has the root schema Format defined - //Assert.Equal(expectedV3Schema, v3Schema); + Assert.Equal(expectedV2Schema, v2Schema); } } } From 8cec362ceeb7f59aaaffc0d7ca70f08cc0ed806d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 2 Sep 2022 14:57:01 +0300 Subject: [PATCH 221/855] Bump lib versions --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 94d74046d..9ca5f6cfe 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.4.0-preview2 + 1.4.0-preview3 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index a768312e6..1bbfcb987 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.0-preview2 + 1.4.0-preview3 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From b76499a1fa36bebf12649661d833dc8ace7d67d2 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 2 Sep 2022 17:32:42 +0300 Subject: [PATCH 222/855] v1.4.0 stable release --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 9ca5f6cfe..3fdbf2b6d 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.4.0-preview3 + 1.4.0 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 1bbfcb987..f07012b5d 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.0-preview3 + 1.4.0 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 6ff3176aae598ead11894df46088c446e5637aba Mon Sep 17 00:00:00 2001 From: Irvine Sunday <40403681+irvinesunday@users.noreply.github.com> Date: Wed, 7 Sep 2022 18:50:57 +0300 Subject: [PATCH 223/855] Appends `format` property value to root schema if contained in `anyOf`, `oneOf` or `allOf` when serializing as v2 (#1001) * Retrieve format from schema composition properties when serializing as V2 * Update tests * Check for format nullability or empty * Bump up lib. version * PR review comments: validate nullability and empty --- .../Microsoft.OpenApi.csproj | 2 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 18 +++++++-- .../Models/OpenApiParameterTests.cs | 37 ++++++++++++++++++- 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index f07012b5d..fa8bee8bf 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.0 + 1.4.1 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 8734c19a2..6019d7362 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; @@ -566,6 +566,13 @@ internal void WriteAsItemsProperties(IOpenApiWriter writer) writer.WriteProperty(OpenApiConstants.Type, Type); // format + if (string.IsNullOrEmpty(Format)) + { + Format = AllOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? + AnyOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? + OneOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format; + } + writer.WriteProperty(OpenApiConstants.Format, Format); // items @@ -630,9 +637,12 @@ 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; + if (string.IsNullOrEmpty(Format)) + { + Format = AllOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? + AnyOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? + OneOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format; + } writer.WriteProperty(OpenApiConstants.Format, Format); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index 6db019be7..cfcc56d15 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs @@ -50,7 +50,12 @@ public class OpenApiParameterTests Schema = new OpenApiSchema { Title = "title2", - Description = "description2" + Description = "description2", + OneOf = new List + { + new OpenApiSchema { Type = "number", Format = "double" }, + new OpenApiSchema { Type = "string" } + } }, Examples = new Dictionary { @@ -234,6 +239,15 @@ public void SerializeAdvancedParameterAsV3JsonWorks() ""explode"": true, ""schema"": { ""title"": ""title2"", + ""oneOf"": [ + { + ""type"": ""number"", + ""format"": ""double"" + }, + { + ""type"": ""string"" + } + ], ""description"": ""description2"" }, ""examples"": { @@ -253,6 +267,27 @@ public void SerializeAdvancedParameterAsV3JsonWorks() actual.Should().Be(expected); } + [Fact] + public void SerializeAdvancedParameterAsV2JsonWorks() + { + // Arrange + var expected = @"{ + ""in"": ""path"", + ""name"": ""name1"", + ""description"": ""description1"", + ""required"": true, + ""format"": ""double"" +}"; + + // Act + var actual = AdvancedPathParameterWithSchema.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); + + // Assert + actual = actual.MakeLineBreaksEnvironmentNeutral(); + expected = expected.MakeLineBreaksEnvironmentNeutral(); + actual.Should().Be(expected); + } + [Theory] [InlineData(true)] [InlineData(false)] From 9b4a0ef2cdd444668c3ac84c5d98d41b89274ee3 Mon Sep 17 00:00:00 2001 From: Millicent Achieng Date: Thu, 8 Sep 2022 22:00:18 +0300 Subject: [PATCH 224/855] Separate warnings and errors in Open API YAML reader ReadAsync method --- .../OpenApiYamlDocumentReader.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 3aedafbf1..b26c982fe 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -114,11 +114,15 @@ public async Task ReadAsync(YamlDocument input) // Validate the document if (_settings.RuleSet != null && _settings.RuleSet.Rules.Count > 0) { - var errors = document.Validate(_settings.RuleSet); - foreach (var item in errors) + var openApiErrors = document.Validate(_settings.RuleSet); + foreach (var item in openApiErrors.Where(e => e is OpenApiValidatorError)) { diagnostic.Errors.Add(item); } + foreach (var item in openApiErrors.Where(e => e is OpenApiValidatorWarning)) + { + diagnostic.Warnings.Add(item); + } } return new ReadResult() From 61fcb9ffc47f0aecd8f299cbd23481080f5411dd Mon Sep 17 00:00:00 2001 From: Millicent Achieng Date: Fri, 9 Sep 2022 00:24:45 +0300 Subject: [PATCH 225/855] Minor updates --- .../OpenApiYamlDocumentReader.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index b26c982fe..37113578a 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -71,11 +71,11 @@ public OpenApiDocument Read(YamlDocument input, out OpenApiDiagnostic diagnostic if (_settings.RuleSet != null && _settings.RuleSet.Rules.Count > 0) { var openApiErrors = document.Validate(_settings.RuleSet); - foreach (var item in openApiErrors.Where(e => e is OpenApiValidatorError)) + foreach (var item in openApiErrors.OfType()) { diagnostic.Errors.Add(item); } - foreach (var item in openApiErrors.Where(e => e is OpenApiValidatorWarning)) + foreach (var item in openApiErrors.OfType()) { diagnostic.Warnings.Add(item); } @@ -115,11 +115,11 @@ public async Task ReadAsync(YamlDocument input) if (_settings.RuleSet != null && _settings.RuleSet.Rules.Count > 0) { var openApiErrors = document.Validate(_settings.RuleSet); - foreach (var item in openApiErrors.Where(e => e is OpenApiValidatorError)) + foreach (var item in openApiErrors.OfType()) { diagnostic.Errors.Add(item); } - foreach (var item in openApiErrors.Where(e => e is OpenApiValidatorWarning)) + foreach (var item in openApiErrors.OfType()) { diagnostic.Warnings.Add(item); } From 6cdceb0e5e3e4ad4daa88b5fc7bc3bfd4ac6e390 Mon Sep 17 00:00:00 2001 From: Millicent Achieng Date: Fri, 9 Sep 2022 16:38:04 +0300 Subject: [PATCH 226/855] Bump the version of the Microsoft.OpenApi.Readers --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 3fdbf2b6d..a3227eac0 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.4.0 + 1.4.1 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET From 307d569ba9073ba1ce792588bdea0ae100bfdd62 Mon Sep 17 00:00:00 2001 From: Irvine Sunday <40403681+irvinesunday@users.noreply.github.com> Date: Mon, 12 Sep 2022 20:24:22 +0300 Subject: [PATCH 227/855] Ensures `Paths` are copied in the copy constructor (#1008) * Ensure paths are copied in the copy constructor * Add test for the copy constructor * Bump up lib. version * Check for nullability * Simplify assignment * Revert to original * Add constructor to the abstract class * Call base constructor * Update publicApi --- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- .../Models/OpenApiDocument.cs | 2 +- .../Models/OpenApiExtensibleDictionary.cs | 18 +++++++++++++++++- src/Microsoft.OpenApi/Models/OpenApiPaths.cs | 4 ++-- .../Models/OpenApiDocumentTests.cs | 14 ++++++++++++++ .../PublicApi/PublicApi.approved.txt | 1 + 6 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index fa8bee8bf..3cac5e0b0 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.1 + 1.4.2 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 836e45dd8..93d88b310 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.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; diff --git a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs index 0a43255fb..40c26d429 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -17,6 +16,23 @@ public abstract class OpenApiExtensibleDictionary : Dictionary, IOpenApiExtensible where T : IOpenApiSerializable { + /// + /// Parameterless constructor + /// + protected OpenApiExtensibleDictionary() { } + + /// + /// Initializes a copy of class. + /// + /// The generic dictionary. + /// The dictionary of . + protected OpenApiExtensibleDictionary( + Dictionary dictionary = null, + IDictionary extensions = null) : base (dictionary) + { + Extensions = extensions != null ? new Dictionary(extensions) : null; + } + /// /// This object MAY be extended with Specification Extensions. /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs index f65ccb9c4..9b48b4908 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs @@ -16,7 +16,7 @@ public OpenApiPaths() {} /// /// Initializes a copy of object /// - public OpenApiPaths(OpenApiPaths paths) {} - + /// The . + public OpenApiPaths(OpenApiPaths paths) : base(dictionary: paths) {} } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index cd4cc2b5a..89289397f 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1342,5 +1342,19 @@ private static OpenApiDocument ParseInputFile(string filePath) return openApiDoc; } + + [Fact] + public void CopyConstructorForAdvancedDocumentWorks() + { + // Arrange & Act + var doc = new OpenApiDocument(AdvancedDocument); + + // Assert + Assert.NotNull(doc.Info); + Assert.NotNull(doc.Servers); + Assert.NotNull(doc.Paths); + Assert.Equal(2, doc.Paths.Count); + Assert.NotNull(doc.Components); + } } } diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 643f2aa5f..15bc8562b 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -581,6 +581,7 @@ namespace Microsoft.OpenApi.Models where T : Microsoft.OpenApi.Interfaces.IOpenApiSerializable { protected OpenApiExtensibleDictionary() { } + protected OpenApiExtensibleDictionary(System.Collections.Generic.Dictionary dictionary = null, System.Collections.Generic.IDictionary extensions = null) { } public System.Collections.Generic.IDictionary Extensions { get; set; } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } From 30af040e1b94adb468868924acfc6a737220f736 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Sep 2022 21:14:54 +0000 Subject: [PATCH 228/855] Bump Microsoft.Extensions.Logging.Abstractions from 6.0.1 to 6.0.2 Bumps [Microsoft.Extensions.Logging.Abstractions](https://github.com/dotnet/runtime) from 6.0.1 to 6.0.2. - [Release notes](https://github.com/dotnet/runtime/releases) - [Commits](https://github.com/dotnet/runtime/compare/v6.0.1...v6.0.2) --- updated-dependencies: - dependency-name: Microsoft.Extensions.Logging.Abstractions dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index eda11732d..1e6b17aa6 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -38,7 +38,7 @@ - + From 758bcc59b504b8b9396ce54fe4c2380748eb1fae Mon Sep 17 00:00:00 2001 From: Irvine Date: Wed, 14 Sep 2022 19:17:00 +0300 Subject: [PATCH 229/855] Bump up lib version and Hidi version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 1e6b17aa6..518892f1d 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview9 + 1.0.0-preview10 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET @@ -43,7 +43,7 @@ - + From fd2b6eb726d28385df7ace0972fb9b00686cec42 Mon Sep 17 00:00:00 2001 From: Irvine Date: Wed, 14 Sep 2022 23:55:38 +0300 Subject: [PATCH 230/855] Update some convert settings --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 461ca50be..034350f1a 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -331,7 +331,9 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl) EnableDerivedTypesReferencesForResponses = false, ShowRootPath = false, ShowLinks = false, - ExpandDerivedTypesNavigationProperties = false + ExpandDerivedTypesNavigationProperties = false, + EnableCount = true, + UseSuccessStatusCodeRange = true }; OpenApiDocument document = edmModel.ConvertToOpenApi(settings); From a389eb6cdae8c250d767eec02b84933209cecc84 Mon Sep 17 00:00:00 2001 From: Alexey Sosnin Date: Mon, 19 Sep 2022 19:27:16 +0300 Subject: [PATCH 231/855] fix: invariant culture for version field Writing version field depends on current system culture version: '1.13.0' for `en-US` version: 1.13.0 for `en-GB` existing workaround: set DOTNET_SYSTEM_GLOBALIZATION_INVARIANT environment variable https://learn.microsoft.com/en-us/dotnet/core/runtime-config/globalization#invariant-mode --- .../SpecialCharacterStringExtensions.cs | 2 +- .../OpenApiWriterSpecialCharacterTests.cs | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs index d4f78a5c1..6e1ea2beb 100644 --- a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs @@ -192,7 +192,7 @@ internal static string GetYamlCompatibleString(this string input) if (decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out var _) || IsHexadecimalNotation(input) || bool.TryParse(input, out var _) || - DateTime.TryParse(input, out var _)) + DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.None, out var _)) { return $"'{input}'"; } diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs index f23cc442a..6ac47d6c3 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs @@ -148,5 +148,26 @@ public void WriteStringWithNewlineCharactersInArrayAsYamlWorks(string input, str // Assert actual.Should().Be(expected); } + + [Theory] + [InlineData("1.8.0", " '1.8.0'", "en-US")] + [InlineData("1.8.0", " '1.8.0'", "en-GB")] + [InlineData("1.13.0", " '1.13.0'", "en-US")] + [InlineData("1.13.0", " '1.13.0'", "en-GB")] + public void WriteStringAsYamlDoesNotDependOnSystemCulture(string input, string expected, string culture) + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + + // Arrange + var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); + var writer = new OpenApiYamlWriter(outputStringWriter); + + // Act + writer.WriteValue(input); + var actual = outputStringWriter.GetStringBuilder().ToString(); + + // Assert + actual.Should().Be(expected); + } } } From f94328c3822dc5e3ac0a69be98cc067a6fc57b8f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 19 Sep 2022 21:11:00 +0000 Subject: [PATCH 232/855] Bump Microsoft.OData.Edm from 7.12.2 to 7.12.3 Bumps Microsoft.OData.Edm from 7.12.2 to 7.12.3. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 518892f1d..beacdddc2 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From efe0fe5102dda8b99032e659cf9d4af2578a07c2 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 20 Sep 2022 08:43:28 -0700 Subject: [PATCH 233/855] - bumps minor for hidi --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index beacdddc2..fbb16de3f 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.0.0-preview10 + 1.1.0-preview1 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET From e6161124fa2510755bf5f5d3819844f9af09d660 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 21 Sep 2022 21:16:59 +0000 Subject: [PATCH 234/855] Bump Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers Bumps [Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers](https://github.com/dotnet/upgrade-assistant) from 0.4.336902 to 0.4.346202. - [Release notes](https://github.com/dotnet/upgrade-assistant/releases) - [Changelog](https://github.com/dotnet/upgrade-assistant/blob/main/CHANGELOG.md) - [Commits](https://github.com/dotnet/upgrade-assistant/commits) --- updated-dependencies: - dependency-name: Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index 326ef4b69..a47b5af48 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -7,7 +7,7 @@ true - + all From 61e878eecbdffe0e1261b6166e09ede495a25d8b Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 26 Sep 2022 13:12:54 +0300 Subject: [PATCH 235/855] Call base constructor for cloning responses object --- src/Microsoft.OpenApi/Models/OpenApiResponses.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs index 24f4eba0d..aa7a8c984 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs @@ -16,7 +16,7 @@ public OpenApiResponses() { } /// /// Initializes a copy of object /// - public OpenApiResponses(OpenApiResponses openApiResponses) { } - + /// The + public OpenApiResponses(OpenApiResponses openApiResponses) : base(dictionary: openApiResponses) {} } } From d87393d2df2f863981d43effd4d86b989c33b9cd Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 26 Sep 2022 13:13:12 +0300 Subject: [PATCH 236/855] Add test case to validate --- .../Models/OpenApiOperationTests.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index 167383b36..368aeb227 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -787,5 +787,16 @@ public void SerializeOperationWithNullCollectionAsV2JsonWorks() expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } + + [Fact] + public void EnsureOpenApiOperationCopyConstructorCopiesResponsesObject() + { + // Arrange and act + var operation = new OpenApiOperation(_operationWithBody); + + // Assert + Assert.NotNull(operation.Responses); + Assert.Equal(2, operation.Responses.Count); + } } } From 194ef814417b7d619ee36107616be8f092ed5f3d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 26 Sep 2022 13:16:27 +0300 Subject: [PATCH 237/855] Bump lib version for release --- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 3cac5e0b0..233d0717e 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.2 + 1.4.3 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 3af819af19571aaa5adfa81b44ce1d70d0af4cdd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Sep 2022 21:08:09 +0000 Subject: [PATCH 238/855] Bump Microsoft.NET.Test.Sdk from 17.3.1 to 17.3.2 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.3.1 to 17.3.2. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v17.3.1...v17.3.2) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 084738bac..d03fda9c0 100644 --- a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 63b7a2a1f..1579f85e5 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -250,7 +250,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 114ba749c..7f41b101f 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -8,7 +8,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 5b476500c..b922d72d8 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -16,7 +16,7 @@ - + From da040f43428d85c0825b43e861aa81f390bfa863 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 3 Oct 2022 10:57:15 +0300 Subject: [PATCH 239/855] Update access modifier --- src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index 840f9c660..d76d06d0f 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Services /// /// This class is used to walk an OpenApiDocument and convert unresolved references to references to populated objects /// - internal class OpenApiReferenceResolver : OpenApiVisitorBase + public class OpenApiReferenceResolver : OpenApiVisitorBase { private OpenApiDocument _currentDocument; private bool _resolveRemoteReferences; From f9fc28f1a3bc783bb1cbe3c46a3a3ddbc3be92d3 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 3 Oct 2022 11:45:18 +0300 Subject: [PATCH 240/855] Update public Api --- .../PublicApi/PublicApi.approved.txt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 15bc8562b..75e12f480 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1067,6 +1067,25 @@ namespace Microsoft.OpenApi.Services public OpenApiReferenceError(Microsoft.OpenApi.Exceptions.OpenApiException exception) { } public OpenApiReferenceError(Microsoft.OpenApi.Models.OpenApiReference reference, string message) { } } + public class OpenApiReferenceResolver : Microsoft.OpenApi.Services.OpenApiVisitorBase + { + public OpenApiReferenceResolver(Microsoft.OpenApi.Models.OpenApiDocument currentDocument, bool resolveRemoteReferences = true) { } + public System.Collections.Generic.IEnumerable Errors { get; } + public override void Visit(Microsoft.OpenApi.Interfaces.IOpenApiReferenceable referenceable) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiComponents components) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiDocument doc) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiMediaType mediaType) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiOperation operation) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiParameter parameter) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiResponses responses) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiSchema schema) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiSecurityRequirement securityRequirement) { } + public override void Visit(System.Collections.Generic.IDictionary callbacks) { } + public override void Visit(System.Collections.Generic.IDictionary examples) { } + public override void Visit(System.Collections.Generic.IDictionary headers) { } + public override void Visit(System.Collections.Generic.IDictionary links) { } + public override void Visit(System.Collections.Generic.IList parameters) { } + } public class OpenApiUrlTreeNode { public System.Collections.Generic.IDictionary> AdditionalData { get; set; } From 485c45c0fe884c5859ae85092b59edef11c51ff8 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 3 Oct 2022 17:42:18 +0300 Subject: [PATCH 241/855] Add XML comments --- .../Services/OpenApiReferenceResolver.cs | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index d76d06d0f..5d7a39113 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -7,7 +7,6 @@ using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; -using Microsoft.OpenApi.Services; namespace Microsoft.OpenApi.Services { @@ -20,20 +19,24 @@ public class OpenApiReferenceResolver : OpenApiVisitorBase private bool _resolveRemoteReferences; private List _errors = new List(); + /// + /// Initializes the class. + /// public OpenApiReferenceResolver(OpenApiDocument currentDocument, bool resolveRemoteReferences = true) { _currentDocument = currentDocument; _resolveRemoteReferences = resolveRemoteReferences; } - public IEnumerable Errors - { - get - { - return _errors; - } - } + /// + /// List of errors related to the OpenApiDocument + /// + public IEnumerable Errors => _errors; + /// + /// Resolves tags in OpenApiDocument + /// + /// public override void Visit(OpenApiDocument doc) { if (doc.Tags != null) @@ -42,6 +45,10 @@ public override void Visit(OpenApiDocument doc) } } + /// + /// Visits the referenceable element in the host document + /// + /// The referenceable element in the doc. public override void Visit(IOpenApiReferenceable referenceable) { if (referenceable.Reference != null) @@ -49,6 +56,11 @@ public override void Visit(IOpenApiReferenceable referenceable) referenceable.Reference.HostDocument = _currentDocument; } } + + /// + /// Resolves references in components + /// + /// public override void Visit(OpenApiComponents components) { ResolveMap(components.Parameters); @@ -62,6 +74,10 @@ public override void Visit(OpenApiComponents components) ResolveMap(components.Headers); } + /// + /// Resolves all references used in callbacks + /// + /// public override void Visit(IDictionary callbacks) { ResolveMap(callbacks); From d1580a3260c78d3e05925acd642350a375f29a2b Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 3 Oct 2022 12:28:09 -0400 Subject: [PATCH 242/855] Update src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs --- src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index 5d7a39113..feeceb9af 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -16,7 +16,7 @@ namespace Microsoft.OpenApi.Services public class OpenApiReferenceResolver : OpenApiVisitorBase { private OpenApiDocument _currentDocument; - private bool _resolveRemoteReferences; + private readonly bool _resolveRemoteReferences; private List _errors = new List(); /// From 224a67d38957dec108ddbe42f57c6023c6256b96 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 21:09:24 +0000 Subject: [PATCH 243/855] Bump actions/setup-dotnet from 2 to 3 Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 2 to 3. - [Release notes](https://github.com/actions/setup-dotnet/releases) - [Commits](https://github.com/actions/setup-dotnet/compare/v2...v3) --- updated-dependencies: - dependency-name: actions/setup-dotnet dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/ci-cd.yml | 2 +- .github/workflows/codeql-analysis.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 8e5cb1f51..b972c9848 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -14,7 +14,7 @@ jobs: GITHUB_RUN_NUMBER: ${{ github.run_number }} steps: - name: Setup .NET - uses: actions/setup-dotnet@v2 + uses: actions/setup-dotnet@v3 with: dotnet-version: 6.0.x diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 8b965b442..eb56ea14f 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -17,7 +17,7 @@ jobs: uses: actions/checkout@v3 - name: Setup .NET - uses: actions/setup-dotnet@v2 + uses: actions/setup-dotnet@v3 with: dotnet-version: 6.0.x From a76d1c964c2949b3b3e0dc3bf0bd08950fb116f8 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 6 Oct 2022 09:16:16 +0300 Subject: [PATCH 244/855] Bump version for preview release --- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 233d0717e..1affa74c6 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.3 + 1.4.4-preview1 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 42ffc779749f7a0d36c96f6532089d704aa2d2d9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 6 Oct 2022 14:22:30 +0300 Subject: [PATCH 245/855] Setting it to 1.4.4-preview1 so that it's consistent with the Object Model library --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index a3227eac0..d21c300eb 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.4.1 + 1.4.4-preview1 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET From 80785a2aedb4a50759817f1f777be5c7e7dbdf38 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 6 Oct 2022 07:31:07 -0400 Subject: [PATCH 246/855] - bumps hidi version and updates reference to conversion lib Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index fbb16de3f..4814ed70b 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.1.0-preview1 + 1.1.0-preview2 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET @@ -43,7 +43,7 @@ - + From d3bf3223f8d7d93d1deaea1225d53f398d4a1918 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 6 Oct 2022 07:33:39 -0400 Subject: [PATCH 247/855] - moves hidi test project to test directory --- Microsoft.OpenApi.sln | 2 +- .../Microsoft.OpenApi.Hidi.Tests.csproj | 0 .../Services/OpenApiFilterServiceTests.cs | 0 .../Services/OpenApiServiceTests.cs | 0 .../UtilityFiles/OpenApiDocumentMock.cs | 0 .../Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/Todo.xml | 0 .../UtilityFiles/postmanCollection_ver1.json | 0 .../UtilityFiles/postmanCollection_ver2.json | 0 .../UtilityFiles/postmanCollection_ver3.json | 0 .../UtilityFiles/postmanCollection_ver4.json | 0 10 files changed, 1 insertion(+), 1 deletion(-) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/Microsoft.OpenApi.Hidi.Tests.csproj (100%) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/Services/OpenApiFilterServiceTests.cs (100%) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/Services/OpenApiServiceTests.cs (100%) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/OpenApiDocumentMock.cs (100%) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/Todo.xml (100%) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/postmanCollection_ver1.json (100%) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/postmanCollection_ver2.json (100%) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/postmanCollection_ver3.json (100%) rename {Microsoft.OpenApi.Hidi.Tests => test/Microsoft.OpenApi.Hidi.Tests}/UtilityFiles/postmanCollection_ver4.json (100%) diff --git a/Microsoft.OpenApi.sln b/Microsoft.OpenApi.sln index 157cb18ff..bb3c028e7 100644 --- a/Microsoft.OpenApi.sln +++ b/Microsoft.OpenApi.sln @@ -28,7 +28,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.OpenApi.SmokeTest EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.OpenApi.Hidi", "src\Microsoft.OpenApi.Hidi\Microsoft.OpenApi.Hidi.csproj", "{254841B5-7DAC-4D1D-A9C5-44FE5CE467BE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.OpenApi.Hidi.Tests", "Microsoft.OpenApi.Hidi.Tests\Microsoft.OpenApi.Hidi.Tests.csproj", "{D8F799DD-04AC-4A13-B344-45A5B944450A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.OpenApi.Hidi.Tests", "test\Microsoft.OpenApi.Hidi.Tests\Microsoft.OpenApi.Hidi.Tests.csproj", "{D8F799DD-04AC-4A13-B344-45A5B944450A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj rename to test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj diff --git a/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs rename to test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs diff --git a/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs rename to test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs diff --git a/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs rename to test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs diff --git a/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/Todo.xml b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/Todo.xml similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/UtilityFiles/Todo.xml rename to test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/Todo.xml diff --git a/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver1.json b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver1.json similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver1.json rename to test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver1.json diff --git a/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver2.json b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver2.json similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver2.json rename to test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver2.json diff --git a/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver3.json b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver3.json similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver3.json rename to test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver3.json diff --git a/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver4.json b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver4.json similarity index 100% rename from Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver4.json rename to test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/postmanCollection_ver4.json From b1b68f56a77c24ab9068eac2aad19c1815781669 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 6 Oct 2022 15:27:43 +0300 Subject: [PATCH 248/855] Insert null check validation when response header does not contain any schema during V2 deserialization --- .../V2/OpenApiHeaderDeserializer.cs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs index 32caf86aa..5d6cc2ff3 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.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; @@ -139,8 +139,12 @@ internal static partial class OpenApiV2Deserializer { OpenApiConstants.Default, new AnyFieldMapParameter( - p => p.Schema.Default, - (p, v) => p.Schema.Default = v, + p => p.Schema?.Default, + (p, v) => + { + if(p.Schema == null) return; + p.Schema.Default = v; + }, p => p.Schema) } }; @@ -151,8 +155,12 @@ internal static partial class OpenApiV2Deserializer { OpenApiConstants.Enum, new AnyListFieldMapParameter( - p => p.Schema.Enum, - (p, v) => p.Schema.Enum = v, + p => p.Schema?.Enum, + (p, v) => + { + if(p.Schema == null) return; + p.Schema.Enum = v; + }, p => p.Schema) }, }; From bdced92aee7d9d6fc7953fd2c7622fdd06e7dcaa Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 6 Oct 2022 10:23:45 -0400 Subject: [PATCH 249/855] - bumps odata to latest --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 4814ed70b..55d529a06 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From ed740c894292db202ff18be240a2cbacfe5aabc1 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 6 Oct 2022 11:04:07 -0400 Subject: [PATCH 250/855] - fixes references to projects in tests projects --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index d03fda9c0..1a4002daa 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -23,8 +23,8 @@ - - + + From 76321be060729713bb5534ebc0665b94cce401f4 Mon Sep 17 00:00:00 2001 From: Millicent Achieng Date: Thu, 6 Oct 2022 19:49:13 +0300 Subject: [PATCH 251/855] Fix $ref serialization errors for requestBodies and responses (#1033) * Do not add empty consumes array if RequestBody content contains no elements * Add requestbody references as parameter references in v2 serialization * Add consumes and produces properties when we have reference request bodies and responses respectively during v2 serialization * Update src/Microsoft.OpenApi/Models/OpenApiOperation.cs Co-authored-by: Vincent Biret * Apply suggestions from code review Co-authored-by: Vincent Biret * Address code review comments Co-authored-by: Vincent Biret --- .../Models/OpenApiDocument.cs | 15 +++- .../Models/OpenApiOperation.cs | 88 ++++++++----------- .../Models/OpenApiReference.cs | 34 +++---- .../Models/OpenApiRequestBody.cs | 47 ++++++++++ 4 files changed, 108 insertions(+), 76 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 93d88b310..5177e4f45 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -160,7 +160,7 @@ public void SerializeAsV2(IOpenApiWriter writer) // paths writer.WriteRequiredObject(OpenApiConstants.Paths, Paths, (w, p) => p.SerializeAsV2(w)); - // If references have been inlined we don't need the to render the components section + // If references have been inlined we don't need to render the components section // however if they have cycles, then we will need a component rendered if (writer.GetSettings().InlineLocalReferences) { @@ -208,9 +208,20 @@ public void SerializeAsV2(IOpenApiWriter writer) }); } // parameters + var parameters = Components?.Parameters != null + ? new Dictionary(Components.Parameters) + : new Dictionary(); + + if (Components?.RequestBodies != null) + { + foreach (var requestBody in Components.RequestBodies.Where(b => !parameters.ContainsKey(b.Key))) + { + parameters.Add(requestBody.Key, requestBody.Value.ConvertToBodyParameter()); + } + } writer.WriteOptionalMap( OpenApiConstants.Parameters, - Components?.Parameters, + parameters, (w, key, component) => { if (component.Reference != null && diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 7983a243e..d047b9cb6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -224,7 +224,7 @@ public void SerializeAsV2(IOpenApiWriter writer) // operationId writer.WriteProperty(OpenApiConstants.OperationId, OperationId); - IList parameters; + List parameters; if (Parameters == null) { parameters = new List(); @@ -237,70 +237,58 @@ public void SerializeAsV2(IOpenApiWriter writer) if (RequestBody != null) { // consumes - writer.WritePropertyName(OpenApiConstants.Consumes); - writer.WriteStartArray(); var consumes = RequestBody.Content.Keys.Distinct().ToList(); - foreach (var mediaType in consumes) + if (consumes.Any()) { - writer.WriteValue(mediaType); - } - - writer.WriteEndArray(); - - // This is form data. We need to split the request body into multiple parameters. - if (consumes.Contains("application/x-www-form-urlencoded") || - consumes.Contains("multipart/form-data")) - { - foreach (var property in RequestBody.Content.First().Value.Schema.Properties) + // This is form data. We need to split the request body into multiple parameters. + if (consumes.Contains("application/x-www-form-urlencoded") || + consumes.Contains("multipart/form-data")) { - var paramSchema = property.Value; - if ("string".Equals(paramSchema.Type, StringComparison.OrdinalIgnoreCase) - && ("binary".Equals(paramSchema.Format, StringComparison.OrdinalIgnoreCase) - || "base64".Equals(paramSchema.Format, StringComparison.OrdinalIgnoreCase))) - { - paramSchema.Type = "file"; - paramSchema.Format = null; - } - parameters.Add( - new OpenApiFormDataParameter - { - Description = property.Value.Description, - Name = property.Key, - Schema = property.Value, - Required = RequestBody.Content.First().Value.Schema.Required.Contains(property.Key) - - }); + parameters.AddRange(RequestBody.ConvertToFormDataParameters()); + } + else + { + parameters.Add(RequestBody.ConvertToBodyParameter()); } } - else + else if (RequestBody.Reference != null) { - var content = RequestBody.Content.Values.FirstOrDefault(); + parameters.Add( + new OpenApiParameter + { + UnresolvedReference = true, + Reference = RequestBody.Reference + }); - var bodyParameter = new OpenApiBodyParameter + if (RequestBody.Reference.HostDocument != null) { - Description = RequestBody.Description, - // V2 spec actually allows the body to have custom name. - // To allow round-tripping we use an extension to hold the name - Name = "body", - Schema = content?.Schema ?? new OpenApiSchema(), - Required = RequestBody.Required, - Extensions = RequestBody.Extensions.ToDictionary(k => k.Key, v => v.Value) // Clone extensions so we can remove the x-bodyName extensions from the output V2 model. - }; - - if (bodyParameter.Extensions.ContainsKey(OpenApiConstants.BodyName)) + var effectiveRequestBody = RequestBody.GetEffective(RequestBody.Reference.HostDocument); + if (effectiveRequestBody != null) + consumes = effectiveRequestBody.Content.Keys.Distinct().ToList(); + } + } + + if (consumes.Any()) + { + writer.WritePropertyName(OpenApiConstants.Consumes); + writer.WriteStartArray(); + foreach (var mediaType in consumes) { - bodyParameter.Name = (RequestBody.Extensions[OpenApiConstants.BodyName] as OpenApiString)?.Value ?? "body"; - bodyParameter.Extensions.Remove(OpenApiConstants.BodyName); + writer.WriteValue(mediaType); } - - parameters.Add(bodyParameter); + writer.WriteEndArray(); } } if (Responses != null) { - var produces = Responses.Where(r => r.Value.Content != null) - .SelectMany(r => r.Value.Content?.Keys) + var produces = Responses + .Where(static r => r.Value.Content != null) + .SelectMany(static r => r.Value.Content?.Keys) + .Concat( + Responses + .Where(static r => r.Value.Reference != null && r.Value.Reference.HostDocument != null) + .SelectMany(static r => r.Value.GetEffective(r.Value.Reference.HostDocument)?.Content?.Keys)) .Distinct() .ToList(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index 31cc5a6e8..ecc643dc3 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -214,31 +214,17 @@ private string GetExternalReferenceV2() private string GetReferenceTypeNameAsV2(ReferenceType type) { - switch (type) + return type switch { - case ReferenceType.Schema: - return OpenApiConstants.Definitions; - - case ReferenceType.Parameter: - return OpenApiConstants.Parameters; - - case ReferenceType.Response: - return OpenApiConstants.Responses; - - case ReferenceType.Header: - return OpenApiConstants.Headers; - - case ReferenceType.Tag: - return OpenApiConstants.Tags; - - case ReferenceType.SecurityScheme: - return OpenApiConstants.SecurityDefinitions; - - default: - // If the reference type is not supported in V2, simply return null - // to indicate that the reference is not pointing to any object. - return null; - } + ReferenceType.Schema => OpenApiConstants.Definitions, + ReferenceType.Parameter or ReferenceType.RequestBody => OpenApiConstants.Parameters, + ReferenceType.Response => OpenApiConstants.Responses, + ReferenceType.Header => OpenApiConstants.Headers, + ReferenceType.Tag => OpenApiConstants.Tags, + ReferenceType.SecurityScheme => OpenApiConstants.SecurityDefinitions, + _ => null,// If the reference type is not supported in V2, simply return null + // to indicate that the reference is not pointing to any object. + }; } } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 9016fd7a3..70f1f742a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -1,7 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Collections.Generic; +using System.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -144,5 +146,50 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) { // RequestBody object does not exist in V2. } + + internal OpenApiBodyParameter ConvertToBodyParameter() + { + var bodyParameter = new OpenApiBodyParameter + { + Description = Description, + // V2 spec actually allows the body to have custom name. + // To allow round-tripping we use an extension to hold the name + Name = "body", + Schema = Content.Values.FirstOrDefault()?.Schema ?? new OpenApiSchema(), + Required = Required, + Extensions = Extensions.ToDictionary(static k => k.Key, static v => v.Value) // Clone extensions so we can remove the x-bodyName extensions from the output V2 model. + }; + if (bodyParameter.Extensions.ContainsKey(OpenApiConstants.BodyName)) + { + bodyParameter.Name = (Extensions[OpenApiConstants.BodyName] as OpenApiString)?.Value ?? "body"; + bodyParameter.Extensions.Remove(OpenApiConstants.BodyName); + } + return bodyParameter; + } + + internal IEnumerable ConvertToFormDataParameters() + { + if (Content == null || !Content.Any()) + yield break; + + foreach (var property in Content.First().Value.Schema.Properties) + { + var paramSchema = property.Value; + if ("string".Equals(paramSchema.Type, StringComparison.OrdinalIgnoreCase) + && ("binary".Equals(paramSchema.Format, StringComparison.OrdinalIgnoreCase) + || "base64".Equals(paramSchema.Format, StringComparison.OrdinalIgnoreCase))) + { + paramSchema.Type = "file"; + paramSchema.Format = null; + } + yield return new OpenApiFormDataParameter + { + Description = property.Value.Description, + Name = property.Key, + Schema = property.Value, + Required = Content.First().Value.Schema.Required.Contains(property.Key) + }; + } + } } } From b0ebad0a9ce72327d90f4d80f90f229136df37a2 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Fri, 7 Oct 2022 12:15:34 -0400 Subject: [PATCH 252/855] - renames hidi in accordance to naming policy of MCR Signed-off-by: Vincent Biret --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index ec86e0b7f..ad7cdc562 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -6,7 +6,7 @@ on: paths: ['src/Microsoft.OpenApi.Hidi/**', '.github/workflows/**'] env: REGISTRY: msgraphprod.azurecr.io - IMAGE_NAME: public/hidi + IMAGE_NAME: public/openapi/hidi jobs: push_to_registry: environment: From b46242975cc300a6e075bbd7209127a9685c85d6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Oct 2022 21:05:22 +0000 Subject: [PATCH 253/855] Bump docker/login-action from 2.0.0 to 2.1.0 Bumps [docker/login-action](https://github.com/docker/login-action) from 2.0.0 to 2.1.0. - [Release notes](https://github.com/docker/login-action/releases) - [Commits](https://github.com/docker/login-action/compare/v2.0.0...v2.1.0) --- updated-dependencies: - dependency-name: docker/login-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index ec86e0b7f..b9ebfbdb1 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -17,7 +17,7 @@ jobs: - name: Check out the repo uses: actions/checkout@v3 - name: Login to GitHub package feed - uses: docker/login-action@v2.0.0 + uses: docker/login-action@v2.1.0 with: username: ${{ secrets.ACR_USERNAME }} password: ${{ secrets.ACR_PASSWORD }} From 5cd548d400ad1fbb614fc3aef4681665a98d07ca Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Oct 2022 21:05:25 +0000 Subject: [PATCH 254/855] Bump docker/build-push-action from 3.1.1 to 3.2.0 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3.1.1 to 3.2.0. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v3.1.1...v3.2.0) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index ec86e0b7f..1a14c1893 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -30,13 +30,13 @@ jobs: id: getversion - name: Push to GitHub Packages - Nightly if: ${{ github.ref == 'refs/heads/vnext' }} - uses: docker/build-push-action@v3.1.1 + uses: docker/build-push-action@v3.2.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly - name: Push to GitHub Packages - Release if: ${{ github.ref == 'refs/heads/master' }} - uses: docker/build-push-action@v3.1.1 + uses: docker/build-push-action@v3.2.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest,${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.getversion.outputs.version }} From 9d23f18f914ceff80c3aad9aa26593f5469bdccb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 19 Oct 2022 09:20:39 +0300 Subject: [PATCH 255/855] Bump Microsoft.OData.Edm from 7.12.3 to 7.12.4 (#1043) Bumps Microsoft.OData.Edm from 7.12.3 to 7.12.4. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 55d529a06..cbff7e937 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From 3ec0849cd0497b9b72e0c7884bd71b7295d6e520 Mon Sep 17 00:00:00 2001 From: Irvine Date: Mon, 24 Oct 2022 15:29:16 +0300 Subject: [PATCH 256/855] Upgrade conversion lib. ver.; update Hidi version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index cbff7e937..c77e30194 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.1.0-preview2 + 1.1.0-preview3 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET @@ -43,7 +43,7 @@ - + From dc179d382fd8aa54fac8268786500ee23ea2505a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Oct 2022 21:12:21 +0000 Subject: [PATCH 257/855] Bump Verify.Xunit from 17.10.2 to 18.0.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 17.10.2 to 18.0.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/17.10.2...18.0.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index b922d72d8..b243c5dd7 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From b48da170930ddf12a48b7aff550990afe7c9d4c8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Oct 2022 21:12:27 +0000 Subject: [PATCH 258/855] Bump FluentAssertions from 6.7.0 to 6.8.0 Bumps [FluentAssertions](https://github.com/fluentassertions/fluentassertions) from 6.7.0 to 6.8.0. - [Release notes](https://github.com/fluentassertions/fluentassertions/releases) - [Changelog](https://github.com/fluentassertions/fluentassertions/blob/develop/AcceptApiChanges.ps1) - [Commits](https://github.com/fluentassertions/fluentassertions/compare/6.7.0...6.8.0) --- updated-dependencies: - dependency-name: FluentAssertions dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 1579f85e5..1c46de041 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -251,7 +251,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index b922d72d8..dc375ae89 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,7 +15,7 @@ - + From 168a58b1fcd4749d6603938f2538c3bee880946f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 25 Oct 2022 21:12:12 +0000 Subject: [PATCH 259/855] Bump Microsoft.OData.Edm from 7.12.4 to 7.12.5 Bumps Microsoft.OData.Edm from 7.12.4 to 7.12.5. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index c77e30194..37c7d3b42 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From 93d9108d0400d0278a0bae83fbafb14d9ff2577a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 28 Oct 2022 21:10:37 +0000 Subject: [PATCH 260/855] Bump Verify.Xunit from 18.0.0 to 18.1.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 18.0.0 to 18.1.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/18.0.0...18.1.1) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index d1f97f6f3..79beda1ad 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From aa87e77c140c382c844a99417bc7c1e0af7e157b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 28 Oct 2022 21:10:43 +0000 Subject: [PATCH 261/855] Bump Microsoft.Windows.Compatibility from 6.0.0 to 6.0.1 Bumps [Microsoft.Windows.Compatibility](https://github.com/dotnet/runtime) from 6.0.0 to 6.0.1. - [Release notes](https://github.com/dotnet/runtime/releases) - [Commits](https://github.com/dotnet/runtime/compare/v6.0.0...v6.0.1) --- updated-dependencies: - dependency-name: Microsoft.Windows.Compatibility dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index a47b5af48..6b83bdbca 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -10,7 +10,7 @@ all - + From 807dc2f98c26991234420213aaec462a4a139755 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 31 Oct 2022 21:05:58 +0000 Subject: [PATCH 262/855] Bump mathieudutour/github-tag-action from 6.0 to 6.1 Bumps [mathieudutour/github-tag-action](https://github.com/mathieudutour/github-tag-action) from 6.0 to 6.1. - [Release notes](https://github.com/mathieudutour/github-tag-action/releases) - [Commits](https://github.com/mathieudutour/github-tag-action/compare/v6.0...v6.1) --- updated-dependencies: - dependency-name: mathieudutour/github-tag-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/ci-cd.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index b972c9848..b394e018b 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -49,7 +49,7 @@ jobs: - if: steps.conditionals_handler.outputs.is_default_branch == 'true' name: Bump GH tag id: tag_generator - uses: mathieudutour/github-tag-action@v6.0 + uses: mathieudutour/github-tag-action@v6.1 with: github_token: ${{ secrets.GITHUB_TOKEN }} default_bump: false From b89ebc28b4613e4724c87acafd3209212c878ae7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 31 Oct 2022 21:12:01 +0000 Subject: [PATCH 263/855] Bump coverlet.collector from 3.1.2 to 3.2.0 Bumps [coverlet.collector](https://github.com/coverlet-coverage/coverlet) from 3.1.2 to 3.2.0. - [Release notes](https://github.com/coverlet-coverage/coverlet/releases) - [Commits](https://github.com/coverlet-coverage/coverlet/commits/v3.2.0) --- updated-dependencies: - dependency-name: coverlet.collector dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 1a4002daa..2c53d82da 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -16,7 +16,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + runtime; build; native; contentfiles; analyzers; buildtransitive all From 5429810a87def5416b94a2d9620fa7d1b9bb0a30 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 31 Oct 2022 21:12:08 +0000 Subject: [PATCH 264/855] Bump Verify.Xunit from 18.1.1 to 18.2.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 18.1.1 to 18.2.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/18.1.1...18.2.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 79beda1ad..251fe1a4b 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 236a8873938bf56f372ca9510645221ea7b25179 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Nov 2022 21:11:27 +0000 Subject: [PATCH 265/855] Bump Microsoft.OpenApi.OData from 1.2.0-preview5 to 1.2.0-preview6 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.2.0-preview5 to 1.2.0-preview6. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 37c7d3b42..e133b37cf 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 05a1fd8ee3f6eb011d92d0f02931b2bbdc2e0ee7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Nov 2022 21:11:32 +0000 Subject: [PATCH 266/855] Bump Verify.Xunit from 18.2.0 to 18.3.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 18.2.0 to 18.3.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/18.2.0...18.3.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 251fe1a4b..33dd48253 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 2b13d3f71f049df68fa0432e212f4c9ad3e683c1 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 3 Nov 2022 12:35:53 +0300 Subject: [PATCH 267/855] Remove return statement to eliminate NullReference exception --- src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 40b40e85a..1e729f30a 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -105,7 +105,6 @@ public OpenApiReference ConvertToOpenApiReference( catch (OpenApiException ex) { Diagnostic.Errors.Add(new OpenApiError(ex)); - return null; } } // Where fragments point into a non-OpenAPI document, the id will be the complete fragment identifier From e210137335bc20027df5ac7b111c396fef2c1fd6 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 7 Nov 2022 11:30:04 +0300 Subject: [PATCH 268/855] Add a settingsFile parameter that allows one to input a path to the settingsfile --- .../Handlers/TransformCommandHandler.cs | 4 +- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 57 ++++++++++--------- src/Microsoft.OpenApi.Hidi/Program.cs | 5 ++ 3 files changed, 38 insertions(+), 28 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index e8d9431de..696837d3f 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -21,6 +21,7 @@ internal class TransformCommandHandler : ICommandHandler public Option VersionOption { get; set; } public Option FormatOption { get; set; } public Option TerseOutputOption { get; set; } + public Option SettingsFileOption { get; set; } public Option LogLevelOption { get; set; } public Option FilterByOperationIdsOption { get; set; } public Option FilterByTagsOption { get; set; } @@ -42,6 +43,7 @@ public async Task InvokeAsync(InvocationContext context) string? version = context.ParseResult.GetValueForOption(VersionOption); OpenApiFormat? format = context.ParseResult.GetValueForOption(FormatOption); bool terseOutput = context.ParseResult.GetValueForOption(TerseOutputOption); + string settingsFile = context.ParseResult.GetValueForOption(SettingsFileOption); LogLevel logLevel = context.ParseResult.GetValueForOption(LogLevelOption); bool inlineLocal = context.ParseResult.GetValueForOption(InlineLocalOption); bool inlineExternal = context.ParseResult.GetValueForOption(InlineExternalOption); @@ -54,7 +56,7 @@ public async Task InvokeAsync(InvocationContext context) var logger = loggerFactory.CreateLogger(); try { - await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, logLevel, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, cancellationToken); + await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, settingsFile, logLevel, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, cancellationToken); return 0; } diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index e6603d62d..488db08cf 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -45,6 +45,7 @@ public static async Task TransformOpenApiDocument( string? version, OpenApiFormat? format, bool terseOutput, + string settingsFile, LogLevel logLevel, bool inlineLocal, bool inlineExternal, @@ -100,7 +101,7 @@ CancellationToken cancellationToken stream.Position = 0; } - document = await ConvertCsdlToOpenApi(stream); + document = await ConvertCsdlToOpenApi(stream, settingsFile); stopwatch.Stop(); logger.LogTrace("{timestamp}ms: Generated OpenAPI with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); } @@ -306,11 +307,14 @@ public static async Task ValidateOpenApiDocument( } } - internal static IConfiguration GetConfiguration() + public static IConfiguration GetConfiguration(string settingsFile) { + settingsFile ??= "appsettings.json"; + IConfiguration config = new ConfigurationBuilder() - .AddJsonFile("appsettings.json",true) + .AddJsonFile(settingsFile, true) .Build(); + return config; } @@ -319,37 +323,36 @@ internal static IConfiguration GetConfiguration() /// /// The CSDL stream. /// An OpenAPI document. - public static async Task ConvertCsdlToOpenApi(Stream csdl) + public static async Task ConvertCsdlToOpenApi(Stream csdl, string settingsFile = null) { using var reader = new StreamReader(csdl); var csdlText = await reader.ReadToEndAsync(); var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader()); + + var config = GetConfiguration(settingsFile); + var settings = config.GetSection("OpenApiConvertSettings").Get(); - var config = GetConfiguration(); - OpenApiConvertSettings settings = config.GetSection("OpenApiConvertSettings").Get(); - if (settings == null) - { - settings = new OpenApiConvertSettings() + settings ??= new OpenApiConvertSettings() { - AddSingleQuotesForStringParameters = true, - AddEnumDescriptionExtension = true, - DeclarePathParametersOnPathItem = true, - EnableKeyAsSegment = true, - EnableOperationId = true, - ErrorResponsesAsDefault = false, - PrefixEntityTypeNameBeforeKey = true, - TagDepth = 2, - EnablePagination = true, - EnableDiscriminatorValue = true, - EnableDerivedTypesReferencesForRequestBody = false, - EnableDerivedTypesReferencesForResponses = false, - ShowRootPath = false, - ShowLinks = false, - ExpandDerivedTypesNavigationProperties = false, - EnableCount = true, - UseSuccessStatusCodeRange = true + AddSingleQuotesForStringParameters = true, + AddEnumDescriptionExtension = true, + DeclarePathParametersOnPathItem = true, + EnableKeyAsSegment = true, + EnableOperationId = true, + ErrorResponsesAsDefault = false, + PrefixEntityTypeNameBeforeKey = true, + TagDepth = 2, + EnablePagination = true, + EnableDiscriminatorValue = true, + EnableDerivedTypesReferencesForRequestBody = false, + EnableDerivedTypesReferencesForResponses = false, + ShowRootPath = false, + ShowLinks = false, + ExpandDerivedTypesNavigationProperties = false, + EnableCount = true, + UseSuccessStatusCodeRange = true }; - } + OpenApiDocument document = edmModel.ConvertToOpenApi(settings); document = FixReferences(document); diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 67f4c2974..3af6818da 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -47,6 +47,9 @@ static async Task Main(string[] args) var terseOutputOption = new Option("--terse-output", "Produce terse json output"); terseOutputOption.AddAlias("--to"); + var settingsFileOption = new Option("--settingsFile", "The configuration file with CSDL conversion settings."); + settingsFileOption.AddAlias("--sf"); + var logLevelOption = new Option("--log-level", () => LogLevel.Information, "The log level to use when logging messages to the main output."); logLevelOption.AddAlias("--ll"); @@ -87,6 +90,7 @@ static async Task Main(string[] args) versionOption, formatOption, terseOutputOption, + settingsFileOption, logLevelOption, filterByOperationIdsOption, filterByTagsOption, @@ -105,6 +109,7 @@ static async Task Main(string[] args) VersionOption = versionOption, FormatOption = formatOption, TerseOutputOption = terseOutputOption, + SettingsFileOption = settingsFileOption, LogLevelOption = logLevelOption, FilterByOperationIdsOption = filterByOperationIdsOption, FilterByTagsOption = filterByTagsOption, From 67586ec6b99730d4de4883e5295112c3142f5faf Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 7 Nov 2022 11:31:03 +0300 Subject: [PATCH 269/855] Add test --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 3 +++ .../Services/OpenApiServiceTests.cs | 16 ++++++++++++++++ .../Services/appsettingstest.json | 7 +++++++ 3 files changed, 26 insertions(+) create mode 100644 test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 2c53d82da..39fa1d87b 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -34,6 +34,9 @@ + + Always + Always diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index af5437aa1..aed9e4889 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -4,7 +4,9 @@ using System; using System.IO; using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; using Microsoft.OpenApi.Hidi; +using Microsoft.OpenApi.OData; using Microsoft.OpenApi.Services; using Xunit; @@ -51,5 +53,19 @@ public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocumen Assert.NotEmpty(subsetOpenApiDocument.Paths); Assert.Equal(expectedPathCount, subsetOpenApiDocument.Paths.Count); } + + [Fact] + public void ReturnOpenApiConvertSettings() + { + // Arrange + var filePath = "C:\\Users\\v-makim\\source\\repos\\OpenAPI.NET\\test\\Microsoft.OpenApi.Hidi.Tests\\Services\\appsettingstest.json"; + var config = OpenApiService.GetConfiguration(filePath); + + // Act + var settings = config.GetSection("OpenApiConvertSettings").Get(); + + // Assert + Assert.NotNull(settings); + } } } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json b/test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json new file mode 100644 index 000000000..2effcaced --- /dev/null +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json @@ -0,0 +1,7 @@ +{ + "OpenApiConvertSettings": { + "AddSingleQuotesForStringParameters": "true", + "AddEnumDescriptionExtension": "true", + "DeclarePathParametersOnPathItem": "true" + } +} \ No newline at end of file From 6f0bf136194bdc0d422a6abe4d34f9efd95ebe7f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 7 Nov 2022 13:04:04 +0300 Subject: [PATCH 270/855] Use backslash in filePath --- .../Services/OpenApiServiceTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index aed9e4889..68fefe088 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -58,7 +58,7 @@ public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocumen public void ReturnOpenApiConvertSettings() { // Arrange - var filePath = "C:\\Users\\v-makim\\source\\repos\\OpenAPI.NET\\test\\Microsoft.OpenApi.Hidi.Tests\\Services\\appsettingstest.json"; + var filePath = "C:/Users/v-makim/source/repos/OpenAPI.NET/test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json"; var config = OpenApiService.GetConfiguration(filePath); // Act From 568cf91a855480a67e8583a9a399b3995c0c1257 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 7 Nov 2022 14:33:37 +0300 Subject: [PATCH 271/855] Clean up tests --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Services/OpenApiServiceTests.cs | 2 +- .../Services/appsettingstest.json | 7 ------- .../UtilityFiles/appsettingstest.json | 21 +++++++++++++++++++ 4 files changed, 23 insertions(+), 9 deletions(-) delete mode 100644 test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json create mode 100644 test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/appsettingstest.json diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 39fa1d87b..9bc2e7849 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -34,7 +34,7 @@ - + Always diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 68fefe088..44d0740be 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -58,7 +58,7 @@ public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocumen public void ReturnOpenApiConvertSettings() { // Arrange - var filePath = "C:/Users/v-makim/source/repos/OpenAPI.NET/test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json"; + var filePath = "C:/Users/v-makim/source/repos/OpenAPI.NET/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/appsettingstest.json"; var config = OpenApiService.GetConfiguration(filePath); // Act diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json b/test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json deleted file mode 100644 index 2effcaced..000000000 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/appsettingstest.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "OpenApiConvertSettings": { - "AddSingleQuotesForStringParameters": "true", - "AddEnumDescriptionExtension": "true", - "DeclarePathParametersOnPathItem": "true" - } -} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/appsettingstest.json b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/appsettingstest.json new file mode 100644 index 000000000..a71d0a9fa --- /dev/null +++ b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/appsettingstest.json @@ -0,0 +1,21 @@ +{ + "OpenApiConvertSettings": { + "AddSingleQuotesForStringParameters": "true", + "AddEnumDescriptionExtension": "true", + "DeclarePathParametersOnPathItem": "true", + "EnableKeyAsSegment": "true", + "EnableOperationId": "true", + "ErrorResponsesAsDefault": "false", + "PrefixEntityTypeNameBeforeKey": "true", + "TagDepth": 2, + "EnablePagination": "true", + "EnableDiscriminatorValue": "true", + "EnableDerivedTypesReferencesForRequestBody": "false", + "EnableDerivedTypesReferencesForResponses": "false", + "ShowRootPath": "false", + "ShowLinks": "false", + "ExpandDerivedTypesNavigationProperties": "false", + "EnableCount": "true", + "UseSuccessStatusCodeRange": "true" + } +} \ No newline at end of file From efd2ac871cae2f87a19b33118a7f1c708b5acc0f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Nov 2022 21:10:40 +0000 Subject: [PATCH 272/855] Bump Microsoft.Windows.Compatibility from 6.0.1 to 7.0.0 Bumps [Microsoft.Windows.Compatibility](https://github.com/dotnet/runtime) from 6.0.1 to 7.0.0. - [Release notes](https://github.com/dotnet/runtime/releases) - [Commits](https://github.com/dotnet/runtime/commits) --- updated-dependencies: - dependency-name: Microsoft.Windows.Compatibility dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index 6b83bdbca..cf3ff2225 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -10,7 +10,7 @@ all - + From 4f949113ef78c3e2252322bc181cf9abaf42e768 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Nov 2022 21:10:46 +0000 Subject: [PATCH 273/855] Bump Microsoft.NET.Test.Sdk from 17.3.2 to 17.4.0 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.3.2 to 17.4.0. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v17.3.2...v17.4.0) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 2c53d82da..f4c368024 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 1c46de041..2e73118b2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -250,7 +250,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 7f41b101f..bb1cf129d 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -8,7 +8,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 33dd48253..3ee1f6322 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -16,7 +16,7 @@ - + From f5e3b2e1d443909bcecd0673384e7173bc876bc5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Nov 2022 21:10:53 +0000 Subject: [PATCH 274/855] Bump Verify.Xunit from 18.3.0 to 18.4.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 18.3.0 to 18.4.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/18.3.0...18.4.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 33dd48253..49be5986c 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 2bde9e8f799b9f57e5a71074bf325519198c1d7c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Nov 2022 21:10:59 +0000 Subject: [PATCH 275/855] Bump Microsoft.Extensions.Logging.Abstractions from 6.0.2 to 7.0.0 Bumps [Microsoft.Extensions.Logging.Abstractions](https://github.com/dotnet/runtime) from 6.0.2 to 7.0.0. - [Release notes](https://github.com/dotnet/runtime/releases) - [Commits](https://github.com/dotnet/runtime/commits) --- updated-dependencies: - dependency-name: Microsoft.Extensions.Logging.Abstractions dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index e133b37cf..e11d1c315 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -38,7 +38,7 @@ - + From a4bbda0a8a9fef9ac087795f7bf371103a9e0b0f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Nov 2022 21:51:07 +0000 Subject: [PATCH 276/855] Bump Microsoft.Extensions.Logging from 6.0.0 to 7.0.0 Bumps [Microsoft.Extensions.Logging](https://github.com/dotnet/runtime) from 6.0.0 to 7.0.0. - [Release notes](https://github.com/dotnet/runtime/releases) - [Commits](https://github.com/dotnet/runtime/commits) --- updated-dependencies: - dependency-name: Microsoft.Extensions.Logging dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index e11d1c315..c19926e38 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -37,7 +37,7 @@ - + From 4e81b9b1d9d2d825b5b338ab4c33a65a843b4dda Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Nov 2022 22:05:56 +0000 Subject: [PATCH 277/855] Bump Microsoft.Extensions.Logging.Console from 6.0.0 to 7.0.0 Bumps [Microsoft.Extensions.Logging.Console](https://github.com/dotnet/runtime) from 6.0.0 to 7.0.0. - [Release notes](https://github.com/dotnet/runtime/releases) - [Commits](https://github.com/dotnet/runtime/commits) --- updated-dependencies: - dependency-name: Microsoft.Extensions.Logging.Console dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index c19926e38..c884e91fe 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -39,7 +39,7 @@ - + From a54c8f9b38c6378cd8876d6d0faa426573688d18 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Nov 2022 22:17:37 +0000 Subject: [PATCH 278/855] Bump Microsoft.Extensions.Logging.Debug from 6.0.0 to 7.0.0 Bumps [Microsoft.Extensions.Logging.Debug](https://github.com/dotnet/runtime) from 6.0.0 to 7.0.0. - [Release notes](https://github.com/dotnet/runtime/releases) - [Commits](https://github.com/dotnet/runtime/commits) --- updated-dependencies: - dependency-name: Microsoft.Extensions.Logging.Debug dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index c884e91fe..6c9b54e04 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -40,7 +40,7 @@ - + From ec05eca67e7096e30f5e1330c04b3e2b1bad592a Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 8 Nov 2022 12:45:30 +0300 Subject: [PATCH 279/855] Address PR feedback --- .../Microsoft.OpenApi.Hidi.csproj | 8 ++++ src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 48 +++++++++---------- src/Microsoft.OpenApi.Hidi/Program.cs | 15 +----- .../Services/OpenApiServiceTests.cs | 24 ++++++---- 4 files changed, 48 insertions(+), 47 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 0e7abdbdb..c2071f810 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -52,4 +52,12 @@ + + + + <_Parameter1>Microsoft.OpenApi.Hidi.Tests + + + + diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 488db08cf..0d9500682 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -28,6 +28,7 @@ using System.Xml; using System.Reflection; using Microsoft.Extensions.Configuration; +using System.Runtime.CompilerServices; namespace Microsoft.OpenApi.Hidi { @@ -307,7 +308,7 @@ public static async Task ValidateOpenApiDocument( } } - public static IConfiguration GetConfiguration(string settingsFile) + internal static IConfiguration GetConfiguration(string settingsFile) { settingsFile ??= "appsettings.json"; @@ -317,7 +318,7 @@ public static IConfiguration GetConfiguration(string settingsFile) return config; } - + /// /// Converts CSDL to OpenAPI /// @@ -330,28 +331,27 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl, stri var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader()); var config = GetConfiguration(settingsFile); - var settings = config.GetSection("OpenApiConvertSettings").Get(); - - settings ??= new OpenApiConvertSettings() - { - AddSingleQuotesForStringParameters = true, - AddEnumDescriptionExtension = true, - DeclarePathParametersOnPathItem = true, - EnableKeyAsSegment = true, - EnableOperationId = true, - ErrorResponsesAsDefault = false, - PrefixEntityTypeNameBeforeKey = true, - TagDepth = 2, - EnablePagination = true, - EnableDiscriminatorValue = true, - EnableDerivedTypesReferencesForRequestBody = false, - EnableDerivedTypesReferencesForResponses = false, - ShowRootPath = false, - ShowLinks = false, - ExpandDerivedTypesNavigationProperties = false, - EnableCount = true, - UseSuccessStatusCodeRange = true - }; + var settings = new OpenApiConvertSettings() + { + AddSingleQuotesForStringParameters = true, + AddEnumDescriptionExtension = true, + DeclarePathParametersOnPathItem = true, + EnableKeyAsSegment = true, + EnableOperationId = true, + ErrorResponsesAsDefault = false, + PrefixEntityTypeNameBeforeKey = true, + TagDepth = 2, + EnablePagination = true, + EnableDiscriminatorValue = true, + EnableDerivedTypesReferencesForRequestBody = false, + EnableDerivedTypesReferencesForResponses = false, + ShowRootPath = false, + ShowLinks = false, + ExpandDerivedTypesNavigationProperties = false, + EnableCount = true, + UseSuccessStatusCodeRange = true + }; + config.GetSection("OpenApiConvertSettings").Bind(settings); OpenApiDocument document = edmModel.ConvertToOpenApi(settings); diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 3af6818da..71e9e0d00 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -47,8 +47,8 @@ static async Task Main(string[] args) var terseOutputOption = new Option("--terse-output", "Produce terse json output"); terseOutputOption.AddAlias("--to"); - var settingsFileOption = new Option("--settingsFile", "The configuration file with CSDL conversion settings."); - settingsFileOption.AddAlias("--sf"); + var settingsFileOption = new Option("--settings-path", "The configuration file with CSDL conversion settings."); + settingsFileOption.AddAlias("--sp"); var logLevelOption = new Option("--log-level", () => LogLevel.Information, "The log level to use when logging messages to the main output."); logLevelOption.AddAlias("--ll"); @@ -121,20 +121,9 @@ static async Task Main(string[] args) rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); - // Parse the incoming args and invoke the handler await rootCommand.InvokeAsync(args); - - //await new CommandLineBuilder(rootCommand) - // .UseHost(_ => Host.CreateDefaultBuilder(), - // host => { - // var config = host.Services.GetRequiredService(); - // }) - // .UseDefaults() - // .Build() - // .InvokeAsync(args); - //// Wait for logger to write messages to the console before exiting await Task.Delay(10); } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 44d0740be..c2fb3798f 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; -using System.IO; -using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.OpenApi.Hidi; using Microsoft.OpenApi.OData; @@ -54,18 +51,25 @@ public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocumen Assert.Equal(expectedPathCount, subsetOpenApiDocument.Paths.Count); } - [Fact] - public void ReturnOpenApiConvertSettings() + [Theory] + [InlineData("UtilityFiles/appsettingstest.json")] + [InlineData(null)] + public void ReturnOpenApiConvertSettingsWhenSettingsFileIsProvided(string filePath) { // Arrange - var filePath = "C:/Users/v-makim/source/repos/OpenAPI.NET/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/appsettingstest.json"; var config = OpenApiService.GetConfiguration(filePath); - - // Act + + // Act and Assert var settings = config.GetSection("OpenApiConvertSettings").Get(); - // Assert - Assert.NotNull(settings); + if (filePath == null) + { + Assert.Null(settings); + } + else + { + Assert.NotNull(settings); + } } } } From 973cd6da0fac60e9c338bfac7aabe5268f4ed798 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 8 Nov 2022 10:26:15 -0500 Subject: [PATCH 280/855] - upgrades to dotnet 7 Signed-off-by: Vincent Biret --- .azure-pipelines/ci-build.yml | 4 ++-- .github/workflows/ci-cd.yml | 2 +- .github/workflows/codeql-analysis.yml | 2 +- .vscode/launch.json | 2 +- Dockerfile | 6 +++--- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 6 +++--- .../Microsoft.OpenApi.Workbench.csproj | 2 +- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 4 ++-- .../Microsoft.OpenApi.SmokeTests.csproj | 4 ++-- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- .../PublicApi/PublicApi.approved.txt | 2 +- 12 files changed, 19 insertions(+), 19 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 2f1b6b9b5..363654179 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -31,9 +31,9 @@ stages: - job: build steps: - task: UseDotNet@2 - displayName: 'Use .NET 6' + displayName: 'Use .NET' inputs: - version: 6.x + version: 7.x - task: PoliCheck@1 displayName: 'Run PoliCheck "/src"' diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index b394e018b..097fc3b96 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -16,7 +16,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v3 with: - dotnet-version: 6.0.x + dotnet-version: 7.0.x - name: Data gatherer id: data_gatherer diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index eb56ea14f..89d7e62c1 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -19,7 +19,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v3 with: - dotnet-version: 6.0.x + dotnet-version: 7.0.x - name: Initialize CodeQL id: init_codeql diff --git a/.vscode/launch.json b/.vscode/launch.json index b59349979..974002cfe 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,7 +10,7 @@ "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/src/Microsoft.OpenApi.Hidi/bin/Debug/net6.0/Microsoft.OpenApi.Hidi.dll", + "program": "${workspaceFolder}/src/Microsoft.OpenApi.Hidi/bin/Debug/net7.0/Microsoft.OpenApi.Hidi.dll", "args": [], "cwd": "${workspaceFolder}/src/Microsoft.OpenApi.Hidi", // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console diff --git a/Dockerfile b/Dockerfile index 8326ce3b9..6b3507124 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,14 +1,14 @@ -FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env +FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build-env WORKDIR /app COPY ./src ./hidi/src WORKDIR /app/hidi RUN dotnet publish ./src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj -c Release -FROM mcr.microsoft.com/dotnet/runtime:6.0 as runtime +FROM mcr.microsoft.com/dotnet/runtime:7.0 as runtime WORKDIR /app -COPY --from=build-env /app/hidi/src/Microsoft.OpenApi.Hidi/bin/Release/net6.0 ./ +COPY --from=build-env /app/hidi/src/Microsoft.OpenApi.Hidi/bin/Release/net7.0 ./ VOLUME /app/output VOLUME /app/openapi.yml diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index f88e7ed63..c7f84666a 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -2,7 +2,7 @@ Exe - net6.0 + net7.0 9.0 true http://go.microsoft.com/fwlink/?LinkID=288890 @@ -43,8 +43,8 @@ - - + + diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index cf3ff2225..ed69b8145 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -1,6 +1,6 @@  - net6.0-windows + net7.0-windows WinExe false true diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index d73d8af81..f450e2ff7 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -1,7 +1,7 @@ - net6.0 + net7.0 enable enable diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 2e73118b2..cecc1c777 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -1,6 +1,6 @@ - net6.0 + net7.0 false Microsoft @@ -253,7 +253,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index bb1cf129d..9c88e8394 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -1,7 +1,7 @@  - net6.0 + net7.0 @@ -9,7 +9,7 @@ - + all diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 666a2b39b..0a20ba420 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -1,6 +1,6 @@  - net6.0 + net7.0 false Microsoft diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 75e12f480..f0afc457f 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1,7 +1,7 @@ [assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/Microsoft/OpenAPI.NET")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Readers.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Microsoft.OpenApi.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")] -[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName="")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName=".NET Standard 2.0")] namespace Microsoft.OpenApi.Any { public enum AnyType From c9285d3900b2e54f48f845ef400e2e235adb48cf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 8 Nov 2022 21:01:46 +0000 Subject: [PATCH 281/855] Bump System.CommandLine.Hosting Bumps [System.CommandLine.Hosting](https://github.com/dotnet/command-line-api) from 0.4.0-alpha.22114.1 to 0.4.0-alpha.22272.1. - [Release notes](https://github.com/dotnet/command-line-api/releases) - [Changelog](https://github.com/dotnet/command-line-api/blob/main/docs/History.md) - [Commits](https://github.com/dotnet/command-line-api/commits) --- updated-dependencies: - dependency-name: System.CommandLine.Hosting dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index f88e7ed63..c3fe239bb 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -44,7 +44,7 @@ - + From 07c4567ada2c914d203e5a3016794c3ea4c97da5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 8 Nov 2022 21:20:46 +0000 Subject: [PATCH 282/855] Bump Microsoft.OpenApi.OData from 1.2.0-preview6 to 1.2.0-preview7 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.2.0-preview6 to 1.2.0-preview7. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index c3fe239bb..d89cd5026 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From b6a22d52381f6a775c7ae1ddfe53f1ce151d6c4b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Nov 2022 21:01:40 +0000 Subject: [PATCH 283/855] Bump Verify.Xunit from 18.4.0 to 19.0.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 18.4.0 to 19.0.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 666a2b39b..2c3854a74 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 8538d192ab23971c99b4c00a8bb85afc5273ece0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Nov 2022 21:01:49 +0000 Subject: [PATCH 284/855] Bump Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers Bumps [Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers](https://github.com/dotnet/upgrade-assistant) from 0.4.346202 to 0.4.355802. - [Release notes](https://github.com/dotnet/upgrade-assistant/releases) - [Changelog](https://github.com/dotnet/upgrade-assistant/blob/main/CHANGELOG.md) - [Commits](https://github.com/dotnet/upgrade-assistant/commits) --- updated-dependencies: - dependency-name: Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index cf3ff2225..6c6f8cac9 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -7,7 +7,7 @@ true - + all From fb9633dcdaeec8c483778a497f0f356e05fbb4cd Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 10 Nov 2022 09:00:14 -0500 Subject: [PATCH 285/855] - adds dotnet 6 since ESRP requires it Signed-off-by: Vincent Biret --- .azure-pipelines/ci-build.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 363654179..cc34d8e1f 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -31,7 +31,12 @@ stages: - job: build steps: - task: UseDotNet@2 - displayName: 'Use .NET' + displayName: 'Use .NET 6' # needed for ESRP signing + inputs: + version: 6.x + + - task: UseDotNet@2 + displayName: 'Use .NET 7' inputs: version: 7.x From 8529c423c9ecf1c3778fda0463b979352f11f772 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 10 Nov 2022 09:42:01 -0500 Subject: [PATCH 286/855] - switches to dotnet 2 to fix ESRP Signed-off-by: Vincent Biret --- .azure-pipelines/ci-build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index cc34d8e1f..4ce92b8e9 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -31,9 +31,9 @@ stages: - job: build steps: - task: UseDotNet@2 - displayName: 'Use .NET 6' # needed for ESRP signing + displayName: 'Use .NET 2' # needed for ESRP signing inputs: - version: 6.x + version: 2.x - task: UseDotNet@2 displayName: 'Use .NET 7' From b69da0d692d677936dd67327990e8fa7f37b43c4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Nov 2022 21:02:32 +0000 Subject: [PATCH 287/855] Bump Verify.Xunit from 19.0.0 to 19.1.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.0.0 to 19.1.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.0.0...19.1.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index ecd30cfdd..e2a21cc74 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 3a679ddf3419d9d1d7437538b9946b093b09f76e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Nov 2022 21:07:16 +0000 Subject: [PATCH 288/855] Bump Microsoft.OpenApi.OData from 1.2.0-preview7 to 1.2.0-preview8 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.2.0-preview7 to 1.2.0-preview8. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index c7f84666a..03d8c70f0 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 2d48b610f589a1488f1ddf9ca087b28c6685a592 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 18 Nov 2022 12:35:54 +0300 Subject: [PATCH 289/855] Adds a flag for identifying whether an external reference is a fragment --- .../V3/OpenApiV3VersionService.cs | 16 ++++++++++------ src/Microsoft.OpenApi/Models/OpenApiReference.cs | 12 +++++++++++- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 1e729f30a..742b64388 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -71,6 +71,7 @@ public OpenApiReference ConvertToOpenApiReference( string reference, ReferenceType? type) { + var openApiReference = new OpenApiReference(); if (!string.IsNullOrWhiteSpace(reference)) { var segments = reference.Split('#'); @@ -127,13 +128,16 @@ public OpenApiReference ConvertToOpenApiReference( } id = localSegments[3]; } - - return new OpenApiReference + else { - ExternalResource = segments[0], - Type = type, - Id = id - }; + openApiReference.IsFragrament = true; + } + + openApiReference.ExternalResource = segments[0]; + openApiReference.Type = type; + openApiReference.Id = id; + + return openApiReference; } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index ecc643dc3..e8798cc64 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -45,6 +45,11 @@ public class OpenApiReference : IOpenApiSerializable /// public bool IsLocal => ExternalResource == null; + /// + /// Gets a flag indicating whether a file is a valid OpenAPI document or a fragment + /// + public bool IsFragrament = false; + /// /// The OpenApiDocument that is hosting the OpenApiReference instance. This is used to enable dereferencing the reference. /// @@ -196,7 +201,12 @@ private string GetExternalReferenceV3() { if (Id != null) { - return ExternalResource + "#/components/" + Type.GetDisplayName() + "/"+ Id; + if (IsFragrament) + { + return ExternalResource + "#" + Id; + } + + return ExternalResource + "#/components/" + Type.GetDisplayName() + "/"+ Id; } return ExternalResource; From 901346c404b711c6b5b85edff35f63c41ada976b Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 18 Nov 2022 12:36:26 +0300 Subject: [PATCH 290/855] Adds tests to verify external references that are fragments aren't rewritten --- .../Microsoft.OpenApi.Readers.Tests.csproj | 3 +++ .../V3Tests/OpenApiDocumentTests.cs | 20 +++++++++++++++++++ .../documentWithExternalRefs.yaml | 16 +++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/documentWithExternalRefs.yaml diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 2e73118b2..b5d1167f3 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -149,6 +149,9 @@ Never + + Never + Never diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 6fbb7065a..362609291 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.IO; using System.Linq; +using System.Text; using System.Threading; using FluentAssertions; using Microsoft.OpenApi.Any; @@ -1327,5 +1328,24 @@ public void HeaderParameterShouldAllowExample() }); } } + + [Fact] + public void DoesNotChangeExternalReferences() + { + // Arrange + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "documentWithExternalRefs.yaml")); + + // Act + var doc = new OpenApiStreamReader( + new OpenApiReaderSettings { ReferenceResolution = ReferenceResolutionSetting.DoNotResolveReferences}) + .Read(stream, out var diagnostic); + + var externalRef = doc.Components.Schemas["Nested"].Properties["AnyOf"].AnyOf.First().Reference.ReferenceV3; + var externalRef2 = doc.Components.Schemas["Nested"].Properties["AnyOf"].AnyOf.Last().Reference.ReferenceV3; + + // Assert + Assert.Equal("file:///C:/MySchemas.json#/definitions/ArrayObject", externalRef); + Assert.Equal("../foo/schemas.yaml#/components/schemas/Number", externalRef2); + } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/documentWithExternalRefs.yaml b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/documentWithExternalRefs.yaml new file mode 100644 index 000000000..c0b7b3a25 --- /dev/null +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/documentWithExternalRefs.yaml @@ -0,0 +1,16 @@ + openapi: 3.0.1 + info: + title: anyOf-oneOf + license: + name: MIT + version: 1.0.0 + paths: { } + components: + schemas: + Nested: + type: object + properties: + AnyOf: + anyOf: + - $ref: file:///C:/MySchemas.json#/definitions/ArrayObject + - $ref: ../foo/schemas.yaml#/components/schemas/Number \ No newline at end of file From f73e673ac00b5a1d1e3e9c51bd27c57631f6bbe9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 18 Nov 2022 12:57:52 +0300 Subject: [PATCH 291/855] Update public API --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 75e12f480..4eb7a060d 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -773,6 +773,7 @@ namespace Microsoft.OpenApi.Models } public class OpenApiReference : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { + public bool IsFragrament; public OpenApiReference() { } public OpenApiReference(Microsoft.OpenApi.Models.OpenApiReference reference) { } public string ExternalResource { get; set; } From 4428e67a9d61c69d9b77bd526e94b6c9ae42c0b7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 18 Nov 2022 16:13:22 +0300 Subject: [PATCH 292/855] Move variable declaration closer to assignment --- src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 742b64388..ebe372d40 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -71,7 +71,6 @@ public OpenApiReference ConvertToOpenApiReference( string reference, ReferenceType? type) { - var openApiReference = new OpenApiReference(); if (!string.IsNullOrWhiteSpace(reference)) { var segments = reference.Split('#'); @@ -110,6 +109,8 @@ public OpenApiReference ConvertToOpenApiReference( } // Where fragments point into a non-OpenAPI document, the id will be the complete fragment identifier string id = segments[1]; + var openApiReference = new OpenApiReference(); + // $ref: externalSource.yaml#/Pet if (id.StartsWith("/components/")) { From 5be9a79b48a097fb8e152c30b89e9e947253c4d1 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 21 Nov 2022 10:30:32 +0300 Subject: [PATCH 293/855] Bump up lib versions from preview to stable releases --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index f88e7ed63..da61c969f 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.1.0-preview3 + 1.1.0 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index d21c300eb..defdfdd54 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.4.4-preview1 + 1.4.4 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 1affa74c6..50d026f91 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.4-preview1 + 1.4.4 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From a810004a8c6e6810147c5f4c26a80ae00bb2c3c0 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 21 Nov 2022 11:24:44 +0300 Subject: [PATCH 294/855] Add conversion setting --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index f88e7ed63..62677c571 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 0d9500682..56dda4d9a 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -349,7 +349,8 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl, stri ShowLinks = false, ExpandDerivedTypesNavigationProperties = false, EnableCount = true, - UseSuccessStatusCodeRange = true + UseSuccessStatusCodeRange = true, + EnableTypeDisambiguationForDefaultValueOfOdataTypeProperty = true }; config.GetSection("OpenApiConvertSettings").Bind(settings); From 7c9fac2667658abee93f15606aa816cbd5ec7ce1 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 22 Nov 2022 16:49:23 +0300 Subject: [PATCH 295/855] Add condition to ensure collectionFormat is only written out if schema type is array --- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index e0e472721..aa7983500 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -377,7 +377,7 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) // allowEmptyValue writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false); - if (this.In == ParameterLocation.Query) + if (this.In == ParameterLocation.Query && Schema?.Type == "array") { if (this.Style == ParameterStyle.Form && this.Explode == true) { From 42a40150251ef16933127511133dcb5ae39842db Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 22 Nov 2022 16:49:42 +0300 Subject: [PATCH 296/855] Add test --- .../Models/OpenApiDocumentTests.cs | 54 ++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 89289397f..d6c9f6e4b 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.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; @@ -1356,5 +1356,57 @@ public void CopyConstructorForAdvancedDocumentWorks() Assert.Equal(2, doc.Paths.Count); Assert.NotNull(doc.Components); } + + [Fact] + public void SerializeV2DocumentWithNonArraySchemaTypeDoesNotWriteOutCollectionFormat() + { + // Arrange + var expected = @"swagger: '2.0' +info: { } +paths: + /foo: + get: + parameters: + - in: query + type: string + responses: { }"; + + var doc = new OpenApiDocument + { + Info = new OpenApiInfo(), + Paths = new OpenApiPaths + { + ["/foo"] = new OpenApiPathItem + { + Operations = new Dictionary + { + [OperationType.Get] = new OpenApiOperation + { + Parameters = new List + { + new OpenApiParameter + { + In = ParameterLocation.Query, + Schema = new OpenApiSchema + { + Type = "string" + } + } + }, + Responses = new OpenApiResponses() + } + } + } + } + }; + + // Act + var actual = doc.SerializeAsYaml(OpenApiSpecVersion.OpenApi2_0); + + // Assert + actual = actual.MakeLineBreaksEnvironmentNeutral(); + expected = expected.MakeLineBreaksEnvironmentNeutral(); + actual.Should().Be(expected); + } } } From a409b3164a56ab71a10024e4204d7289571b6775 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 22 Nov 2022 16:49:56 +0300 Subject: [PATCH 297/855] Update verify snapshots --- ...DocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt | 3 +-- ...dDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt | 2 +- ...eferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt | 3 +-- ...ReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt | 2 +- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt index a991e0761..a2e4fbd4c 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=False.verified.txt @@ -46,8 +46,7 @@ "name": "limit", "description": "maximum number of results to return", "type": "integer", - "format": "int32", - "collectionFormat": "multi" + "format": "int32" } ], "responses": { diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt index 5ce01bf79..081bcda08 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV2JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http"],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"query","name":"tags","description":"tags to filter by","type":"array","items":{"type":"string"},"collectionFormat":"multi"},{"in":"query","name":"limit","description":"maximum number of results to return","type":"integer","format":"int32","collectionFormat":"multi"}],"responses":{"200":{"description":"pet response","schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","consumes":["application/json"],"produces":["application/json","text/html"],"parameters":[{"in":"body","name":"body","description":"Pet to add to the store","required":true,"schema":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}}],"responses":{"200":{"description":"pet response","schema":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to fetch","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"pet response","schema":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","produces":["text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to delete","required":true,"type":"integer","format":"int64"}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}}}},"definitions":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}} \ No newline at end of file +{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http"],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"query","name":"tags","description":"tags to filter by","type":"array","items":{"type":"string"},"collectionFormat":"multi"},{"in":"query","name":"limit","description":"maximum number of results to return","type":"integer","format":"int32"}],"responses":{"200":{"description":"pet response","schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","consumes":["application/json"],"produces":["application/json","text/html"],"parameters":[{"in":"body","name":"body","description":"Pet to add to the store","required":true,"schema":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}}],"responses":{"200":{"description":"pet response","schema":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to fetch","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"pet response","schema":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","produces":["text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to delete","required":true,"type":"integer","format":"int64"}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}},"5XX":{"description":"unexpected server error","schema":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}}}}},"definitions":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt index 1ee60de40..443881617 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=False.verified.txt @@ -46,8 +46,7 @@ "name": "limit", "description": "maximum number of results to return", "type": "integer", - "format": "int32", - "collectionFormat": "multi" + "format": "int32" } ], "responses": { diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt index 682b253b7..3818a4799 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV2JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http"],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"query","name":"tags","description":"tags to filter by","type":"array","items":{"type":"string"},"collectionFormat":"multi"},{"in":"query","name":"limit","description":"maximum number of results to return","type":"integer","format":"int32","collectionFormat":"multi"}],"responses":{"200":{"description":"pet response","schema":{"type":"array","items":{"$ref":"#/definitions/pet"}}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","consumes":["application/json"],"produces":["application/json","text/html"],"parameters":[{"in":"body","name":"body","description":"Pet to add to the store","required":true,"schema":{"$ref":"#/definitions/newPet"}}],"responses":{"200":{"description":"pet response","schema":{"$ref":"#/definitions/pet"}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to fetch","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"pet response","schema":{"$ref":"#/definitions/pet"}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","produces":["text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to delete","required":true,"type":"integer","format":"int64"}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}}}},"definitions":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}} \ No newline at end of file +{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http"],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"query","name":"tags","description":"tags to filter by","type":"array","items":{"type":"string"},"collectionFormat":"multi"},{"in":"query","name":"limit","description":"maximum number of results to return","type":"integer","format":"int32"}],"responses":{"200":{"description":"pet response","schema":{"type":"array","items":{"$ref":"#/definitions/pet"}}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","consumes":["application/json"],"produces":["application/json","text/html"],"parameters":[{"in":"body","name":"body","description":"Pet to add to the store","required":true,"schema":{"$ref":"#/definitions/newPet"}}],"responses":{"200":{"description":"pet response","schema":{"$ref":"#/definitions/pet"}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","produces":["application/json","application/xml","text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to fetch","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"pet response","schema":{"$ref":"#/definitions/pet"}},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","produces":["text/html"],"parameters":[{"in":"path","name":"id","description":"ID of pet to delete","required":true,"type":"integer","format":"int64"}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","schema":{"$ref":"#/definitions/errorModel"}},"5XX":{"description":"unexpected server error","schema":{"$ref":"#/definitions/errorModel"}}}}}},"definitions":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"format":"int32","type":"integer"},"message":{"type":"string"}}}}} \ No newline at end of file From 257107c56a3ec218cfa5e3d6368f549414e1a806 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 22 Nov 2022 17:13:22 +0300 Subject: [PATCH 298/855] Address PR feedback --- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index aa7983500..a57674da3 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Collections.Generic; using System.Runtime; using Microsoft.OpenApi.Any; @@ -377,7 +378,7 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) // allowEmptyValue writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false); - if (this.In == ParameterLocation.Query && Schema?.Type == "array") + if (this.In == ParameterLocation.Query && "array".Equals(Schema?.Type, StringComparison.OrdinalIgnoreCase)) { if (this.Style == ParameterStyle.Form && this.Explode == true) { From bf9a4810b79512678b4c81737bec1909cad8fe7e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 23 Nov 2022 11:03:03 +0300 Subject: [PATCH 299/855] Use backing property to check whether user has explicitly set style, if not, we don't write it out. --- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index e0e472721..745a46adc 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.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; @@ -238,9 +238,12 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) // allowEmptyValue writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false); - + // style - writer.WriteProperty(OpenApiConstants.Style, Style?.GetDisplayName()); + if (_style.HasValue) + { + writer.WriteProperty(OpenApiConstants.Style, Style.Value.GetDisplayName()); + } // explode writer.WriteProperty(OpenApiConstants.Explode, Explode, Style.HasValue && Style.Value == ParameterStyle.Form); From 3eb4f02cd4650e7b4bf1a4154ac62b2e6baaf208 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 23 Nov 2022 11:03:27 +0300 Subject: [PATCH 300/855] Add test to validate --- .../Models/OpenApiDocumentTests.cs | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 89289397f..095e661d4 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1356,5 +1356,94 @@ public void CopyConstructorForAdvancedDocumentWorks() Assert.Equal(2, doc.Paths.Count); Assert.NotNull(doc.Components); } + + [Fact] + public void SerializeV2DocumentWithStyleAsNullDoesNotWriteOutStyleValue() + { + // Arrange + var expected = @"openapi: 3.0.1 +info: + title: magic style + version: 1.0.0 +paths: + /foo: + get: + parameters: + - name: id + in: query + schema: + type: object + additionalProperties: + type: integer + responses: + '200': + description: foo + content: + text/plain: + schema: + type: string"; + + var doc = new OpenApiDocument + { + Info = new OpenApiInfo + { + Title = "magic style", + Version = "1.0.0" + }, + Paths = new OpenApiPaths + { + ["/foo"] = new OpenApiPathItem + { + Operations = new Dictionary + { + [OperationType.Get] = new OpenApiOperation + { + Parameters = new List + { + new OpenApiParameter + { + Name = "id", + In = ParameterLocation.Query, + Schema = new OpenApiSchema + { + Type = "object", + AdditionalProperties = new OpenApiSchema + { + Type = "integer" + } + } + } + }, + Responses = new OpenApiResponses + { + ["200"] = new OpenApiResponse + { + Description = "foo", + Content = new Dictionary + { + ["text/plain"] = new OpenApiMediaType + { + Schema = new OpenApiSchema + { + Type = "string" + } + } + } + } + } + } + } + } + } + }; + + // Act + var actual = doc.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); + + // Assert + actual = actual.MakeLineBreaksEnvironmentNeutral(); + expected = expected.MakeLineBreaksEnvironmentNeutral(); + actual.Should().Be(expected); + } } } From 9681ebb41772805395c93fa4f48c75f691edb54e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 23 Nov 2022 11:29:00 +0300 Subject: [PATCH 301/855] Clean up tests --- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 2 +- ...3JsonWorks_produceTerseOutput=False.verified.txt | 4 ---- ...3JsonWorks_produceTerseOutput=False.verified.txt | 4 ---- ...3JsonWorks_produceTerseOutput=False.verified.txt | 2 -- .../Models/OpenApiOperationTests.cs | 13 ++++--------- ...WorksAsync_produceTerseOutput=False.verified.txt | 3 +-- .../Models/OpenApiParameterTests.cs | 3 +-- 7 files changed, 7 insertions(+), 24 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 745a46adc..42d46dbf2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.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; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt index 5b27add35..a688f8525 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -30,7 +30,6 @@ "name": "tags", "in": "query", "description": "tags to filter by", - "style": "form", "schema": { "type": "array", "items": { @@ -42,7 +41,6 @@ "name": "limit", "in": "query", "description": "maximum number of results to return", - "style": "form", "schema": { "type": "integer", "format": "int32" @@ -266,7 +264,6 @@ "in": "path", "description": "ID of pet to fetch", "required": true, - "style": "simple", "schema": { "type": "integer", "format": "int64" @@ -378,7 +375,6 @@ "in": "path", "description": "ID of pet to delete", "required": true, - "style": "simple", "schema": { "type": "integer", "format": "int64" diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=False.verified.txt index f272b26eb..f1da0b354 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -30,7 +30,6 @@ "name": "tags", "in": "query", "description": "tags to filter by", - "style": "form", "schema": { "type": "array", "items": { @@ -42,7 +41,6 @@ "name": "limit", "in": "query", "description": "maximum number of results to return", - "style": "form", "schema": { "type": "integer", "format": "int32" @@ -151,7 +149,6 @@ "in": "path", "description": "ID of pet to fetch", "required": true, - "style": "simple", "schema": { "type": "integer", "format": "int64" @@ -205,7 +202,6 @@ "in": "path", "description": "ID of pet to delete", "required": true, - "style": "simple", "schema": { "type": "integer", "format": "int64" diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=False.verified.txt index 8b90dd0ee..c2e9f5312 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -20,7 +20,6 @@ "in": "path", "description": "The first operand", "required": true, - "style": "simple", "schema": { "type": "integer", "my-extension": 4 @@ -32,7 +31,6 @@ "in": "path", "description": "The second operand", "required": true, - "style": "simple", "schema": { "type": "integer", "my-extension": 4 diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index 368aeb227..2079a3122 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -334,13 +334,11 @@ public void SerializeOperationWithBodyAsV3JsonWorks() ""parameters"": [ { ""name"": ""parameter1"", - ""in"": ""path"", - ""style"": ""simple"" + ""in"": ""path"" }, { ""name"": ""parameter2"", - ""in"": ""header"", - ""style"": ""simple"" + ""in"": ""header"" } ], ""requestBody"": { @@ -409,13 +407,11 @@ public void SerializeAdvancedOperationWithTagAndSecurityAsV3JsonWorks() ""parameters"": [ { ""name"": ""parameter1"", - ""in"": ""path"", - ""style"": ""simple"" + ""in"": ""path"" }, { ""name"": ""parameter2"", - ""in"": ""header"", - ""style"": ""simple"" + ""in"": ""header"" } ], ""requestBody"": { @@ -505,7 +501,6 @@ public void SerializeOperationWithFormDataAsV3JsonWorks() ""in"": ""path"", ""description"": ""ID of pet that needs to be updated"", ""required"": true, - ""style"": ""simple"", ""schema"": { ""type"": ""string"" } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=False.verified.txt index f4424fa30..5275532e8 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=False.verified.txt @@ -1,5 +1,4 @@ { "name": "name1", - "in": "path", - "style": "simple" + "in": "path" } \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index cfcc56d15..2f57673af 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs @@ -213,8 +213,7 @@ public void SerializeBasicParameterAsV3JsonWorks() // Arrange var expected = @"{ ""name"": ""name1"", - ""in"": ""path"", - ""style"": ""simple"" + ""in"": ""path"" }"; // Act From 48394eff6208973a7df7b816b97d3814f56d2a27 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 23 Nov 2022 11:52:37 +0300 Subject: [PATCH 302/855] Update verifier snapshot --- ...dDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt index a688f8525..a94db37b7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -1,4 +1,4 @@ -{ +{ "openapi": "3.0.1", "info": { "title": "Swagger Petstore (Simple)", From 0a0ec5fcf3a1bbad79ac960551ffa839fc63025b Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 23 Nov 2022 14:01:52 +0300 Subject: [PATCH 303/855] Delete verifier --- ...orks_produceTerseOutput=False.verified.txt | 495 ------------------ 1 file changed, 495 deletions(-) delete mode 100644 test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt deleted file mode 100644 index a94db37b7..000000000 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ /dev/null @@ -1,495 +0,0 @@ -{ - "openapi": "3.0.1", - "info": { - "title": "Swagger Petstore (Simple)", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "Swagger API team", - "url": "http://swagger.io", - "email": "foo@example.com" - }, - "license": { - "name": "MIT", - "url": "http://opensource.org/licenses/MIT" - }, - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://petstore.swagger.io/api" - } - ], - "paths": { - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "operationId": "findPets", - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "tags to filter by", - "schema": { - "type": "array", - "items": { - "type": "string" - } - } - }, - { - "name": "limit", - "in": "query", - "description": "maximum number of results to return", - "schema": { - "type": "integer", - "format": "int32" - } - } - ], - "responses": { - "200": { - "description": "pet response", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - }, - "application/xml": { - "schema": { - "type": "array", - "items": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - } - } - }, - "4XX": { - "description": "unexpected client error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "5XX": { - "description": "unexpected server error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - } - } - }, - "post": { - "description": "Creates a new pet in the store. Duplicates are allowed", - "operationId": "addPet", - "requestBody": { - "description": "Pet to add to the store", - "content": { - "application/json": { - "schema": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "pet response", - "content": { - "application/json": { - "schema": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - } - }, - "4XX": { - "description": "unexpected client error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "5XX": { - "description": "unexpected server error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - } - } - } - }, - "/pets/{id}": { - "get": { - "description": "Returns a user based on a single ID, if the user does not have access to the pet", - "operationId": "findPetById", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to fetch", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } - } - ], - "responses": { - "200": { - "description": "pet response", - "content": { - "application/json": { - "schema": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - }, - "application/xml": { - "schema": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - } - }, - "4XX": { - "description": "unexpected client error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "5XX": { - "description": "unexpected server error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - } - } - }, - "delete": { - "description": "deletes a single pet based on the ID supplied", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "4XX": { - "description": "unexpected client error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "5XX": { - "description": "unexpected server error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - } - } - } - } - }, - "components": { - "schemas": { - "pet": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "newPet": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "errorModel": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } -} \ No newline at end of file From 089ddc2e66b6d3068ef6d7289851fd01d246c9e5 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 23 Nov 2022 14:08:20 +0300 Subject: [PATCH 304/855] Revert change --- ...orks_produceTerseOutput=False.verified.txt | 495 ++++++++++++++++++ 1 file changed, 495 insertions(+) create mode 100644 test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt new file mode 100644 index 000000000..a94db37b7 --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -0,0 +1,495 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "Swagger Petstore (Simple)", + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "name": "Swagger API team", + "url": "http://swagger.io", + "email": "foo@example.com" + }, + "license": { + "name": "MIT", + "url": "http://opensource.org/licenses/MIT" + }, + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://petstore.swagger.io/api" + } + ], + "paths": { + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "operationId": "findPets", + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "tags to filter by", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "limit", + "in": "query", + "description": "maximum number of results to return", + "schema": { + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + }, + "application/xml": { + "schema": { + "type": "array", + "items": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + }, + "post": { + "description": "Creates a new pet in the store. Duplicates are allowed", + "operationId": "addPet", + "requestBody": { + "description": "Pet to add to the store", + "content": { + "application/json": { + "schema": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "/pets/{id}": { + "get": { + "description": "Returns a user based on a single ID, if the user does not have access to the pet", + "operationId": "findPetById", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to fetch", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + }, + "application/xml": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + }, + "delete": { + "description": "deletes a single pet based on the ID supplied", + "operationId": "deletePet", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to delete", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "responses": { + "204": { + "description": "pet deleted" + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "pet": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "newPet": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "errorModel": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } +} \ No newline at end of file From 429d7c599001d39454cd6a45fbfbf38d6d982f69 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 25 Nov 2022 09:38:17 +0300 Subject: [PATCH 305/855] Bump Newtonsoft.Json from 13.0.1 to 13.0.2 (#1091) Bumps [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) from 13.0.1 to 13.0.2. - [Release notes](https://github.com/JamesNK/Newtonsoft.Json/releases) - [Commits](https://github.com/JamesNK/Newtonsoft.Json/compare/13.0.1...13.0.2) --- updated-dependencies: - dependency-name: Newtonsoft.Json dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index a12969f52..920c0e65a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -256,7 +256,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 9c88e8394..9634f9358 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -9,7 +9,7 @@ - + all diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index e2a21cc74..8de99ad85 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -18,7 +18,7 @@ - + From 49270e398b98dd5f8698e727ccf4c374afa1ae6f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 25 Nov 2022 11:29:06 +0300 Subject: [PATCH 306/855] Remove test --- test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 72dccdd4b..a2f331e0f 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -988,7 +988,6 @@ public OpenApiDocumentTests(ITestOutputHelper output) [Theory] [InlineData(true)] - [InlineData(false)] public async Task SerializeAdvancedDocumentAsV3JsonWorks(bool produceTerseOutput) { // Arrange From 775c136da9809af6d79a4b72f4d226905a9ab351 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 25 Nov 2022 11:53:24 +0300 Subject: [PATCH 307/855] Remove verified text --- ...orks_produceTerseOutput=False.verified.txt | 496 +----------------- 1 file changed, 1 insertion(+), 495 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt index a94db37b7..5f282702b 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -1,495 +1 @@ -{ - "openapi": "3.0.1", - "info": { - "title": "Swagger Petstore (Simple)", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "Swagger API team", - "url": "http://swagger.io", - "email": "foo@example.com" - }, - "license": { - "name": "MIT", - "url": "http://opensource.org/licenses/MIT" - }, - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://petstore.swagger.io/api" - } - ], - "paths": { - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "operationId": "findPets", - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "tags to filter by", - "schema": { - "type": "array", - "items": { - "type": "string" - } - } - }, - { - "name": "limit", - "in": "query", - "description": "maximum number of results to return", - "schema": { - "type": "integer", - "format": "int32" - } - } - ], - "responses": { - "200": { - "description": "pet response", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - }, - "application/xml": { - "schema": { - "type": "array", - "items": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - } - } - }, - "4XX": { - "description": "unexpected client error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "5XX": { - "description": "unexpected server error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - } - } - }, - "post": { - "description": "Creates a new pet in the store. Duplicates are allowed", - "operationId": "addPet", - "requestBody": { - "description": "Pet to add to the store", - "content": { - "application/json": { - "schema": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "pet response", - "content": { - "application/json": { - "schema": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - } - }, - "4XX": { - "description": "unexpected client error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "5XX": { - "description": "unexpected server error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - } - } - } - }, - "/pets/{id}": { - "get": { - "description": "Returns a user based on a single ID, if the user does not have access to the pet", - "operationId": "findPetById", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to fetch", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } - } - ], - "responses": { - "200": { - "description": "pet response", - "content": { - "application/json": { - "schema": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - }, - "application/xml": { - "schema": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } - } - }, - "4XX": { - "description": "unexpected client error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "5XX": { - "description": "unexpected server error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - } - } - }, - "delete": { - "description": "deletes a single pet based on the ID supplied", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "4XX": { - "description": "unexpected client error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "5XX": { - "description": "unexpected server error", - "content": { - "text/html": { - "schema": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } - } - } - } - } - }, - "components": { - "schemas": { - "pet": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "newPet": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "errorModel": { - "required": [ - "code", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } - } -} \ No newline at end of file + \ No newline at end of file From b47d3a1fe383e41ee7432d939a6af4fe8782278e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 25 Nov 2022 11:57:32 +0300 Subject: [PATCH 308/855] Add verified text --- ...orks_produceTerseOutput=False.verified.txt | 496 +++++++++++++++++- 1 file changed, 495 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt index 5f282702b..a94db37b7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=False.verified.txt @@ -1 +1,495 @@ - \ No newline at end of file +{ + "openapi": "3.0.1", + "info": { + "title": "Swagger Petstore (Simple)", + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "name": "Swagger API team", + "url": "http://swagger.io", + "email": "foo@example.com" + }, + "license": { + "name": "MIT", + "url": "http://opensource.org/licenses/MIT" + }, + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://petstore.swagger.io/api" + } + ], + "paths": { + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "operationId": "findPets", + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "tags to filter by", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "limit", + "in": "query", + "description": "maximum number of results to return", + "schema": { + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + }, + "application/xml": { + "schema": { + "type": "array", + "items": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + }, + "post": { + "description": "Creates a new pet in the store. Duplicates are allowed", + "operationId": "addPet", + "requestBody": { + "description": "Pet to add to the store", + "content": { + "application/json": { + "schema": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "/pets/{id}": { + "get": { + "description": "Returns a user based on a single ID, if the user does not have access to the pet", + "operationId": "findPetById", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to fetch", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + }, + "application/xml": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + }, + "delete": { + "description": "deletes a single pet based on the ID supplied", + "operationId": "deletePet", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to delete", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "responses": { + "204": { + "description": "pet deleted" + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "pet": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "newPet": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "errorModel": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } +} \ No newline at end of file From 2a7cfdc7fd5872d42c1e822fd7bc48778215c2a9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 25 Nov 2022 12:09:33 +0300 Subject: [PATCH 309/855] Return test --- test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index a2f331e0f..5aa4612b4 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -987,7 +987,8 @@ public OpenApiDocumentTests(ITestOutputHelper output) } [Theory] - [InlineData(true)] + //[InlineData(true)] + [InlineData(false)] public async Task SerializeAdvancedDocumentAsV3JsonWorks(bool produceTerseOutput) { // Arrange From 4df2357e4eb313b80f1edbb5467108fbf5ddb89b Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 25 Nov 2022 12:13:34 +0300 Subject: [PATCH 310/855] Delete verified text --- ...edDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt index e3abf0e50..5f282702b 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","style":"form","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","style":"form","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"application/xml":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"style":"simple","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"application/xml":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"style":"simple","schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file + \ No newline at end of file From d41d2af6527ef7a37e4bbaa0f50fd1e79b962e70 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 25 Nov 2022 12:14:46 +0300 Subject: [PATCH 311/855] Add verified text --- ...edDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt index 5f282702b..72106e400 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ - \ No newline at end of file +{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"application/xml":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"application/xml":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file From 84a7ba23e3fcfa1ed05a8c4827fd808343031e4c Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Fri, 25 Nov 2022 14:33:28 +0300 Subject: [PATCH 312/855] Revert change --- test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 5aa4612b4..bbcf1ad15 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.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; @@ -987,8 +987,8 @@ public OpenApiDocumentTests(ITestOutputHelper output) } [Theory] - //[InlineData(true)] [InlineData(false)] + [InlineData(true)] public async Task SerializeAdvancedDocumentAsV3JsonWorks(bool produceTerseOutput) { // Arrange From 0527f999ce4a52de3aa421588e1368db8fdb94a6 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 28 Nov 2022 11:20:50 +0300 Subject: [PATCH 313/855] Remove static modifier as it creates static dependency of the document instance when running tests in parallel causing one to fail --- test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index bbcf1ad15..8633bdbaf 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1,10 +1,11 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Extensions; @@ -598,7 +599,7 @@ public class OpenApiDocumentTests public static OpenApiSchema ErrorModelSchema = AdvancedComponents.Schemas["errorModel"]; - public static OpenApiDocument AdvancedDocument = new OpenApiDocument + public OpenApiDocument AdvancedDocument = new OpenApiDocument { Info = new OpenApiInfo { From d4b6c00962462f808fdf7fcd997da80ae9af5782 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 28 Nov 2022 11:21:07 +0300 Subject: [PATCH 314/855] Update verified snapshots --- ...rks2_produceTerseOutput=False.verified.txt | 495 ++++++++++++++++++ ...orks2_produceTerseOutput=True.verified.txt | 1 + 2 files changed, 496 insertions(+) create mode 100644 test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks2_produceTerseOutput=False.verified.txt create mode 100644 test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks2_produceTerseOutput=True.verified.txt diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks2_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks2_produceTerseOutput=False.verified.txt new file mode 100644 index 000000000..a94db37b7 --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks2_produceTerseOutput=False.verified.txt @@ -0,0 +1,495 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "Swagger Petstore (Simple)", + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "name": "Swagger API team", + "url": "http://swagger.io", + "email": "foo@example.com" + }, + "license": { + "name": "MIT", + "url": "http://opensource.org/licenses/MIT" + }, + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://petstore.swagger.io/api" + } + ], + "paths": { + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "operationId": "findPets", + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "tags to filter by", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "limit", + "in": "query", + "description": "maximum number of results to return", + "schema": { + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + }, + "application/xml": { + "schema": { + "type": "array", + "items": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + }, + "post": { + "description": "Creates a new pet in the store. Duplicates are allowed", + "operationId": "addPet", + "requestBody": { + "description": "Pet to add to the store", + "content": { + "application/json": { + "schema": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "/pets/{id}": { + "get": { + "description": "Returns a user based on a single ID, if the user does not have access to the pet", + "operationId": "findPetById", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to fetch", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "responses": { + "200": { + "description": "pet response", + "content": { + "application/json": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + }, + "application/xml": { + "schema": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + } + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + }, + "delete": { + "description": "deletes a single pet based on the ID supplied", + "operationId": "deletePet", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to delete", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "responses": { + "204": { + "description": "pet deleted" + }, + "4XX": { + "description": "unexpected client error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "5XX": { + "description": "unexpected server error", + "content": { + "text/html": { + "schema": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "pet": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "newPet": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "errorModel": { + "required": [ + "code", + "message" + ], + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + } +} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks2_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks2_produceTerseOutput=True.verified.txt new file mode 100644 index 000000000..72106e400 --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentAsV3JsonWorks2_produceTerseOutput=True.verified.txt @@ -0,0 +1 @@ +{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"application/xml":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"application/xml":{"schema":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file From 5a58d79f50b527b970cb4ce8602fc06919c4cd0c Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 29 Nov 2022 09:51:04 -0500 Subject: [PATCH 315/855] - adds coverage dependencies --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 4 ++++ .../Microsoft.OpenApi.Readers.Tests.csproj | 8 ++++++++ .../Microsoft.OpenApi.SmokeTests.csproj | 8 ++++++++ .../Microsoft.OpenApi.Tests.csproj | 8 ++++++++ 4 files changed, 28 insertions(+) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index f450e2ff7..5cc0d90a8 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -9,6 +9,10 @@ + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 920c0e65a..8fb35ee88 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -253,6 +253,14 @@ + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 9634f9358..0fab323f7 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -8,6 +8,14 @@ + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 8de99ad85..055137f7b 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,6 +15,14 @@ + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + From 47984b463a6d7e515401623d51e0ef8d8b63b417 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 29 Nov 2022 09:53:26 -0500 Subject: [PATCH 316/855] - adds sonarcloud workflow definition --- .github/workflows/sonarcloud.yml | 78 ++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 .github/workflows/sonarcloud.yml diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml new file mode 100644 index 000000000..6812553ce --- /dev/null +++ b/.github/workflows/sonarcloud.yml @@ -0,0 +1,78 @@ +name: Sonarcloud +on: + workflow_dispatch: + push: + branches: + - main + paths-ignore: ['.vscode/**'] + pull_request: + types: [opened, synchronize, reopened] + paths-ignore: ['.vscode/**'] + +env: + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + +jobs: + checksecret: + name: check if SONAR_TOKEN is set in github secrets + runs-on: ubuntu-latest + outputs: + is_SONAR_TOKEN_set: ${{ steps.checksecret_job.outputs.is_SONAR_TOKEN_set }} + steps: + - name: Check whether unity activation requests should be done + id: checksecret_job + run: | + echo "is_SONAR_TOKEN_set=${{ env.SONAR_TOKEN != '' }}" >> $GITHUB_OUTPUT + build: + needs: [checksecret] + if: needs.checksecret.outputs.is_SONAR_TOKEN_set == 'true' + name: Build + runs-on: ubuntu-latest + steps: + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + distribution: 'adopt' + java-version: 11 + - name: Setup .NET 5 # At the moment the scanner requires dotnet 5 https://www.nuget.org/packages/dotnet-sonarscanner + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 5.0.x + - name: Setup .NET + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 7.0.x + - uses: actions/checkout@v3 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + - name: Cache SonarCloud packages + uses: actions/cache@v3 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + - name: Cache SonarCloud scanner + id: cache-sonar-scanner + uses: actions/cache@v3 + with: + path: ./.sonar/scanner + key: ${{ runner.os }}-sonar-scanner + restore-keys: ${{ runner.os }}-sonar-scanner + - name: Install SonarCloud scanner + if: steps.cache-sonar-scanner.outputs.cache-hit != 'true' + shell: pwsh + run: | + New-Item -Path ./.sonar/scanner -ItemType Directory + dotnet tool update dotnet-sonarscanner --tool-path ./.sonar/scanner + - name: Build and analyze + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + CollectCoverage: true + CoverletOutputFormat: 'opencover' # https://github.com/microsoft/vstest/issues/4014#issuecomment-1307913682 + shell: pwsh + run: | + ./.sonar/scanner/dotnet-sonarscanner begin /k:"microsoft_OpenAPI.NET" /o:"microsoft" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.opencover.reportsPaths="test/**/coverage.opencover.xml" + dotnet workload restore + dotnet build + dotnet test Microsoft.OpenApi.sln --no-build --verbosity normal /p:CollectCoverage=true /p:CoverletOutputFormat=opencover + ./.sonar/scanner/dotnet-sonarscanner end /d:sonar.login="${{ secrets.SONAR_TOKEN }}" \ No newline at end of file From 65e92bfb963c798b752b0152850cb481d7279290 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 29 Nov 2022 09:57:17 -0500 Subject: [PATCH 317/855] - switches to windows agent because of workbench projectg --- .github/workflows/sonarcloud.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 6812553ce..d7efd6213 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -27,7 +27,7 @@ jobs: needs: [checksecret] if: needs.checksecret.outputs.is_SONAR_TOKEN_set == 'true' name: Build - runs-on: ubuntu-latest + runs-on: windows-latest steps: - name: Set up JDK 11 uses: actions/setup-java@v3 From 53f5f805a8c624b89a0cc5f9c5d2a15c817c274a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 29 Nov 2022 21:01:40 +0000 Subject: [PATCH 318/855] Bump Verify.Xunit from 19.1.0 to 19.3.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.1.0 to 19.3.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.1.0...19.3.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 8de99ad85..40f9eb637 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -20,7 +20,7 @@ - + all From 495d8e635e03b427403624e7971ad081015322c3 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 1 Dec 2022 10:40:37 +0300 Subject: [PATCH 319/855] Add OpenApiTypeMapper that maps .NET primitive types to the OpenAPI schema type equivalent --- .../Extensions/OpenApiTypeMapper.cs | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs new file mode 100644 index 000000000..42b645b3a --- /dev/null +++ b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Microsoft.OpenApi.Models; + +namespace Microsoft.OpenApi.Extensions +{ + /// + /// Extension methods for . + /// + public static class OpenApiTypeMapper + { + private static readonly Dictionary> _simpleTypeToOpenApiSchema = new() + { + [typeof(bool)] = () => new OpenApiSchema { Type = "boolean" }, + [typeof(byte)] = () => new OpenApiSchema { Type = "string", Format = "byte" }, + [typeof(int)] = () => new OpenApiSchema { Type = "integer", Format = "int32" }, + [typeof(uint)] = () => new OpenApiSchema { Type = "integer", Format = "int32" }, + [typeof(long)] = () => new OpenApiSchema { Type = "integer", Format = "int64" }, + [typeof(ulong)] = () => new OpenApiSchema { Type = "integer", Format = "int64" }, + [typeof(float)] = () => new OpenApiSchema { Type = "number", Format = "float" }, + [typeof(double)] = () => new OpenApiSchema { Type = "number", Format = "double" }, + [typeof(decimal)] = () => new OpenApiSchema { Type = "number", Format = "double" }, + [typeof(DateTime)] = () => new OpenApiSchema { Type = "string", Format = "date-time" }, + [typeof(DateTimeOffset)] = () => new OpenApiSchema { Type = "string", Format = "date-time" }, + [typeof(Guid)] = () => new OpenApiSchema { Type = "string", Format = "uuid" }, + [typeof(char)] = () => new OpenApiSchema { Type = "string" }, + + // Nullable types + [typeof(bool?)] = () => new OpenApiSchema { Type = "boolean", Nullable = true }, + [typeof(byte?)] = () => new OpenApiSchema { Type = "string", Format = "byte", Nullable = true }, + [typeof(int?)] = () => new OpenApiSchema { Type = "integer", Format = "int32", Nullable = true }, + [typeof(uint?)] = () => new OpenApiSchema { Type = "integer", Format = "int32", Nullable = true }, + [typeof(long?)] = () => new OpenApiSchema { Type = "integer", Format = "int64", Nullable = true }, + [typeof(ulong?)] = () => new OpenApiSchema { Type = "integer", Format = "int64", Nullable = true }, + [typeof(float?)] = () => new OpenApiSchema { Type = "number", Format = "float", Nullable = true }, + [typeof(double?)] = () => new OpenApiSchema { Type = "number", Format = "double", Nullable = true }, + [typeof(decimal?)] = () => new OpenApiSchema { Type = "number", Format = "double", Nullable = true }, + [typeof(DateTime?)] = () => new OpenApiSchema { Type = "string", Format = "date-time", Nullable = true }, + [typeof(DateTimeOffset?)] = () => new OpenApiSchema { Type = "string", Format = "date-time", Nullable = true }, + [typeof(Guid?)] = () => new OpenApiSchema { Type = "string", Format = "uuid", Nullable = true }, + [typeof(char?)] = () => new OpenApiSchema { Type = "string", Nullable = true }, + + [typeof(Uri)] = () => new OpenApiSchema { Type = "string" }, // Uri is treated as simple string + [typeof(string)] = () => new OpenApiSchema { Type = "string" }, + [typeof(object)] = () => new OpenApiSchema { Type = "object" } + }; + + /// + /// Maps a simple type to an OpenAPI data type and format. + /// + /// Simple type. + /// + /// All the following types from http://swagger.io/specification/#data-types-12 are supported. + /// Other types including nullables and URL are also supported. + /// Common Name type format Comments + /// =========== ======= ====== ========================================= + /// integer integer int32 signed 32 bits + /// long integer int64 signed 64 bits + /// float number float + /// double number double + /// string string [empty] + /// byte string byte base64 encoded characters + /// binary string binary any sequence of octets + /// boolean boolean [empty] + /// date string date As defined by full-date - RFC3339 + /// dateTime string date-time As defined by date-time - RFC3339 + /// password string password Used to hint UIs the input needs to be obscured. + /// If the type is not recognized as "simple", System.String will be returned. + /// + public static OpenApiSchema MapTypeToOpenApiPrimitiveType(this Type type) + { + if (type == null) + { + throw new ArgumentNullException(nameof(type)); + } + + return _simpleTypeToOpenApiSchema.TryGetValue(type, out var result) + ? result() + : new OpenApiSchema { Type = "string" }; + } + } +} From 83db7027a2758b3a8a8215a9096e3209fc5d2737 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 1 Dec 2022 10:40:57 +0300 Subject: [PATCH 320/855] Add test and update public API interface --- .../Extensions/OpenApiTypeMapperTests.cs | 35 +++++++++++++++++++ .../PublicApi/PublicApi.approved.txt | 4 +++ 2 files changed, 39 insertions(+) create mode 100644 test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs diff --git a/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs b/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs new file mode 100644 index 000000000..450103e2c --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using FluentAssertions; +using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Models; +using Xunit; + +namespace Microsoft.OpenApi.Tests.Extensions +{ + public class OpenApiTypeMapperTests + { + [Theory] + [MemberData(nameof(PrimitiveTypeData))] + public void MapTypeToOpenApiPrimitiveTypeShouldSucceed(Type type, OpenApiSchema expected) + { + // Arrange & Act + var actual = OpenApiTypeMapper.MapTypeToOpenApiPrimitiveType(type); + + // Assert + actual.Should().BeEquivalentTo(expected); + } + + public static IEnumerable PrimitiveTypeData => new List + { + new object[] { typeof(int), new OpenApiSchema { Type = "integer", Format = "int32" } }, + new object[] { typeof(string), new OpenApiSchema { Type = "string" } }, + new object[] { typeof(double), new OpenApiSchema { Type = "number", Format = "double" } }, + new object[] { typeof(float?), new OpenApiSchema { Type = "number", Format = "float", Nullable = true } }, + new object[] { typeof(DateTimeOffset), new OpenApiSchema { Type = "string", Format = "date-time" } } + }; + } +} diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index b8646cae5..98ed35ecb 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -282,6 +282,10 @@ namespace Microsoft.OpenApi.Extensions public static void SerializeAsYaml(this T element, System.IO.Stream stream, Microsoft.OpenApi.OpenApiSpecVersion specVersion) where T : Microsoft.OpenApi.Interfaces.IOpenApiSerializable { } } + public static class OpenApiTypeMapper + { + public static Microsoft.OpenApi.Models.OpenApiSchema MapTypeToOpenApiPrimitiveType(this System.Type type) { } + } public static class StringExtensions { public static T GetEnumFromDisplayName(this string displayName) { } From f8678d3053564c2df1b6fe2aaa311a7da2eb08cc Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 5 Dec 2022 12:48:25 -0500 Subject: [PATCH 321/855] - adds missing validation methods Signed-off-by: Vincent Biret --- .../Microsoft.OpenApi.Readers.csproj | 2 +- .../Microsoft.OpenApi.csproj | 2 +- .../Validations/OpenApiValidator.cs | 96 ++++++++++++++++++- .../PublicApi/PublicApi.approved.txt | 18 ++++ 4 files changed, 115 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index defdfdd54..bcac9a7af 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.4.4 + 1.4.5 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 50d026f91..a938a968f 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.4 + 1.4.5 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index ba2ed4129..a0aee12e7 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -20,7 +20,7 @@ public class OpenApiValidator : OpenApiVisitorBase, IValidationContext private readonly IList _warnings = new List(); /// - /// Create a vistor that will validate an OpenAPIDocument + /// Create a visitor that will validate an OpenAPIDocument /// /// public OpenApiValidator(ValidationRuleSet ruleSet) @@ -198,6 +198,100 @@ public void AddWarning(OpenApiValidatorWarning warning) /// The object to be validated public override void Visit(IList items) => Validate(items, items.GetType()); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiPathItem item) => Validate(item); + + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiServerVariable item) => Validate(item); + + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiSecurityScheme item) => Validate(item); + + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiSecurityRequirement item) => Validate(item); + + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiRequestBody item) => Validate(item); + + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiPaths item) => Validate(item); + + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiLink item) => Validate(item); + + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiExample item) => Validate(item); + + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(OpenApiOperation item) => Validate(item); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(IDictionary item) => Validate(item, item.GetType()); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(IDictionary item) => Validate(item, item.GetType()); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(IDictionary item) => Validate(item, item.GetType()); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(IDictionary item) => Validate(item, item.GetType()); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(IDictionary item) => Validate(item, item.GetType()); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(IDictionary item) => Validate(item, item.GetType()); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(IDictionary item) => Validate(item, item.GetType()); + /// + /// Execute validation rules against a + /// + /// The object to be validated + public override void Visit(IDictionary item) => Validate(item, item.GetType()); + private void Validate(T item) { var type = typeof(T); diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index b8646cae5..5c84bfb2e 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1225,6 +1225,24 @@ namespace Microsoft.OpenApi.Validations public override void Visit(Microsoft.OpenApi.Models.OpenApiServer item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiTag item) { } public override void Visit(System.Collections.Generic.IList items) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiPathItem item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiServerVariable item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiSecurityScheme item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiSecurityRequirement item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiRequestBody item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiPaths item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiLink item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiExample item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiOperation item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } + } public class OpenApiValidatorError : Microsoft.OpenApi.Models.OpenApiError { From 2d9a007c24d0581a34857aa5dc14b6c06188e267 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 5 Dec 2022 13:15:27 -0500 Subject: [PATCH 322/855] - reorders public api definition Signed-off-by: Vincent Biret --- .../PublicApi/PublicApi.approved.txt | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 5c84bfb2e..9b4747312 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1212,37 +1212,36 @@ namespace Microsoft.OpenApi.Validations public override void Visit(Microsoft.OpenApi.Models.OpenApiContact item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiDocument item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiEncoding item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiExample item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiExternalDocs item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiHeader item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiInfo item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiLicense item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiLink item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiMediaType item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiOAuthFlow item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiOperation item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiParameter item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiPathItem item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiPaths item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiRequestBody item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiResponse item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiResponses item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiSchema item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiSecurityRequirement item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiSecurityScheme item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiServer item) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiTag item) { } - public override void Visit(System.Collections.Generic.IList items) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiPathItem item) { } public override void Visit(Microsoft.OpenApi.Models.OpenApiServerVariable item) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiSecurityScheme item) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiSecurityRequirement item) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiRequestBody item) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiPaths item) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiLink item) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiExample item) { } - public override void Visit(Microsoft.OpenApi.Models.OpenApiOperation item) { } + public override void Visit(Microsoft.OpenApi.Models.OpenApiTag item) { } public override void Visit(System.Collections.Generic.IDictionary item) { } - public override void Visit(System.Collections.Generic.IDictionary item) { } public override void Visit(System.Collections.Generic.IDictionary item) { } - public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } public override void Visit(System.Collections.Generic.IDictionary item) { } + public override void Visit(System.Collections.Generic.IDictionary item) { } public override void Visit(System.Collections.Generic.IDictionary item) { } - public override void Visit(System.Collections.Generic.IDictionary item) { } - + public override void Visit(System.Collections.Generic.IList items) { } } public class OpenApiValidatorError : Microsoft.OpenApi.Models.OpenApiError { From 9d5da501e4bf2ee1ae514c4417204d9a8f5dad62 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 5 Dec 2022 21:03:37 +0000 Subject: [PATCH 323/855] Bump Moq from 4.18.2 to 4.18.3 Bumps [Moq](https://github.com/moq/moq4) from 4.18.2 to 4.18.3. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/main/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/compare/v4.18.2...v4.18.3) --- updated-dependencies: - dependency-name: Moq dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index f450e2ff7..a864bc5e4 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -10,7 +10,7 @@ - + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 40f9eb637..b37500ccc 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -17,7 +17,7 @@ - + From 0b141fa92a0cebe4d056d00602a9158cbcfc84dd Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 6 Dec 2022 10:23:47 +0300 Subject: [PATCH 324/855] Map OpenApiSchema types to simple type and add test to validate --- .../Extensions/OpenApiTypeMapper.cs | 47 ++++++++++++++++++- .../Extensions/OpenApiTypeMapperTests.cs | 34 +++++++++++--- 2 files changed, 73 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs index 42b645b3a..ec7235271 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs @@ -42,7 +42,7 @@ public static class OpenApiTypeMapper [typeof(DateTimeOffset?)] = () => new OpenApiSchema { Type = "string", Format = "date-time", Nullable = true }, [typeof(Guid?)] = () => new OpenApiSchema { Type = "string", Format = "uuid", Nullable = true }, [typeof(char?)] = () => new OpenApiSchema { Type = "string", Nullable = true }, - + [typeof(Uri)] = () => new OpenApiSchema { Type = "string" }, // Uri is treated as simple string [typeof(string)] = () => new OpenApiSchema { Type = "string" }, [typeof(object)] = () => new OpenApiSchema { Type = "object" } @@ -81,5 +81,50 @@ public static OpenApiSchema MapTypeToOpenApiPrimitiveType(this Type type) ? result() : new OpenApiSchema { Type = "string" }; } + + /// + /// Maps an OpenAPI data type and format to a simple type. + /// + /// The OpenApi data type + /// The simple type + /// + public static Type MapOpenApiPrimitiveTypeToSimpleType(this OpenApiSchema schema) + { + if (schema == null) + { + throw new ArgumentNullException(nameof(schema)); + } + + var type = (schema.Type, schema.Format, schema.Nullable) switch + { + ("boolean", null, false) => typeof(bool), + ("integer", "int32", false) => typeof(int), + ("integer", "int64", false) => typeof(long), + ("number", "float", false) => typeof(float), + ("number", "double", false) => typeof(double), + ("number", "decimal", false) => typeof(decimal), + ("string", "byte", false) => typeof(byte), + ("string", "date-time", false) => typeof(DateTimeOffset), + ("string", "uuid", false) => typeof(Guid), + ("string", "duration", false) => typeof(TimeSpan), + ("string", "char", false) => typeof(char), + ("string", null, false) => typeof(string), + ("object", null, false) => typeof(object), + ("string", "uri", false) => typeof(Uri), + ("integer", "int32", true) => typeof(int?), + ("integer", "int64", true) => typeof(long?), + ("number", "float", true) => typeof(float?), + ("number", "double", true) => typeof(double?), + ("number", "decimal", true) => typeof(decimal?), + ("string", "byte", true) => typeof(byte?), + ("string", "date-time", true) => typeof(DateTimeOffset?), + ("string", "uuid", true) => typeof(Guid?), + ("string", "char", true) => typeof(char?), + ("boolean", null, true) => typeof(bool?), + _ => typeof(string), + }; + + return type; + } } } diff --git a/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs b/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs index 450103e2c..c2b6d9597 100644 --- a/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs +++ b/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs @@ -12,6 +12,24 @@ namespace Microsoft.OpenApi.Tests.Extensions { public class OpenApiTypeMapperTests { + public static IEnumerable PrimitiveTypeData => new List + { + new object[] { typeof(int), new OpenApiSchema { Type = "integer", Format = "int32" } }, + new object[] { typeof(string), new OpenApiSchema { Type = "string" } }, + new object[] { typeof(double), new OpenApiSchema { Type = "number", Format = "double" } }, + new object[] { typeof(float?), new OpenApiSchema { Type = "number", Format = "float", Nullable = true } }, + new object[] { typeof(DateTimeOffset), new OpenApiSchema { Type = "string", Format = "date-time" } } + }; + + public static IEnumerable OpenApiDataTypes => new List + { + new object[] { new OpenApiSchema { Type = "integer", Format = "int32"}, typeof(int) }, + new object[] { new OpenApiSchema { Type = "string" }, typeof(string) }, + new object[] { new OpenApiSchema { Type = "number", Format = "double" }, typeof(double) }, + new object[] { new OpenApiSchema { Type = "number", Format = "float", Nullable = true }, typeof(float?) }, + new object[] { new OpenApiSchema { Type = "string", Format = "date-time" }, typeof(DateTimeOffset) } + }; + [Theory] [MemberData(nameof(PrimitiveTypeData))] public void MapTypeToOpenApiPrimitiveTypeShouldSucceed(Type type, OpenApiSchema expected) @@ -23,13 +41,15 @@ public void MapTypeToOpenApiPrimitiveTypeShouldSucceed(Type type, OpenApiSchema actual.Should().BeEquivalentTo(expected); } - public static IEnumerable PrimitiveTypeData => new List + [Theory] + [MemberData(nameof(OpenApiDataTypes))] + public void MapOpenApiSchemaTypeToSimpleTypeShouldSucceed(OpenApiSchema schema, Type expected) { - new object[] { typeof(int), new OpenApiSchema { Type = "integer", Format = "int32" } }, - new object[] { typeof(string), new OpenApiSchema { Type = "string" } }, - new object[] { typeof(double), new OpenApiSchema { Type = "number", Format = "double" } }, - new object[] { typeof(float?), new OpenApiSchema { Type = "number", Format = "float", Nullable = true } }, - new object[] { typeof(DateTimeOffset), new OpenApiSchema { Type = "string", Format = "date-time" } } - }; + // Arrange & Act + var actual = OpenApiTypeMapper.MapOpenApiPrimitiveTypeToSimpleType(schema); + + // Assert + actual.Should().Be(expected); + } } } From 043a592724cc9fe42c4c8d0e99ab0965c11ad7bb Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 6 Dec 2022 10:44:11 +0300 Subject: [PATCH 325/855] Fixes bug where the schema copy constructor would run into a stack overflow due to wrong copying of AdditionalProperties object --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 6019d7362..513b865df 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -280,7 +280,7 @@ public OpenApiSchema(OpenApiSchema schema) MaxProperties = schema?.MaxProperties ?? MaxProperties; MinProperties = schema?.MinProperties ?? MinProperties; AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? AdditionalPropertiesAllowed; - AdditionalProperties = new(schema?.AdditionalProperties); + AdditionalProperties = schema?.AdditionalProperties != null ? new(schema?.AdditionalProperties) : null; Discriminator = schema?.Discriminator != null ? new(schema?.Discriminator) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema?.Example); Enum = schema?.Enum != null ? new List(schema.Enum) : null; From 8f874266b97222d89c4fa3128d56d520c73416df Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 6 Dec 2022 10:44:49 +0300 Subject: [PATCH 326/855] Add test to validate --- .../Models/OpenApiSchemaTests.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index 429129c1e..fd6fea2cb 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -463,5 +463,22 @@ public void SerializeAsV2ShouldSetFormatPropertyInParentSchemaIfPresentInChildre // Assert Assert.Equal(expectedV2Schema, v2Schema); } + + [Fact] + public void OpenApiSchemaCopyConstructorSucceeds() + { + var baseSchema = new OpenApiSchema() + { + Type = "string", + Format = "date" + }; + + var actualSchema = new OpenApiSchema(baseSchema) + { + Nullable = true + }; + + Assert.Equal("string", actualSchema.Type); + } } } From 1dae8dc97198486032006bfce09c6402f1fd18a7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 6 Dec 2022 10:46:56 +0300 Subject: [PATCH 327/855] Add test assertions --- test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index fd6fea2cb..447d01337 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -479,6 +479,8 @@ public void OpenApiSchemaCopyConstructorSucceeds() }; Assert.Equal("string", actualSchema.Type); + Assert.Equal("date", actualSchema.Format); + Assert.True(actualSchema.Nullable); } } } From dca31513f5dafa879c2a0b36fe85dc174faa2b1e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 6 Dec 2022 17:42:48 +0300 Subject: [PATCH 328/855] Update Uri format --- src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs index ec7235271..d8023b4cb 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs @@ -43,7 +43,7 @@ public static class OpenApiTypeMapper [typeof(Guid?)] = () => new OpenApiSchema { Type = "string", Format = "uuid", Nullable = true }, [typeof(char?)] = () => new OpenApiSchema { Type = "string", Nullable = true }, - [typeof(Uri)] = () => new OpenApiSchema { Type = "string" }, // Uri is treated as simple string + [typeof(Uri)] = () => new OpenApiSchema { Type = "string", Format = "uri"}, // Uri is treated as simple string [typeof(string)] = () => new OpenApiSchema { Type = "string" }, [typeof(object)] = () => new OpenApiSchema { Type = "object" } }; From 2ad17ba74a3604f405b490a201c17e74966908a9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 6 Dec 2022 18:00:16 +0300 Subject: [PATCH 329/855] Update type and format to lowercase --- src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs index d8023b4cb..16441a9e7 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs @@ -95,7 +95,7 @@ public static Type MapOpenApiPrimitiveTypeToSimpleType(this OpenApiSchema schema throw new ArgumentNullException(nameof(schema)); } - var type = (schema.Type, schema.Format, schema.Nullable) switch + var type = (schema.Type?.ToLowerInvariant(), schema.Format.ToLowerInvariant(), schema.Nullable) switch { ("boolean", null, false) => typeof(bool), ("integer", "int32", false) => typeof(int), From 0b4110aa9d296a220ce3516eb94949655d614cdf Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 6 Dec 2022 19:01:56 +0300 Subject: [PATCH 330/855] Fix failing tests --- src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs | 2 +- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs index 16441a9e7..970b3a976 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs @@ -95,7 +95,7 @@ public static Type MapOpenApiPrimitiveTypeToSimpleType(this OpenApiSchema schema throw new ArgumentNullException(nameof(schema)); } - var type = (schema.Type?.ToLowerInvariant(), schema.Format.ToLowerInvariant(), schema.Nullable) switch + var type = (schema.Type?.ToLowerInvariant(), schema.Format?.ToLowerInvariant(), schema.Nullable) switch { ("boolean", null, false) => typeof(bool), ("integer", "int32", false) => typeof(int), diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 98ed35ecb..5aaa55b19 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -284,6 +284,7 @@ namespace Microsoft.OpenApi.Extensions } public static class OpenApiTypeMapper { + public static System.Type MapOpenApiPrimitiveTypeToSimpleType(this Microsoft.OpenApi.Models.OpenApiSchema schema) { } public static Microsoft.OpenApi.Models.OpenApiSchema MapTypeToOpenApiPrimitiveType(this System.Type type) { } } public static class StringExtensions From 1a7392f64c1586286526945fe9d3c00b684f8fa2 Mon Sep 17 00:00:00 2001 From: Irvine Sunday <40403681+irvinesunday@users.noreply.github.com> Date: Thu, 8 Dec 2022 15:03:18 +0300 Subject: [PATCH 331/855] Serialize `OpenApiDate` values properly to short date (#1102) * Serialize OpenApiDate properly as Date * Change test date value Using value 01/01/0001 could be represented as 1/1/0001 in a machine using a different regional format, and thus cause the test to fail --- src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs | 2 +- ...ithoutReferenceWorks_produceTerseOutput=False.verified.txt | 3 ++- ...WithoutReferenceWorks_produceTerseOutput=True.verified.txt | 2 +- test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs | 4 +++- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs index e0abda167..bd6db956a 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -118,7 +118,7 @@ public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) case PrimitiveType.Date: var dateValue = (OpenApiDate)(IOpenApiPrimitive)this; - writer.WriteValue(dateValue.Value); + writer.WriteValue(dateValue.Value.ToShortDateString()); break; case PrimitiveType.DateTime: diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt index 45f085f73..868b45156 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt @@ -21,6 +21,7 @@ } ] } - ] + ], + "aDate": "12/12/2022" } } \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt index b503d318e..7ab9ad1d6 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"value":{"versions":[{"status":"Status1","id":"v1","links":[{"href":"http://example.com/1","rel":"sampleRel1"}]},{"status":"Status2","id":"v2","links":[{"href":"http://example.com/2","rel":"sampleRel2"}]}]}} \ No newline at end of file +{"value":{"versions":[{"status":"Status1","id":"v1","links":[{"href":"http://example.com/1","rel":"sampleRel1"}]},{"status":"Status2","id":"v2","links":[{"href":"http://example.com/2","rel":"sampleRel2"}]}],"aDate":"12/12/2022"}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs index 6108c3c26..d42d65ce7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Globalization; using System.IO; using System.Text; @@ -95,7 +96,8 @@ public class OpenApiExampleTests } } } - } + }, + ["aDate"] = new OpenApiDate(DateTime.Parse("12/12/2022 00:00:00")) } }; From 48a809e987a1331263d460d711e4f7955281892f Mon Sep 17 00:00:00 2001 From: Roman Kolesnikov Date: Fri, 9 Dec 2022 17:06:07 +0100 Subject: [PATCH 332/855] check Extensions object for null using Microsoft.OpenApi.OData package it generates OpenApi document with OpenApiComponents.Extensions == null --- src/Microsoft.OpenApi/Services/OpenApiWalker.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index 78ca5e61b..8c469261c 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -274,7 +274,7 @@ internal void Walk(IOpenApiExtensible openApiExtensible) _visitor.Visit(openApiExtensible); - if (openApiExtensible != null) + if (openApiExtensible.Extensions != null) { foreach (var item in openApiExtensible.Extensions) { From e971a7a3dac3de006a26a0afe4c2d6f79253b8fe Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Dec 2022 21:01:34 +0000 Subject: [PATCH 333/855] Bump Microsoft.OData.Edm from 7.12.5 to 7.13.0 Bumps Microsoft.OData.Edm from 7.12.5 to 7.13.0. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index aba953065..3ba1aa4ed 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From 74db9654796f39072111b415ce214e03c8301461 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 14 Dec 2022 12:06:14 +0300 Subject: [PATCH 334/855] Enable termination of transform process --- src/Microsoft.OpenApi.Hidi/Program.cs | 35 +++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 71e9e0d00..f8934a0f4 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -1,15 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.CommandLine; -using System.CommandLine.Builder; -using System.CommandLine.Hosting; using System.CommandLine.Parsing; - +using System.Diagnostics; using System.IO; +using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Hidi.Handlers; @@ -19,6 +17,9 @@ static class Program { static async Task Main(string[] args) { + // subscribe to CancelKeyPress event to listen for termination requests from users through Ctrl+C or Ctrl+Break keys + Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPressEvent); + var rootCommand = new RootCommand() { }; @@ -127,5 +128,29 @@ static async Task Main(string[] args) //// Wait for logger to write messages to the console before exiting await Task.Delay(10); } + + /// + /// This event is raised when the user presses either of the two breaking key combinations: Ctrl+C or Ctrl+Break keys. + /// + /// + /// + private static void Console_CancelKeyPressEvent(object sender, ConsoleCancelEventArgs eventArgs) + { + if ((eventArgs.SpecialKey == ConsoleSpecialKey.ControlC) || (eventArgs.SpecialKey == ConsoleSpecialKey.ControlBreak)) + { + Console.WriteLine("CTRL+C pressed, aborting current process..."); + Thread.Sleep(5000); + + if (Process.GetCurrentProcess().HasExited) + { + Console.WriteLine("Process has already exited."); + } + else + { + Console.WriteLine("Process has not exited, attempting to kill process..."); + Process.GetCurrentProcess().Kill(); + } + } + } } } From 49158bef07fd32f9c9e943ea0444dbbe34bde344 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 15 Dec 2022 21:01:54 +0000 Subject: [PATCH 335/855] Bump Microsoft.OpenApi.OData from 1.2.0-preview8 to 1.2.0-preview9 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.2.0-preview8 to 1.2.0-preview9. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 3ba1aa4ed..e27a214d5 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 07f0edfb169415a410f0fb44850243997c002af5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 16 Dec 2022 21:04:52 +0000 Subject: [PATCH 336/855] Bump Microsoft.NET.Test.Sdk from 17.4.0 to 17.4.1 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.4.0 to 17.4.1. - [Release notes](https://github.com/microsoft/vstest/releases) - [Changelog](https://github.com/microsoft/vstest/blob/main/docs/releases.md) - [Commits](https://github.com/microsoft/vstest/compare/v17.4.0...v17.4.1) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 0902ff177..4d052a56c 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -13,7 +13,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 8fb35ee88..1e46b43bf 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -261,7 +261,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 0fab323f7..8e0f1a398 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -16,7 +16,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 5f6d0c748..8add64e36 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -24,7 +24,7 @@ all - + From 7867fdd569c13969fe34345c9a81f09133a7adde Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 19 Dec 2022 13:46:34 +0300 Subject: [PATCH 337/855] Use an IConsole instance to register and handle cancellation when CTRL+C is pressed --- src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index 696837d3f..c0af09728 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -50,6 +50,8 @@ public async Task InvokeAsync(InvocationContext context) string filterbyoperationids = context.ParseResult.GetValueForOption(FilterByOperationIdsOption); string filterbytags = context.ParseResult.GetValueForOption(FilterByTagsOption); string filterbycollection = context.ParseResult.GetValueForOption(FilterByCollectionOption); + + var console = context.Console; CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken)); using var loggerFactory = Logger.ConfigureLogger(logLevel); From 6c1e502616c4338e17f7d818d802b66a6220599a Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 19 Dec 2022 13:47:32 +0300 Subject: [PATCH 338/855] Pass cancellation token to the conversion method and degrade gracefully when an operation is terminated --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 56dda4d9a..dbcdf5457 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -102,7 +102,7 @@ CancellationToken cancellationToken stream.Position = 0; } - document = await ConvertCsdlToOpenApi(stream, settingsFile); + document = await ConvertCsdlToOpenApi(stream, cancellationToken, settingsFile); stopwatch.Stop(); logger.LogTrace("{timestamp}ms: Generated OpenAPI with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); } @@ -216,6 +216,10 @@ CancellationToken cancellationToken textWriter.Flush(); } } + catch(TaskCanceledException) + { + Console.Error.WriteLine("CTRL+C pressed, aborting the operation."); + } catch (Exception ex) { throw new InvalidOperationException($"Could not transform the document, reason: {ex.Message}", ex); @@ -324,12 +328,12 @@ internal static IConfiguration GetConfiguration(string settingsFile) /// /// The CSDL stream. /// An OpenAPI document. - public static async Task ConvertCsdlToOpenApi(Stream csdl, string settingsFile = null) + public static async Task ConvertCsdlToOpenApi(Stream csdl, CancellationToken token, string settingsFile = null) { using var reader = new StreamReader(csdl); - var csdlText = await reader.ReadToEndAsync(); + var csdlText = await reader.ReadToEndAsync(token); var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader()); - + var config = GetConfiguration(settingsFile); var settings = new OpenApiConvertSettings() { @@ -353,9 +357,8 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl, stri EnableTypeDisambiguationForDefaultValueOfOdataTypeProperty = true }; config.GetSection("OpenApiConvertSettings").Bind(settings); - - OpenApiDocument document = edmModel.ConvertToOpenApi(settings); + OpenApiDocument document = edmModel.ConvertToOpenApi(settings); document = FixReferences(document); return document; From 5d8ef7f208fd379693b57b570915bce05aea69b1 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 19 Dec 2022 13:47:44 +0300 Subject: [PATCH 339/855] Clean up code --- src/Microsoft.OpenApi.Hidi/Program.cs | 34 +++------------------------ 1 file changed, 3 insertions(+), 31 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index f8934a0f4..e9246eb6c 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -16,12 +16,8 @@ namespace Microsoft.OpenApi.Hidi static class Program { static async Task Main(string[] args) - { - // subscribe to CancelKeyPress event to listen for termination requests from users through Ctrl+C or Ctrl+Break keys - Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPressEvent); - - var rootCommand = new RootCommand() { - }; + { + var rootCommand = new RootCommand() {}; // command option parameters and aliases var descriptionOption = new Option("--openapi", "Input OpenAPI description file path or URL"); @@ -121,36 +117,12 @@ static async Task Main(string[] args) rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); - + // Parse the incoming args and invoke the handler await rootCommand.InvokeAsync(args); //// Wait for logger to write messages to the console before exiting await Task.Delay(10); - } - - /// - /// This event is raised when the user presses either of the two breaking key combinations: Ctrl+C or Ctrl+Break keys. - /// - /// - /// - private static void Console_CancelKeyPressEvent(object sender, ConsoleCancelEventArgs eventArgs) - { - if ((eventArgs.SpecialKey == ConsoleSpecialKey.ControlC) || (eventArgs.SpecialKey == ConsoleSpecialKey.ControlBreak)) - { - Console.WriteLine("CTRL+C pressed, aborting current process..."); - Thread.Sleep(5000); - - if (Process.GetCurrentProcess().HasExited) - { - Console.WriteLine("Process has already exited."); - } - else - { - Console.WriteLine("Process has not exited, attempting to kill process..."); - Process.GetCurrentProcess().Kill(); - } - } } } } From 05256ddbc71359739b845bc71dd315f44bb50a57 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 19 Dec 2022 14:01:37 +0300 Subject: [PATCH 340/855] Fix failing tests --- .../Services/OpenApiServiceTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index c2fb3798f..70b222750 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -20,7 +20,7 @@ public async Task ReturnConvertedCSDLFile() var csdlStream = fileInput.OpenRead(); // Act - var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream); + var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream, CancellationToken.None); var expectedPathCount = 5; // Assert @@ -39,9 +39,9 @@ public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocumen var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UtilityFiles\\Todo.xml"); var fileInput = new FileInfo(filePath); var csdlStream = fileInput.OpenRead(); - + // Act - var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream); + var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream, CancellationToken.None); var predicate = OpenApiFilterService.CreatePredicate(operationIds, tags); var subsetOpenApiDocument = OpenApiFilterService.CreateFilteredDocument(openApiDoc, predicate); From 214774b07889286f9019830465a9fbd8a8696450 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 19 Dec 2022 08:18:17 -0500 Subject: [PATCH 341/855] Update src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs --- src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index c0af09728..e46b34340 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -51,7 +51,6 @@ public async Task InvokeAsync(InvocationContext context) string filterbytags = context.ParseResult.GetValueForOption(FilterByTagsOption); string filterbycollection = context.ParseResult.GetValueForOption(FilterByCollectionOption); - var console = context.Console; CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken)); using var loggerFactory = Logger.ConfigureLogger(logLevel); From 4a163a6ea3701734989ad270d7e5071e95c5317e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 19 Dec 2022 19:12:18 +0300 Subject: [PATCH 342/855] Code clean up --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 4 ++-- .../Services/OpenApiServiceTests.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index dbcdf5457..60bba4aef 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -102,7 +102,7 @@ CancellationToken cancellationToken stream.Position = 0; } - document = await ConvertCsdlToOpenApi(stream, cancellationToken, settingsFile); + document = await ConvertCsdlToOpenApi(stream, settingsFile, cancellationToken); stopwatch.Stop(); logger.LogTrace("{timestamp}ms: Generated OpenAPI with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); } @@ -328,7 +328,7 @@ internal static IConfiguration GetConfiguration(string settingsFile) /// /// The CSDL stream. /// An OpenAPI document. - public static async Task ConvertCsdlToOpenApi(Stream csdl, CancellationToken token, string settingsFile = null) + public static async Task ConvertCsdlToOpenApi(Stream csdl, string settingsFile = null, CancellationToken token = default) { using var reader = new StreamReader(csdl); var csdlText = await reader.ReadToEndAsync(token); diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 70b222750..3d764b4fb 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -20,7 +20,7 @@ public async Task ReturnConvertedCSDLFile() var csdlStream = fileInput.OpenRead(); // Act - var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream, CancellationToken.None); + var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream); var expectedPathCount = 5; // Assert @@ -41,7 +41,7 @@ public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocumen var csdlStream = fileInput.OpenRead(); // Act - var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream, CancellationToken.None); + var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream); var predicate = OpenApiFilterService.CreatePredicate(operationIds, tags); var subsetOpenApiDocument = OpenApiFilterService.CreateFilteredDocument(openApiDoc, predicate); From f205c36a0a15b7aadc96b2a238a2ba6c6c79e0db Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 19 Dec 2022 21:03:05 +0000 Subject: [PATCH 343/855] Bump Verify.Xunit from 19.3.0 to 19.5.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.3.0 to 19.5.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.3.0...19.5.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 8add64e36..66f9e5bec 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 48fbe511f00bff69ea09228e6ec1f83b83a934ee Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 30 Dec 2022 21:01:29 +0000 Subject: [PATCH 344/855] Bump Moq from 4.18.3 to 4.18.4 Bumps [Moq](https://github.com/moq/moq4) from 4.18.3 to 4.18.4. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/main/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/compare/v4.18.3...v4.18.4) --- updated-dependencies: - dependency-name: Moq dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 4d052a56c..578cdc9e3 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -14,7 +14,7 @@ all - + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 66f9e5bec..7edbf969f 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -25,7 +25,7 @@ - + From 006bcf26860eebb93ffd0ce080e01be9cbb3b3d1 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 31 Dec 2022 22:57:20 +1100 Subject: [PATCH 345/855] verify string writer --- .../Models/OpenApiCallbackTests.cs | 9 +++---- .../Models/OpenApiDocumentTests.cs | 18 +++++--------- .../Models/OpenApiExampleTests.cs | 9 +++---- .../Models/OpenApiHeaderTests.cs | 17 +++++-------- .../Models/OpenApiLinkTests.cs | 9 +++---- .../Models/OpenApiParameterTests.cs | 24 +++++++------------ .../Models/OpenApiRequestBodyTests.cs | 9 +++---- .../Models/OpenApiResponseTests.cs | 12 ++++------ .../Models/OpenApiSchemaTests.cs | 9 +++---- .../Models/OpenApiSecuritySchemeTests.cs | 6 ++--- .../Models/OpenApiTagTests.cs | 24 +++++++------------ 11 files changed, 49 insertions(+), 97 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs index 9d512566f..93b78e71b 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs @@ -117,10 +117,9 @@ public async Task SerializeAdvancedCallbackAsV3JsonWorks(bool produceTerseOutput // Act AdvancedCallback.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -135,10 +134,9 @@ public async Task SerializeReferencedCallbackAsV3JsonWorks(bool produceTerseOutp // Act ReferencedCallback.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -153,10 +151,9 @@ public async Task SerializeReferencedCallbackAsV3JsonWithoutReferenceWorks(bool // Act ReferencedCallback.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 8633bdbaf..c4876db7a 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -999,10 +999,9 @@ public async Task SerializeAdvancedDocumentAsV3JsonWorks(bool produceTerseOutput // Act AdvancedDocument.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -1017,10 +1016,9 @@ public async Task SerializeAdvancedDocumentWithReferenceAsV3JsonWorks(bool produ // Act AdvancedDocumentWithReference.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -1035,10 +1033,9 @@ public async Task SerializeAdvancedDocumentAsV2JsonWorks(bool produceTerseOutput // Act AdvancedDocument.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -1053,10 +1050,9 @@ public async Task SerializeDuplicateExtensionsAsV3JsonWorks(bool produceTerseOut // Act DuplicateExtensions.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -1071,10 +1067,9 @@ public async Task SerializeDuplicateExtensionsAsV2JsonWorks(bool produceTerseOut // Act DuplicateExtensions.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -1089,10 +1084,9 @@ public async Task SerializeAdvancedDocumentWithReferenceAsV2JsonWorks(bool produ // Act AdvancedDocumentWithReference.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Fact] diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs index d42d65ce7..e12a7d100 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs @@ -120,10 +120,9 @@ public async Task SerializeAdvancedExampleAsV3JsonWorks(bool produceTerseOutput) // Act AdvancedExample.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -138,10 +137,9 @@ public async Task SerializeReferencedExampleAsV3JsonWorks(bool produceTerseOutpu // Act ReferencedExample.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -156,10 +154,9 @@ public async Task SerializeReferencedExampleAsV3JsonWithoutReferenceWorks(bool p // Act ReferencedExample.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs index 846d470ba..d45bd0038 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs @@ -60,10 +60,9 @@ public async Task SerializeAdvancedHeaderAsV3JsonWorks(bool produceTerseOutput) // Act AdvancedHeader.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -78,10 +77,9 @@ public async Task SerializeReferencedHeaderAsV3JsonWorks(bool produceTerseOutput // Act ReferencedHeader.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -99,7 +97,7 @@ public async Task SerializeReferencedHeaderAsV3JsonWithoutReferenceWorks(bool pr var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -114,10 +112,9 @@ public async Task SerializeAdvancedHeaderAsV2JsonWorks(bool produceTerseOutput) // Act AdvancedHeader.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -132,10 +129,9 @@ public async Task SerializeReferencedHeaderAsV2JsonWorks(bool produceTerseOutput // Act ReferencedHeader.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -150,10 +146,9 @@ public async Task SerializeReferencedHeaderAsV2JsonWithoutReferenceWorks(bool pr // Act ReferencedHeader.SerializeAsV2WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs index 4e439a2a8..4a10be0ae 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs @@ -90,10 +90,9 @@ public async Task SerializeAdvancedLinkAsV3JsonWorksAsync(bool produceTerseOutpu // Act AdvancedLink.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -108,10 +107,9 @@ public async Task SerializeReferencedLinkAsV3JsonWorksAsync(bool produceTerseOut // Act ReferencedLink.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -126,10 +124,9 @@ public async Task SerializeReferencedLinkAsV3JsonWithoutReferenceWorksAsync(bool // Act ReferencedLink.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index 2f57673af..2a2c65202 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs @@ -299,10 +299,9 @@ public async Task SerializeReferencedParameterAsV3JsonWorksAsync(bool produceTer // Act ReferencedParameter.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -317,10 +316,9 @@ public async Task SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync // Act ReferencedParameter.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -335,10 +333,9 @@ public async Task SerializeReferencedParameterAsV2JsonWorksAsync(bool produceTer // Act ReferencedParameter.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -353,10 +350,9 @@ public async Task SerializeReferencedParameterAsV2JsonWithoutReferenceWorksAsync // Act ReferencedParameter.SerializeAsV2WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -371,10 +367,9 @@ public async Task SerializeParameterWithSchemaReferenceAsV2JsonWorksAsync(bool p // Act AdvancedHeaderParameterWithSchemaReference.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -389,10 +384,9 @@ public async Task SerializeParameterWithSchemaTypeObjectAsV2JsonWorksAsync(bool // Act AdvancedHeaderParameterWithSchemaTypeObject.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -407,10 +401,9 @@ public async Task SerializeParameterWithFormStyleAndExplodeFalseWorksAsync(bool // Act ParameterWithFormStyleAndExplodeFalse.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -425,10 +418,9 @@ public async Task SerializeParameterWithFormStyleAndExplodeTrueWorksAsync(bool p // Act ParameterWithFormStyleAndExplodeTrue.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs index d8bdacae4..78fcd0d07 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs @@ -72,10 +72,9 @@ public async Task SerializeAdvancedRequestBodyAsV3JsonWorksAsync(bool produceTer // Act AdvancedRequestBody.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -90,10 +89,9 @@ public async Task SerializeReferencedRequestBodyAsV3JsonWorksAsync(bool produceT // Act ReferencedRequestBody.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -108,10 +106,9 @@ public async Task SerializeReferencedRequestBodyAsV3JsonWithoutReferenceWorksAsy // Act ReferencedRequestBody.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs index a5555ddd9..0010e8cb6 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs @@ -294,10 +294,9 @@ public async Task SerializeReferencedResponseAsV3JsonWorksAsync(bool produceTers // Act ReferencedResponse.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -312,10 +311,9 @@ public async Task SerializeReferencedResponseAsV3JsonWithoutReferenceWorksAsync( // Act ReferencedResponse.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -330,10 +328,9 @@ public async Task SerializeReferencedResponseAsV2JsonWorksAsync(bool produceTers // Act ReferencedResponse.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -348,10 +345,9 @@ public async Task SerializeReferencedResponseAsV2JsonWithoutReferenceWorksAsync( // Act ReferencedResponse.SerializeAsV2WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index 447d01337..e4078f2f7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -381,10 +381,9 @@ public async Task SerializeReferencedSchemaAsV3WithoutReferenceJsonWorksAsync(bo // Act ReferencedSchema.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -399,10 +398,9 @@ public async Task SerializeReferencedSchemaAsV3JsonWorksAsync(bool produceTerseO // Act ReferencedSchema.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -417,10 +415,9 @@ public async Task SerializeSchemaWRequiredPropertiesAsV2JsonWorksAsync(bool prod // Act AdvancedSchemaWithRequiredPropertiesObject.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Fact] diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs index 1294f0f48..44a388d90 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs @@ -318,10 +318,9 @@ public async Task SerializeReferencedSecuritySchemeAsV3JsonWorksAsync(bool produ writer.WriteNull(); writer.WriteEndObject(); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -336,10 +335,9 @@ public async Task SerializeReferencedSecuritySchemeAsV3JsonWithoutReferenceWorks // Act ReferencedSecurityScheme.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs index 7e837bd52..66c0dfd70 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs @@ -60,10 +60,9 @@ public async Task SerializeBasicTagAsV3JsonWithoutReferenceWorksAsync(bool produ // Act BasicTag.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -78,10 +77,9 @@ public async Task SerializeBasicTagAsV2JsonWithoutReferenceWorksAsync(bool produ // Act BasicTag.SerializeAsV2WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Fact] @@ -133,10 +131,9 @@ public async Task SerializeAdvancedTagAsV3JsonWithoutReferenceWorksAsync(bool pr // Act AdvancedTag.SerializeAsV3WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -151,10 +148,9 @@ public async Task SerializeAdvancedTagAsV2JsonWithoutReferenceWorksAsync(bool pr // Act AdvancedTag.SerializeAsV2WithoutReference(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Fact] @@ -219,10 +215,9 @@ public async Task SerializeAdvancedTagAsV3JsonWorksAsync(bool produceTerseOutput // Act AdvancedTag.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -237,10 +232,9 @@ public async Task SerializeAdvancedTagAsV2JsonWorksAsync(bool produceTerseOutput // Act AdvancedTag.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Fact] @@ -295,10 +289,9 @@ public async Task SerializeReferencedTagAsV3JsonWorksAsync(bool produceTerseOutp // Act ReferencedTag.SerializeAsV3(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Theory] @@ -313,10 +306,9 @@ public async Task SerializeReferencedTagAsV2JsonWorksAsync(bool produceTerseOutp // Act ReferencedTag.SerializeAsV2(writer); writer.Flush(); - var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert - await Verifier.Verify(actual).UseParameters(produceTerseOutput); + await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } [Fact] From e5170530affd8494756f4e5f90ef7004c8b79135 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Thu, 22 Dec 2022 22:54:07 -0500 Subject: [PATCH 346/855] Added show command --- .../Handlers/ShowCommandHandler.cs | 51 ++++++++ src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 114 ++++++++++++++++++ src/Microsoft.OpenApi.Hidi/Program.cs | 16 +++ src/Microsoft.OpenApi.Hidi/readme.md | 32 +++-- 4 files changed, 204 insertions(+), 9 deletions(-) create mode 100644 src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs new file mode 100644 index 000000000..e6542c34a --- /dev/null +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.CommandLine; +using System.CommandLine.Invocation; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace Microsoft.OpenApi.Hidi.Handlers +{ + internal class ShowCommandHandler : ICommandHandler + { + public Option DescriptionOption { get; set; } + public Option OutputOption { get; set; } + public Option LogLevelOption { get; set; } + + public int Invoke(InvocationContext context) + { + return InvokeAsync(context).GetAwaiter().GetResult(); + } + public async Task InvokeAsync(InvocationContext context) + { + string openapi = context.ParseResult.GetValueForOption(DescriptionOption); + FileInfo output = context.ParseResult.GetValueForOption(OutputOption); + LogLevel logLevel = context.ParseResult.GetValueForOption(LogLevelOption); + CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken)); + + using var loggerFactory = Logger.ConfigureLogger(logLevel); + var logger = loggerFactory.CreateLogger(); + try + { + await OpenApiService.ShowOpenApiDocument(openapi, output, logLevel, cancellationToken); + + return 0; + } + catch (Exception ex) + { +#if DEBUG + logger.LogCritical(ex, ex.Message); + throw; // so debug tools go straight to the source of the exception when attached +#else + logger.LogCritical( ex.Message); + return 1; +#endif + } + } + } +} diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 60bba4aef..a1f95a63d 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -535,5 +535,119 @@ private static ILoggerFactory ConfigureLoggerInstance(LogLevel loglevel) .SetMinimumLevel(loglevel); }); } + + internal static async Task ShowOpenApiDocument(string openapi, FileInfo output, LogLevel logLevel, CancellationToken cancellationToken) + { + using var loggerFactory = Logger.ConfigureLogger(logLevel); + var logger = loggerFactory.CreateLogger(); + try + { + if (string.IsNullOrEmpty(openapi)) + { + throw new ArgumentNullException(nameof(openapi)); + } + var stream = await GetStream(openapi, logger, cancellationToken); + + OpenApiDocument document; + Stopwatch stopwatch = Stopwatch.StartNew(); + using (logger.BeginScope($"Parsing OpenAPI: {openapi}", openapi)) + { + stopwatch.Start(); + + var result = await new OpenApiStreamReader(new OpenApiReaderSettings + { + RuleSet = ValidationRuleSet.GetDefaultRuleSet() + } + ).ReadAsync(stream); + + logger.LogTrace("{timestamp}ms: Completed parsing.", stopwatch.ElapsedMilliseconds); + + document = result.OpenApiDocument; + var context = result.OpenApiDiagnostic; + if (context.Errors.Count != 0) + { + using (logger.BeginScope("Detected errors")) + { + foreach (var error in context.Errors) + { + logger.LogError(error.ToString()); + } + } + } + stopwatch.Stop(); + } + + using (logger.BeginScope("Creating diagram")) + { + // Create OpenApiUrlTree from document + + using var file = new FileStream(output.FullName, FileMode.Create); + var writer = new StreamWriter(file); + WriteTreeDocument(openapi, document, writer); + writer.Flush(); + + logger.LogTrace("Finished walking through the OpenApi document. "); + } + } + catch (Exception ex) + { + throw new InvalidOperationException($"Could not generate the document, reason: {ex.Message}", ex); + } + } + + private static void WriteTreeDocument(string openapi, OpenApiDocument document, StreamWriter writer) + { + var rootNode = OpenApiUrlTreeNode.Create(document, "main"); + + writer.WriteLine("# " + document.Info.Title); + writer.WriteLine(); + writer.WriteLine("OpenAPI: " + openapi); + writer.Write(@"
+GET +POST +GET POST +GET PATCH DELETE +GET PUT DELETE +GET DELETE +DELETE +
+"); + writer.WriteLine(); + writer.WriteLine("```mermaid"); + writer.WriteLine("graph LR"); + writer.WriteLine("classDef GET fill:lightSteelBlue,stroke:#333,stroke-width:2px;"); + writer.WriteLine("classDef POST fill:SteelBlue,stroke:#333,stroke-width:2px;"); + writer.WriteLine("classDef GETPOST fill:forestGreen,stroke:#333,stroke-width:2px;"); + writer.WriteLine("classDef DELETEGETPATCH fill:yellowGreen,stroke:#333,stroke-width:2px;"); + writer.WriteLine("classDef DELETEGETPUT fill:olive,stroke:#333,stroke-width:2px;"); + writer.WriteLine("classDef DELETEGET fill:DarkSeaGreen,stroke:#333,stroke-width:2px;"); + writer.WriteLine("classDef DELETE fill:tomato,stroke:#333,stroke-width:2px;"); + writer.WriteLine("classDef OTHER fill:white,stroke:#333,stroke-width:2px;"); + + ProcessNode(rootNode, writer); + writer.WriteLine("```"); + } + + private static void ProcessNode(OpenApiUrlTreeNode node, StreamWriter writer) + { + var path = string.IsNullOrEmpty(node.Path) ? "/" : Sanitize(node.Path); + foreach (var child in node.Children) + { + writer.WriteLine($"{Sanitize(path)} --> {Sanitize(child.Value.Path)}[{Sanitize(child.Key)}]"); + ProcessNode(child.Value, writer); + } + var methods = String.Join("", node.PathItems.SelectMany(p => p.Value.Operations.Select(o => o.Key)) + .Distinct() + .Select(o => o.ToString().ToUpper()) + .OrderBy(o => o) + .ToList()); + if (String.IsNullOrEmpty(methods)) methods = "OTHER"; + writer.WriteLine($"class {path} {methods}"); + } + + private static string Sanitize(string token) + { + return token.Replace("\\", "/").Replace("{", ":").Replace("}", ""); + } } } diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index e9246eb6c..b9db1229f 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -115,6 +115,22 @@ static async Task Main(string[] args) InlineExternalOption = inlineExternalOption }; + var showCommand = new Command("show") + { + descriptionOption, + logLevelOption, + outputOption, + cleanOutputOption + }; + + showCommand.Handler = new ShowCommandHandler + { + DescriptionOption = descriptionOption, + OutputOption = outputOption, + LogLevelOption = logLevelOption + }; + + rootCommand.Add(showCommand); rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); diff --git a/src/Microsoft.OpenApi.Hidi/readme.md b/src/Microsoft.OpenApi.Hidi/readme.md index 6295c5c99..a6283817e 100644 --- a/src/Microsoft.OpenApi.Hidi/readme.md +++ b/src/Microsoft.OpenApi.Hidi/readme.md @@ -1,24 +1,26 @@ -# Overview +# Overview Hidi is a command line tool that makes it easy to work with and transform OpenAPI documents. The tool enables you validate and apply transformations to and from different file formats using various commands to do different actions on the files. ## Capabilities + Hidi has these key capabilities that enable you to build different scenarios off the tool • Validation of OpenAPI files • Conversion of OpenAPI files into different file formats: convert files from JSON to YAML, YAML to JSON • Slice or filter OpenAPI documents to smaller subsets using operationIDs and tags + • Generate a Mermaid diagram of the API from an OpenAPI document - -## Installation +## Installation Install [Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenApi.Hidi/1.0.0-preview4) package from NuGet by running the following command: -### .NET CLI(Global) +### .NET CLI(Global) + 1. dotnet tool install --global Microsoft.OpenApi.Hidi --prerelease -### .NET CLI(local) +### .NET CLI(local) 1. dotnet new tool-manifest #if you are setting up the OpenAPI.NET repo 2. dotnet tool install --local Microsoft.OpenApi.Hidi --prerelease @@ -27,14 +29,17 @@ Install [Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenAp ## How to use Hidi + Once you've installed the package locally, you can invoke the Hidi by running: hidi [command]. You can access the list of command options we have by running hidi -h The tool avails the following commands: • Validate • Transform + • Show -### Validate +### Validate + This command option accepts an OpenAPI document as an input parameter, visits multiple OpenAPI elements within the document and returns statistics count report on the following elements: • Path Items @@ -54,9 +59,10 @@ It accepts the following command: **Example:** `hidi.exe validate --openapi C:\OpenApidocs\Mail.yml --loglevel trace` -Run validate -h to see the options available. - -### Transform +Run validate -h to see the options available. + +### Transform + Used to convert file formats from JSON to YAML and vice versa and performs slicing of OpenAPI documents. This command accepts the following parameters: @@ -90,3 +96,11 @@ This command accepts the following parameters: hidi transform -cs dataverse.csdl --csdlFilter "appointments,opportunities" -o appointmentsAndOpportunities.yaml -ll trace Run transform -h to see all the available usage options. + +### Show + +This command accepts an OpenAPI document as an input parameter and generates a Markdown file that contains a diagram of the API using Mermaid syntax. + +**Examples:** + + 1. hidi show -d files\People.yml -o People.md -ll trace From 49a12f384632a08c2cb663c7a9c8350a62953294 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Fri, 23 Dec 2022 12:42:12 -0500 Subject: [PATCH 347/855] Moved mermaid writer into OpenApiUrlTreeNode and fixed more sanitization issues --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 52 +++------------- .../Services/OpenApiUrlTreeNode.cs | 59 +++++++++++++++++++ 2 files changed, 68 insertions(+), 43 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index a1f95a63d..881fda1e1 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -602,52 +602,18 @@ private static void WriteTreeDocument(string openapi, OpenApiDocument document, writer.WriteLine("# " + document.Info.Title); writer.WriteLine(); writer.WriteLine("OpenAPI: " + openapi); - writer.Write(@"
-GET -POST -GET POST -GET PATCH DELETE -GET PUT DELETE -GET DELETE -DELETE -
-"); - writer.WriteLine(); - writer.WriteLine("```mermaid"); - writer.WriteLine("graph LR"); - writer.WriteLine("classDef GET fill:lightSteelBlue,stroke:#333,stroke-width:2px;"); - writer.WriteLine("classDef POST fill:SteelBlue,stroke:#333,stroke-width:2px;"); - writer.WriteLine("classDef GETPOST fill:forestGreen,stroke:#333,stroke-width:2px;"); - writer.WriteLine("classDef DELETEGETPATCH fill:yellowGreen,stroke:#333,stroke-width:2px;"); - writer.WriteLine("classDef DELETEGETPUT fill:olive,stroke:#333,stroke-width:2px;"); - writer.WriteLine("classDef DELETEGET fill:DarkSeaGreen,stroke:#333,stroke-width:2px;"); - writer.WriteLine("classDef DELETE fill:tomato,stroke:#333,stroke-width:2px;"); - writer.WriteLine("classDef OTHER fill:white,stroke:#333,stroke-width:2px;"); - - ProcessNode(rootNode, writer); - writer.WriteLine("```"); - } - private static void ProcessNode(OpenApiUrlTreeNode node, StreamWriter writer) - { - var path = string.IsNullOrEmpty(node.Path) ? "/" : Sanitize(node.Path); - foreach (var child in node.Children) + writer.WriteLine(@"
"); + // write a span for each mermaidcolorscheme + foreach (var color in OpenApiUrlTreeNode.MermaidColorScheme) { - writer.WriteLine($"{Sanitize(path)} --> {Sanitize(child.Value.Path)}[{Sanitize(child.Key)}]"); - ProcessNode(child.Value, writer); + writer.WriteLine($"{color.Key.Replace("_"," ")}"); } - var methods = String.Join("", node.PathItems.SelectMany(p => p.Value.Operations.Select(o => o.Key)) - .Distinct() - .Select(o => o.ToString().ToUpper()) - .OrderBy(o => o) - .ToList()); - if (String.IsNullOrEmpty(methods)) methods = "OTHER"; - writer.WriteLine($"class {path} {methods}"); - } - - private static string Sanitize(string token) - { - return token.Replace("\\", "/").Replace("{", ":").Replace("}", ""); + writer.WriteLine("/div"); + writer.WriteLine(); + writer.WriteLine("```mermaid"); + rootNode.WriteMermaid(writer); + writer.WriteLine("```"); } } } diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 30a47bdd7..81c66f120 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Microsoft.OpenApi.Models; @@ -235,5 +236,63 @@ public void AddAdditionalData(Dictionary> additionalData) } } } + + /// + /// Write tree as Mermaid syntax + /// + /// StreamWriter to write the Mermaid content to + public void WriteMermaid(StreamWriter writer) + { + writer.WriteLine("graph LR"); + foreach (var color in MermaidColorScheme) + { + writer.WriteLine($"classDef {color.Key} fill:{color.Value},stroke:#333,stroke-width:4px"); + } + + ProcessNode(this, writer); + } + + /// + /// Dictionary that maps a set of HTTP methods to HTML color. Keys are sorted, uppercased, concatenated HTTP methods. + /// + public static Dictionary MermaidColorScheme = new Dictionary + { + { "GET", "lightSteelBlue" }, + { "POST", "SteelBlue" }, + { "GET_POST", "forestGreen" }, + { "DELETE_GET_PATCH", "yellowGreen" }, + { "DELETE_GET_PUT", "olive" }, + { "DELETE_GET", "DarkSeaGreen" }, + { "DELETE", "tomato" }, + { "OTHER", "white" } + }; + + private static void ProcessNode(OpenApiUrlTreeNode node, StreamWriter writer) + { + var path = string.IsNullOrEmpty(node.Path) ? "/" : SanitizeMermaidNode(node.Path); + foreach (var child in node.Children) + { + writer.WriteLine($"{path} --> {SanitizeMermaidNode(child.Value.Path)}[\"{child.Key}\"]"); + ProcessNode(child.Value, writer); + } + var methods = String.Join("_", node.PathItems.SelectMany(p => p.Value.Operations.Select(o => o.Key)) + .Distinct() + .Select(o => o.ToString().ToUpper()) + .OrderBy(o => o) + .ToList()); + if (String.IsNullOrEmpty(methods)) methods = "OTHER"; + writer.WriteLine($"class {path} {methods}"); + } + + private static string SanitizeMermaidNode(string token) + { + return token.Replace("\\", "/") + .Replace("{", ":") + .Replace("}", "") + .Replace(".", "_") + .Replace(";", "_") + .Replace("-", "_") + .Replace("default", "def_ault"); // default is a reserved word for classes + } } } From 87818841f1739220145dfab79053452456b515f9 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 24 Dec 2022 18:35:42 -0500 Subject: [PATCH 348/855] Added shapes for better accessibility --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 6 +- .../Services/OpenApiUrlTreeNode.cs | 119 +++++++++++++++--- 2 files changed, 107 insertions(+), 18 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 881fda1e1..fbbacb140 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -605,11 +605,11 @@ private static void WriteTreeDocument(string openapi, OpenApiDocument document, writer.WriteLine(@"
"); // write a span for each mermaidcolorscheme - foreach (var color in OpenApiUrlTreeNode.MermaidColorScheme) + foreach (var style in OpenApiUrlTreeNode.MermaidNodeStyles) { - writer.WriteLine($"{color.Key.Replace("_"," ")}"); + writer.WriteLine($"{style.Key.Replace("_"," ")}"); } - writer.WriteLine("/div"); + writer.WriteLine("
"); writer.WriteLine(); writer.WriteLine("```mermaid"); rootNode.WriteMermaid(writer); diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 81c66f120..5b07cd8c7 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -244,9 +244,9 @@ public void AddAdditionalData(Dictionary> additionalData) public void WriteMermaid(StreamWriter writer) { writer.WriteLine("graph LR"); - foreach (var color in MermaidColorScheme) + foreach (var style in MermaidNodeStyles) { - writer.WriteLine($"classDef {color.Key} fill:{color.Value},stroke:#333,stroke-width:4px"); + writer.WriteLine($"classDef {style.Key} fill:{style.Value.Color},stroke:#333,stroke-width:2px"); } ProcessNode(this, writer); @@ -255,35 +255,71 @@ public void WriteMermaid(StreamWriter writer) /// /// Dictionary that maps a set of HTTP methods to HTML color. Keys are sorted, uppercased, concatenated HTTP methods. /// - public static Dictionary MermaidColorScheme = new Dictionary + public static Dictionary MermaidNodeStyles = new Dictionary { - { "GET", "lightSteelBlue" }, - { "POST", "SteelBlue" }, - { "GET_POST", "forestGreen" }, - { "DELETE_GET_PATCH", "yellowGreen" }, - { "DELETE_GET_PUT", "olive" }, - { "DELETE_GET", "DarkSeaGreen" }, - { "DELETE", "tomato" }, - { "OTHER", "white" } + { "GET", new MermaidNodeStyle("lightSteelBlue", MermaidNodeShape.SquareCornerRectangle) }, + { "POST", new MermaidNodeStyle("Lightcoral", MermaidNodeShape.OddShape) }, + { "GET_POST", new MermaidNodeStyle("forestGreen", MermaidNodeShape.RoundedCornerRectangle) }, + { "DELETE_GET_PATCH", new MermaidNodeStyle("yellowGreen", MermaidNodeShape.Circle) }, + { "DELETE_GET_PATCH_PUT", new MermaidNodeStyle("oliveDrab", MermaidNodeShape.Circle) }, + { "DELETE_GET_PUT", new MermaidNodeStyle("olive", MermaidNodeShape.Circle) }, + { "DELETE_GET", new MermaidNodeStyle("DarkSeaGreen", MermaidNodeShape.Circle) }, + { "DELETE", new MermaidNodeStyle("Tomato", MermaidNodeShape.Rhombus) }, + { "OTHER", new MermaidNodeStyle("White", MermaidNodeShape.SquareCornerRectangle) }, }; private static void ProcessNode(OpenApiUrlTreeNode node, StreamWriter writer) { var path = string.IsNullOrEmpty(node.Path) ? "/" : SanitizeMermaidNode(node.Path); + var methods = GetMethods(node); + var (startChar, endChar) = GetShapeDelimiters(methods); foreach (var child in node.Children) { - writer.WriteLine($"{path} --> {SanitizeMermaidNode(child.Value.Path)}[\"{child.Key}\"]"); + var childMethods = GetMethods(child.Value); + var (childStartChar, childEndChar) = GetShapeDelimiters(childMethods); + writer.WriteLine($"{path}{startChar}\"{node.Segment}\"{endChar} --> {SanitizeMermaidNode(child.Value.Path)}{childStartChar}\"{child.Key}\"{childEndChar}"); ProcessNode(child.Value, writer); } - var methods = String.Join("_", node.PathItems.SelectMany(p => p.Value.Operations.Select(o => o.Key)) + if (String.IsNullOrEmpty(methods)) methods = "OTHER"; + writer.WriteLine($"class {path} {methods}"); + } + + private static string GetMethods(OpenApiUrlTreeNode node) + { + return String.Join("_", node.PathItems.SelectMany(p => p.Value.Operations.Select(o => o.Key)) .Distinct() .Select(o => o.ToString().ToUpper()) .OrderBy(o => o) .ToList()); - if (String.IsNullOrEmpty(methods)) methods = "OTHER"; - writer.WriteLine($"class {path} {methods}"); } + private static (string, string) GetShapeDelimiters(string methods) + { + + if (MermaidNodeStyles.ContainsKey(methods)) + { + //switch on shape + switch (MermaidNodeStyles[methods].Shape) + { + case MermaidNodeShape.Circle: + return ("((", "))"); + case MermaidNodeShape.RoundedCornerRectangle: + return ("(", ")"); + case MermaidNodeShape.Rhombus: + return ("{", "}"); + case MermaidNodeShape.SquareCornerRectangle: + return ("[", "]"); + case MermaidNodeShape.OddShape: + return (">", "]"); + default: + return ("[", "]"); + } + } + else + { + return ("[", "]"); + } + } private static string SanitizeMermaidNode(string token) { return token.Replace("\\", "/") @@ -295,4 +331,57 @@ private static string SanitizeMermaidNode(string token) .Replace("default", "def_ault"); // default is a reserved word for classes } } + /// + /// Defines the color and shape of a node in a Mermaid graph diagram + /// + public class MermaidNodeStyle + { + /// + /// + /// + /// + /// + public MermaidNodeStyle(string color, MermaidNodeShape shape) + { + Color = color; + Shape = shape; + } + + /// + /// + /// + public string Color { get; } + + /// + /// + /// + public MermaidNodeShape Shape { get; } + } + + /// + /// + /// + public enum MermaidNodeShape + { + /// + /// Rectangle with square corners + /// + SquareCornerRectangle, + /// + /// Rectangle with rounded corners + /// + RoundedCornerRectangle, + /// + /// Circle + /// + Circle, + /// + /// Rhombus + /// + Rhombus, + /// + /// Odd shape + /// + OddShape + } } From 0bc172675c9d65cabcb1649c08a388a3732372f8 Mon Sep 17 00:00:00 2001 From: Darrel Date: Sat, 24 Dec 2022 19:06:22 -0500 Subject: [PATCH 349/855] Update to do a unnecessary using Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index fbbacb140..0df940d03 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -582,7 +582,7 @@ internal static async Task ShowOpenApiDocument(string openapi, FileInfo output, // Create OpenApiUrlTree from document using var file = new FileStream(output.FullName, FileMode.Create); - var writer = new StreamWriter(file); + using var writer = new StreamWriter(file); WriteTreeDocument(openapi, document, writer); writer.Flush(); From e8061ac95c051c05c25681d96d92d2b13db5f3ae Mon Sep 17 00:00:00 2001 From: Darrel Date: Sat, 24 Dec 2022 19:14:45 -0500 Subject: [PATCH 350/855] Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 5b07cd8c7..205bb8cdd 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -289,7 +289,7 @@ private static string GetMethods(OpenApiUrlTreeNode node) return String.Join("_", node.PathItems.SelectMany(p => p.Value.Operations.Select(o => o.Key)) .Distinct() .Select(o => o.ToString().ToUpper()) - .OrderBy(o => o) + .Order() .ToList()); } From 5a7146c09799b395b548e256f1a9c4aedca5a927 Mon Sep 17 00:00:00 2001 From: Darrel Date: Sat, 24 Dec 2022 19:15:08 -0500 Subject: [PATCH 351/855] Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 205bb8cdd..4b211349a 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -288,7 +288,7 @@ private static string GetMethods(OpenApiUrlTreeNode node) { return String.Join("_", node.PathItems.SelectMany(p => p.Value.Operations.Select(o => o.Key)) .Distinct() - .Select(o => o.ToString().ToUpper()) + .Select(static o => o.ToString().ToUpper()) .Order() .ToList()); } From fc3ba5e36d2b8d7779e9cd7837b218c5b16c8429 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 24 Dec 2022 19:15:57 -0500 Subject: [PATCH 352/855] Added a bunch of usings and removed an unnecessary flush to address comments --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 0df940d03..52d2e4fc9 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -265,7 +265,7 @@ public static async Task ValidateOpenApiDocument( { throw new ArgumentNullException(nameof(openapi)); } - var stream = await GetStream(openapi, logger, cancellationToken); + using var stream = await GetStream(openapi, logger, cancellationToken); OpenApiDocument document; Stopwatch stopwatch = Stopwatch.StartNew(); @@ -546,7 +546,7 @@ internal static async Task ShowOpenApiDocument(string openapi, FileInfo output, { throw new ArgumentNullException(nameof(openapi)); } - var stream = await GetStream(openapi, logger, cancellationToken); + using var stream = await GetStream(openapi, logger, cancellationToken); OpenApiDocument document; Stopwatch stopwatch = Stopwatch.StartNew(); @@ -584,7 +584,6 @@ internal static async Task ShowOpenApiDocument(string openapi, FileInfo output, using var file = new FileStream(output.FullName, FileMode.Create); using var writer = new StreamWriter(file); WriteTreeDocument(openapi, document, writer); - writer.Flush(); logger.LogTrace("Finished walking through the OpenApi document. "); } From 6c57e8da3b8820ec7f82500f4fcfb098de86eac9 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 24 Dec 2022 19:22:48 -0500 Subject: [PATCH 353/855] Fixed broken order method --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 4b211349a..5b07cd8c7 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -288,8 +288,8 @@ private static string GetMethods(OpenApiUrlTreeNode node) { return String.Join("_", node.PathItems.SelectMany(p => p.Value.Operations.Select(o => o.Key)) .Distinct() - .Select(static o => o.ToString().ToUpper()) - .Order() + .Select(o => o.ToString().ToUpper()) + .OrderBy(o => o) .ToList()); } From 9e2ff5161cb0c8720cf14a98929704240410b11a Mon Sep 17 00:00:00 2001 From: Darrel Date: Wed, 28 Dec 2022 09:18:14 -0500 Subject: [PATCH 354/855] Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 5b07cd8c7..70b325712 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -296,7 +296,7 @@ private static string GetMethods(OpenApiUrlTreeNode node) private static (string, string) GetShapeDelimiters(string methods) { - if (MermaidNodeStyles.ContainsKey(methods)) + if (MermaidNodeStyles.TryGetValue(methods, out var style)) { //switch on shape switch (MermaidNodeStyles[methods].Shape) From efeeca7c5a76ec48eb99916ce161306576cf2189 Mon Sep 17 00:00:00 2001 From: Darrel Date: Wed, 28 Dec 2022 17:05:52 -0500 Subject: [PATCH 355/855] Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 70b325712..01634d94e 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -299,7 +299,7 @@ private static (string, string) GetShapeDelimiters(string methods) if (MermaidNodeStyles.TryGetValue(methods, out var style)) { //switch on shape - switch (MermaidNodeStyles[methods].Shape) + switch (style.Shape) { case MermaidNodeShape.Circle: return ("((", "))"); From 5d87820d686424d50136e3de330570b97cfbaaba Mon Sep 17 00:00:00 2001 From: Darrel Date: Wed, 28 Dec 2022 17:06:21 -0500 Subject: [PATCH 356/855] Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 01634d94e..556b54a9f 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -255,7 +255,7 @@ public void WriteMermaid(StreamWriter writer) /// /// Dictionary that maps a set of HTTP methods to HTML color. Keys are sorted, uppercased, concatenated HTTP methods. /// - public static Dictionary MermaidNodeStyles = new Dictionary + public static Dictionary MermaidNodeStyles = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "GET", new MermaidNodeStyle("lightSteelBlue", MermaidNodeShape.SquareCornerRectangle) }, { "POST", new MermaidNodeStyle("Lightcoral", MermaidNodeShape.OddShape) }, From 674fe14b22d37c82380814b72150905cecee1c14 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Tue, 3 Jan 2023 17:57:55 -0500 Subject: [PATCH 357/855] Changed mermaid styles to make them readonly --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 556b54a9f..d28b9d53f 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; using Microsoft.OpenApi.Models; @@ -255,7 +256,7 @@ public void WriteMermaid(StreamWriter writer) /// /// Dictionary that maps a set of HTTP methods to HTML color. Keys are sorted, uppercased, concatenated HTTP methods. /// - public static Dictionary MermaidNodeStyles = new Dictionary(StringComparer.OrdinalIgnoreCase) + public readonly static IReadOnlyDictionary MermaidNodeStyles = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "GET", new MermaidNodeStyle("lightSteelBlue", MermaidNodeShape.SquareCornerRectangle) }, { "POST", new MermaidNodeStyle("Lightcoral", MermaidNodeShape.OddShape) }, @@ -341,7 +342,7 @@ public class MermaidNodeStyle ///
/// /// - public MermaidNodeStyle(string color, MermaidNodeShape shape) + internal MermaidNodeStyle(string color, MermaidNodeShape shape) { Color = color; Shape = shape; From 931270fcfe2f930940499138ed045e8d5b976cb7 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Tue, 3 Jan 2023 23:08:02 -0500 Subject: [PATCH 358/855] Fixed data in broken test --- .../Services/OpenApiServiceTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 3d764b4fb..a080db11a 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -30,7 +30,7 @@ public async Task ReturnConvertedCSDLFile() } [Theory] - [InlineData("Todos.Todo.UpdateTodo",null, 1)] + [InlineData("Todos.Todo.UpdateTodoById",null, 1)] [InlineData("Todos.Todo.ListTodo",null, 1)] [InlineData(null, "Todos.Todo", 4)] public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocument(string operationIds, string tags, int expectedPathCount) From 079da0f22f4c2b3eb4a9acb1f20b531a49a609e8 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Tue, 3 Jan 2023 23:08:31 -0500 Subject: [PATCH 359/855] Updated public API --- .../PublicApi/PublicApi.approved.txt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index db3a3ecf7..cc3378c4c 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1062,6 +1062,19 @@ namespace Microsoft.OpenApi.Services public string Response { get; set; } public string ServerVariable { get; } } + public enum MermaidNodeShape + { + SquareCornerRectangle = 0, + RoundedCornerRectangle = 1, + Circle = 2, + Rhombus = 3, + OddShape = 4, + } + public class MermaidNodeStyle + { + public string Color { get; } + public Microsoft.OpenApi.Services.MermaidNodeShape Shape { get; } + } public static class OpenApiFilterService { public static Microsoft.OpenApi.Models.OpenApiDocument CreateFilteredDocument(Microsoft.OpenApi.Models.OpenApiDocument source, System.Func predicate) { } @@ -1094,6 +1107,7 @@ namespace Microsoft.OpenApi.Services } public class OpenApiUrlTreeNode { + public static readonly System.Collections.Generic.IReadOnlyDictionary MermaidNodeStyles; public System.Collections.Generic.IDictionary> AdditionalData { get; set; } public System.Collections.Generic.IDictionary Children { get; } public bool IsParameter { get; } @@ -1104,6 +1118,7 @@ namespace Microsoft.OpenApi.Services public void Attach(Microsoft.OpenApi.Models.OpenApiDocument doc, string label) { } public Microsoft.OpenApi.Services.OpenApiUrlTreeNode Attach(string path, Microsoft.OpenApi.Models.OpenApiPathItem pathItem, string label) { } public bool HasOperations(string label) { } + public void WriteMermaid(System.IO.StreamWriter writer) { } public static Microsoft.OpenApi.Services.OpenApiUrlTreeNode Create() { } public static Microsoft.OpenApi.Services.OpenApiUrlTreeNode Create(Microsoft.OpenApi.Models.OpenApiDocument doc, string label) { } } From 2783cb75ab6a2a390ded1cf345ee587a18550702 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 4 Jan 2023 09:56:15 -0500 Subject: [PATCH 360/855] - bumps hidi version to get latest odata and mermaid Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index e27a214d5..e23533fbf 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.1.0 + 1.2.0 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET From 9858a80bbbb8f7e835ec9cc7eab4a35547d577dd Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 5 Jan 2023 10:06:11 +0300 Subject: [PATCH 361/855] Revert "Serialize `OpenApiDate` values properly to short date (#1102)" This reverts commit 1a7392f64c1586286526945fe9d3c00b684f8fa2. --- src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs | 2 +- ...ithoutReferenceWorks_produceTerseOutput=False.verified.txt | 3 +-- ...WithoutReferenceWorks_produceTerseOutput=True.verified.txt | 2 +- test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs | 4 +--- 4 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs index bd6db956a..e0abda167 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -118,7 +118,7 @@ public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) case PrimitiveType.Date: var dateValue = (OpenApiDate)(IOpenApiPrimitive)this; - writer.WriteValue(dateValue.Value.ToShortDateString()); + writer.WriteValue(dateValue.Value); break; case PrimitiveType.DateTime: diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt index 868b45156..45f085f73 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt @@ -21,7 +21,6 @@ } ] } - ], - "aDate": "12/12/2022" + ] } } \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt index 7ab9ad1d6..b503d318e 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"value":{"versions":[{"status":"Status1","id":"v1","links":[{"href":"http://example.com/1","rel":"sampleRel1"}]},{"status":"Status2","id":"v2","links":[{"href":"http://example.com/2","rel":"sampleRel2"}]}],"aDate":"12/12/2022"}} \ No newline at end of file +{"value":{"versions":[{"status":"Status1","id":"v1","links":[{"href":"http://example.com/1","rel":"sampleRel1"}]},{"status":"Status2","id":"v2","links":[{"href":"http://example.com/2","rel":"sampleRel2"}]}]}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs index e12a7d100..d2f317863 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Globalization; using System.IO; using System.Text; @@ -96,8 +95,7 @@ public class OpenApiExampleTests } } } - }, - ["aDate"] = new OpenApiDate(DateTime.Parse("12/12/2022 00:00:00")) + } } }; From 70724b511d38373c1554df7525beef2c546f8c85 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 5 Jan 2023 11:48:13 +0300 Subject: [PATCH 362/855] Fix failing test by updating operation id --- .../Services/OpenApiServiceTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 3d764b4fb..379482283 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -30,8 +30,8 @@ public async Task ReturnConvertedCSDLFile() } [Theory] - [InlineData("Todos.Todo.UpdateTodo",null, 1)] - [InlineData("Todos.Todo.ListTodo",null, 1)] + [InlineData("Todos.Todo.UpdateTodoById", null, 1)] + [InlineData("Todos.Todo.ListTodo", null, 1)] [InlineData(null, "Todos.Todo", 4)] public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocument(string operationIds, string tags, int expectedPathCount) { From fa86d4ffce6e7605d7899dc98916ef4313749ebb Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 5 Jan 2023 12:02:59 +0300 Subject: [PATCH 363/855] Write out the corresponding DateTime value as a short date representation by retrieving a substring of the instance --- src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs index e0abda167..b8dcf097d 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -118,7 +118,7 @@ public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) case PrimitiveType.Date: var dateValue = (OpenApiDate)(IOpenApiPrimitive)this; - writer.WriteValue(dateValue.Value); + writer.WriteValue(dateValue.Value.ToString("o").Substring(0, 10)); break; case PrimitiveType.DateTime: From 6d21b494362fa51ef62433363a10553758862928 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 5 Jan 2023 12:03:14 +0300 Subject: [PATCH 364/855] Fix tests --- ...ithoutReferenceWorks_produceTerseOutput=False.verified.txt | 3 ++- ...WithoutReferenceWorks_produceTerseOutput=True.verified.txt | 2 +- test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs | 4 +++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt index 45f085f73..bbe6f7e93 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=False.verified.txt @@ -21,6 +21,7 @@ } ] } - ] + ], + "aDate": "2022-12-12" } } \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt index b503d318e..e84267af4 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.SerializeReferencedExampleAsV3JsonWithoutReferenceWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"value":{"versions":[{"status":"Status1","id":"v1","links":[{"href":"http://example.com/1","rel":"sampleRel1"}]},{"status":"Status2","id":"v2","links":[{"href":"http://example.com/2","rel":"sampleRel2"}]}]}} \ No newline at end of file +{"value":{"versions":[{"status":"Status1","id":"v1","links":[{"href":"http://example.com/1","rel":"sampleRel1"}]},{"status":"Status2","id":"v2","links":[{"href":"http://example.com/2","rel":"sampleRel2"}]}],"aDate":"2022-12-12"}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs index d2f317863..e12a7d100 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Globalization; using System.IO; using System.Text; @@ -95,7 +96,8 @@ public class OpenApiExampleTests } } } - } + }, + ["aDate"] = new OpenApiDate(DateTime.Parse("12/12/2022 00:00:00")) } }; From a0d002af805b38b5a2c31da3fecf9cda9d75af29 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 5 Jan 2023 12:12:51 +0300 Subject: [PATCH 365/855] Upgrade lib versions --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index bcac9a7af..e65b857bf 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.4.5 + 1.5.0 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index a938a968f..e13da5d5e 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.4.5 + 1.5.0 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 222357487b67282c25e62e8ec3fa3afb4da93c00 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 5 Jan 2023 12:30:31 +0300 Subject: [PATCH 366/855] Fix failing test --- .../Services/OpenApiServiceTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 3d764b4fb..a080db11a 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -30,7 +30,7 @@ public async Task ReturnConvertedCSDLFile() } [Theory] - [InlineData("Todos.Todo.UpdateTodo",null, 1)] + [InlineData("Todos.Todo.UpdateTodoById",null, 1)] [InlineData("Todos.Todo.ListTodo",null, 1)] [InlineData(null, "Todos.Todo", 4)] public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocument(string operationIds, string tags, int expectedPathCount) From 3f5978410e5e0cb9deb024f97f7ed26b08a61c1c Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Thu, 5 Jan 2023 14:27:41 -0500 Subject: [PATCH 367/855] Refactored OpenAPIService to remove duplicate code --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 145 +++++++------------ 1 file changed, 50 insertions(+), 95 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 52d2e4fc9..d2eb2e229 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -29,6 +29,7 @@ using System.Reflection; using Microsoft.Extensions.Configuration; using System.Runtime.CompilerServices; +using System.Reflection.Metadata; namespace Microsoft.OpenApi.Hidi { @@ -110,43 +111,13 @@ CancellationToken cancellationToken else { stream = await GetStream(openapi, logger, cancellationToken); - - using (logger.BeginScope($"Parse OpenAPI: {openapi}",openapi)) - { - stopwatch.Restart(); - var result = await new OpenApiStreamReader(new OpenApiReaderSettings - { - RuleSet = ValidationRuleSet.GetDefaultRuleSet(), - LoadExternalRefs = inlineExternal, - BaseUrl = openapi.StartsWith("http") ? new Uri(openapi) : new Uri("file:" + new FileInfo(openapi).DirectoryName + "\\") - } - ).ReadAsync(stream); - - document = result.OpenApiDocument; - - var context = result.OpenApiDiagnostic; - if (context.Errors.Count > 0) - { - logger.LogTrace("{timestamp}ms: Parsed OpenAPI with errors. {count} paths found.", stopwatch.ElapsedMilliseconds, document.Paths.Count); - - var errorReport = new StringBuilder(); - - foreach (var error in context.Errors) - { - logger.LogError("OpenApi Parsing error: {message}", error.ToString()); - errorReport.AppendLine(error.ToString()); - } - logger.LogError($"{stopwatch.ElapsedMilliseconds}ms: OpenApi Parsing errors {string.Join(Environment.NewLine, context.Errors.Select(e => e.Message).ToArray())}"); - } - else - { - logger.LogTrace("{timestamp}ms: Parsed OpenApi successfully. {count} paths found.", stopwatch.ElapsedMilliseconds, document.Paths.Count); - } - - openApiFormat = format ?? GetOpenApiFormat(openapi, logger); - openApiVersion = version != null ? TryParseOpenApiSpecVersion(version) : result.OpenApiDiagnostic.SpecificationVersion; - stopwatch.Stop(); - } + stopwatch.Restart(); + var result = await ParseOpenApi(openapi, logger, stream); + document = result.OpenApiDocument; + + openApiFormat = format ?? GetOpenApiFormat(openapi, logger); + openApiVersion = version != null ? TryParseOpenApiSpecVersion(version) : result.OpenApiDiagnostic.SpecificationVersion; + stopwatch.Stop(); } using (logger.BeginScope("Filter")) @@ -267,40 +238,13 @@ public static async Task ValidateOpenApiDocument( } using var stream = await GetStream(openapi, logger, cancellationToken); - OpenApiDocument document; - Stopwatch stopwatch = Stopwatch.StartNew(); - using (logger.BeginScope($"Parsing OpenAPI: {openapi}", openapi)) - { - stopwatch.Start(); - - var result = await new OpenApiStreamReader(new OpenApiReaderSettings - { - RuleSet = ValidationRuleSet.GetDefaultRuleSet() - } - ).ReadAsync(stream); - - logger.LogTrace("{timestamp}ms: Completed parsing.", stopwatch.ElapsedMilliseconds); - - document = result.OpenApiDocument; - var context = result.OpenApiDiagnostic; - if (context.Errors.Count != 0) - { - using (logger.BeginScope("Detected errors")) - { - foreach (var error in context.Errors) - { - logger.LogError(error.ToString()); - } - } - } - stopwatch.Stop(); - } + var result = await ParseOpenApi(openapi, logger, stream); using (logger.BeginScope("Calculating statistics")) { var statsVisitor = new StatsVisitor(); var walker = new OpenApiWalker(statsVisitor); - walker.Walk(document); + walker.Walk(result.OpenApiDocument); logger.LogTrace("Finished walking through the OpenApi document. Generating a statistics report.."); logger.LogInformation(statsVisitor.GetStatisticsReport()); @@ -312,6 +256,29 @@ public static async Task ValidateOpenApiDocument( } } + private static async Task ParseOpenApi(string openApiFile, ILogger logger, Stream stream) + { + ReadResult result; + Stopwatch stopwatch = Stopwatch.StartNew(); + using (logger.BeginScope($"Parsing OpenAPI: {openApiFile}", openApiFile)) + { + stopwatch.Start(); + + result = await new OpenApiStreamReader(new OpenApiReaderSettings + { + RuleSet = ValidationRuleSet.GetDefaultRuleSet() + } + ).ReadAsync(stream); + + logger.LogTrace("{timestamp}ms: Completed parsing.", stopwatch.ElapsedMilliseconds); + + LogErrors(logger, result); + stopwatch.Stop(); + } + + return result; + } + internal static IConfiguration GetConfiguration(string settingsFile) { settingsFile ??= "appsettings.json"; @@ -548,34 +515,7 @@ internal static async Task ShowOpenApiDocument(string openapi, FileInfo output, } using var stream = await GetStream(openapi, logger, cancellationToken); - OpenApiDocument document; - Stopwatch stopwatch = Stopwatch.StartNew(); - using (logger.BeginScope($"Parsing OpenAPI: {openapi}", openapi)) - { - stopwatch.Start(); - - var result = await new OpenApiStreamReader(new OpenApiReaderSettings - { - RuleSet = ValidationRuleSet.GetDefaultRuleSet() - } - ).ReadAsync(stream); - - logger.LogTrace("{timestamp}ms: Completed parsing.", stopwatch.ElapsedMilliseconds); - - document = result.OpenApiDocument; - var context = result.OpenApiDiagnostic; - if (context.Errors.Count != 0) - { - using (logger.BeginScope("Detected errors")) - { - foreach (var error in context.Errors) - { - logger.LogError(error.ToString()); - } - } - } - stopwatch.Stop(); - } + var result = await ParseOpenApi(openapi, logger, stream); using (logger.BeginScope("Creating diagram")) { @@ -583,7 +523,7 @@ internal static async Task ShowOpenApiDocument(string openapi, FileInfo output, using var file = new FileStream(output.FullName, FileMode.Create); using var writer = new StreamWriter(file); - WriteTreeDocument(openapi, document, writer); + WriteTreeDocument(openapi, result.OpenApiDocument, writer); logger.LogTrace("Finished walking through the OpenApi document. "); } @@ -594,6 +534,21 @@ internal static async Task ShowOpenApiDocument(string openapi, FileInfo output, } } + private static void LogErrors(ILogger logger, ReadResult result) + { + var context = result.OpenApiDiagnostic; + if (context.Errors.Count != 0) + { + using (logger.BeginScope("Detected errors")) + { + foreach (var error in context.Errors) + { + logger.LogError(error.ToString()); + } + } + } + } + private static void WriteTreeDocument(string openapi, OpenApiDocument document, StreamWriter writer) { var rootNode = OpenApiUrlTreeNode.Create(document, "main"); From e0d08f80c3f289bcb199180d2c0053150beb9af9 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 8 Jan 2023 10:30:07 -0500 Subject: [PATCH 368/855] Added tests for mermaid diagrams --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 4 ++-- .../Services/OpenApiUrlTreeNode.cs | 4 ++-- .../Services/OpenApiServiceTests.cs | 23 +++++++++++++++++++ .../PublicApi/PublicApi.approved.txt | 2 +- ...erifyDiagramFromSampleOpenAPI.verified.txt | 15 ++++++++++++ .../Services/OpenApiUrlTreeNodeTests.cs | 20 ++++++++++++++++ 6 files changed, 63 insertions(+), 5 deletions(-) create mode 100644 test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.VerifyDiagramFromSampleOpenAPI.verified.txt diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index d2eb2e229..73c9fc336 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -549,13 +549,13 @@ private static void LogErrors(ILogger logger, ReadResult result) } } - private static void WriteTreeDocument(string openapi, OpenApiDocument document, StreamWriter writer) + internal static void WriteTreeDocument(string openapiUrl, OpenApiDocument document, StreamWriter writer) { var rootNode = OpenApiUrlTreeNode.Create(document, "main"); writer.WriteLine("# " + document.Info.Title); writer.WriteLine(); - writer.WriteLine("OpenAPI: " + openapi); + writer.WriteLine("OpenAPI: " + openapiUrl); writer.WriteLine(@"
"); // write a span for each mermaidcolorscheme diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index d28b9d53f..d8d4240f8 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -242,7 +242,7 @@ public void AddAdditionalData(Dictionary> additionalData) /// Write tree as Mermaid syntax ///
/// StreamWriter to write the Mermaid content to - public void WriteMermaid(StreamWriter writer) + public void WriteMermaid(TextWriter writer) { writer.WriteLine("graph LR"); foreach (var style in MermaidNodeStyles) @@ -269,7 +269,7 @@ public void WriteMermaid(StreamWriter writer) { "OTHER", new MermaidNodeStyle("White", MermaidNodeShape.SquareCornerRectangle) }, }; - private static void ProcessNode(OpenApiUrlTreeNode node, StreamWriter writer) + private static void ProcessNode(OpenApiUrlTreeNode node, TextWriter writer) { var path = string.IsNullOrEmpty(node.Path) ? "/" : SanitizeMermaidNode(node.Path); var methods = GetMethods(node); diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index a080db11a..eb0872b3b 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -1,10 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System.Text; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Hidi; +using Microsoft.OpenApi.Models; using Microsoft.OpenApi.OData; using Microsoft.OpenApi.Services; +using Microsoft.VisualStudio.TestPlatform.Utilities; using Xunit; namespace Microsoft.OpenApi.Tests.Services @@ -71,5 +75,24 @@ public void ReturnOpenApiConvertSettingsWhenSettingsFileIsProvided(string filePa Assert.NotNull(settings); } } + + [Fact] + public void ShowCommandGeneratesMermaidDiagram() + { + var openApiDoc = new OpenApiDocument(); + openApiDoc.Info = new OpenApiInfo + { + Title = "Test", + Version = "1.0.0" + }; + var stream = new MemoryStream(); + using var writer = new StreamWriter(stream); + OpenApiService.WriteTreeDocument("https://example.org/openapi.json", openApiDoc, writer); + writer.Flush(); + stream.Position = 0; + using var reader = new StreamReader(stream); + var output = reader.ReadToEnd(); + Assert.Contains("graph LR", output); + } } } diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index cc3378c4c..63cd0f535 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1118,7 +1118,7 @@ namespace Microsoft.OpenApi.Services public void Attach(Microsoft.OpenApi.Models.OpenApiDocument doc, string label) { } public Microsoft.OpenApi.Services.OpenApiUrlTreeNode Attach(string path, Microsoft.OpenApi.Models.OpenApiPathItem pathItem, string label) { } public bool HasOperations(string label) { } - public void WriteMermaid(System.IO.StreamWriter writer) { } + public void WriteMermaid(System.IO.TextWriter writer) { } public static Microsoft.OpenApi.Services.OpenApiUrlTreeNode Create() { } public static Microsoft.OpenApi.Services.OpenApiUrlTreeNode Create(Microsoft.OpenApi.Models.OpenApiDocument doc, string label) { } } diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.VerifyDiagramFromSampleOpenAPI.verified.txt b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.VerifyDiagramFromSampleOpenAPI.verified.txt new file mode 100644 index 000000000..19596aff5 --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.VerifyDiagramFromSampleOpenAPI.verified.txt @@ -0,0 +1,15 @@ +graph LR +classDef GET fill:lightSteelBlue,stroke:#333,stroke-width:2px +classDef POST fill:Lightcoral,stroke:#333,stroke-width:2px +classDef GET_POST fill:forestGreen,stroke:#333,stroke-width:2px +classDef DELETE_GET_PATCH fill:yellowGreen,stroke:#333,stroke-width:2px +classDef DELETE_GET_PATCH_PUT fill:oliveDrab,stroke:#333,stroke-width:2px +classDef DELETE_GET_PUT fill:olive,stroke:#333,stroke-width:2px +classDef DELETE_GET fill:DarkSeaGreen,stroke:#333,stroke-width:2px +classDef DELETE fill:Tomato,stroke:#333,stroke-width:2px +classDef OTHER fill:White,stroke:#333,stroke-width:2px +/["/"] --> /houses["houses"] +class /houses OTHER +/["/"] --> /cars["cars"] +class /cars OTHER +class / OTHER diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs index 944e6c830..6d0278415 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs @@ -3,12 +3,16 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Services; +using VerifyXunit; using Xunit; namespace Microsoft.OpenApi.Tests.Services { + [UsesVerify] public class OpenApiUrlTreeNodeTests { private OpenApiDocument OpenApiDocumentSample_1 => new OpenApiDocument() @@ -443,5 +447,21 @@ public void ThrowsArgumentNullExceptionForNullArgumentInAddAdditionalDataMethod( Assert.Throws(() => rootNode.AddAdditionalData(null)); } + + [Fact] + public async Task VerifyDiagramFromSampleOpenAPI() + { + var doc1 = OpenApiDocumentSample_1; + + var label1 = "personal"; + var rootNode = OpenApiUrlTreeNode.Create(doc1, label1); + + var writer = new StringWriter(); + rootNode.WriteMermaid(writer); + writer.Flush(); + var diagram = writer.GetStringBuilder().ToString(); + + await Verifier.Verify(diagram); + } } } From b61edcf71279d11728c8a8359bf640bd44e9e5c9 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 8 Jan 2023 19:30:44 -0500 Subject: [PATCH 369/855] Updated diagram test to cover more scenarios --- ...erifyDiagramFromSampleOpenAPI.verified.txt | 10 ++++----- .../Services/OpenApiUrlTreeNodeTests.cs | 22 +++++++++++++++++-- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.VerifyDiagramFromSampleOpenAPI.verified.txt b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.VerifyDiagramFromSampleOpenAPI.verified.txt index 19596aff5..c24dd943d 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.VerifyDiagramFromSampleOpenAPI.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.VerifyDiagramFromSampleOpenAPI.verified.txt @@ -8,8 +8,8 @@ classDef DELETE_GET_PUT fill:olive,stroke:#333,stroke-width:2px classDef DELETE_GET fill:DarkSeaGreen,stroke:#333,stroke-width:2px classDef DELETE fill:Tomato,stroke:#333,stroke-width:2px classDef OTHER fill:White,stroke:#333,stroke-width:2px -/["/"] --> /houses["houses"] -class /houses OTHER -/["/"] --> /cars["cars"] -class /cars OTHER -class / OTHER +/["/"] --> /houses("houses") +class /houses GET_POST +/["/"] --> /cars>"cars"] +class /cars POST +class / GET diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs index 6d0278415..d251c99c1 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs @@ -19,9 +19,27 @@ public class OpenApiUrlTreeNodeTests { Paths = new OpenApiPaths() { - ["/"] = new OpenApiPathItem(), - ["/houses"] = new OpenApiPathItem(), + ["/"] = new OpenApiPathItem() { + Operations = new Dictionary() + { + [OperationType.Get] = new OpenApiOperation(), + } + }, + ["/houses"] = new OpenApiPathItem() + { + Operations = new Dictionary() + { + [OperationType.Get] = new OpenApiOperation(), + [OperationType.Post] = new OpenApiOperation() + } + }, ["/cars"] = new OpenApiPathItem() + { + Operations = new Dictionary() + { + [OperationType.Post] = new OpenApiOperation() + } + } } }; From 6877019bdc69b6d6a91734aae2d614c814b832cc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 21:02:57 +0000 Subject: [PATCH 370/855] Bump Verify.Xunit from 19.5.0 to 19.6.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.5.0 to 19.6.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.5.0...19.6.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 7edbf969f..f68f77502 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 8a9305b52ec4b6c99904ce3cab7c7336a8f7a765 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Wed, 11 Jan 2023 17:44:02 -0500 Subject: [PATCH 371/855] Added test for show command --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 3 +++ .../Services/OpenApiServiceTests.cs | 10 ++++++++++ .../UtilityFiles/SampleOpenApi.yml | 19 +++++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/SampleOpenApi.yml diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 578cdc9e3..aaaa66cba 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -53,6 +53,9 @@ Always + + PreserveNewest + Always diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index eb0872b3b..fd1ea0d59 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -94,5 +94,15 @@ public void ShowCommandGeneratesMermaidDiagram() var output = reader.ReadToEnd(); Assert.Contains("graph LR", output); } + + [Fact] + public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() + { + var fileinfo = new FileInfo("sample.md"); + await OpenApiService.ShowOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", fileinfo, LogLevel.Information, new CancellationToken()); + + var output = File.ReadAllText(fileinfo.FullName); + Assert.Contains("graph LR", output); + } } } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/SampleOpenApi.yml b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/SampleOpenApi.yml new file mode 100644 index 000000000..c4fb2e62f --- /dev/null +++ b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/SampleOpenApi.yml @@ -0,0 +1,19 @@ +openapi: 3.0.0 +info: + title: Sample OpenApi + version: 1.0.0 +paths: + /api/editresource: + get: + responses: + '200': + description: OK + patch: + responses: + '200': + description: OK + /api/viewresource: + get: + responses: + '200': + description: OK \ No newline at end of file From b0af5268256ec57ced75adb98163a85e15dbcf20 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Wed, 11 Jan 2023 21:29:39 -0500 Subject: [PATCH 372/855] Refactored to improve test coverage --- src/Microsoft.OpenApi.Hidi/Program.cs | 32 +++++++++++-------- .../Services/OpenApiServiceTests.cs | 27 ++++++++++++++++ 2 files changed, 46 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index b9db1229f..03aac121d 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -16,8 +16,19 @@ namespace Microsoft.OpenApi.Hidi static class Program { static async Task Main(string[] args) - { - var rootCommand = new RootCommand() {}; + { + var rootCommand = CreateRootCommand(); + + // Parse the incoming args and invoke the handler + await rootCommand.InvokeAsync(args); + + //// Wait for logger to write messages to the console before exiting + await Task.Delay(10); + } + + internal static RootCommand CreateRootCommand() + { + var rootCommand = new RootCommand() { }; // command option parameters and aliases var descriptionOption = new Option("--openapi", "Input OpenAPI description file path or URL"); @@ -46,7 +57,7 @@ static async Task Main(string[] args) var settingsFileOption = new Option("--settings-path", "The configuration file with CSDL conversion settings."); settingsFileOption.AddAlias("--sp"); - + var logLevelOption = new Option("--log-level", () => LogLevel.Information, "The log level to use when logging messages to the main output."); logLevelOption.AddAlias("--ll"); @@ -71,7 +82,7 @@ static async Task Main(string[] args) logLevelOption }; - validateCommand.Handler = new ValidateCommandHandler + validateCommand.Handler = new ValidateCommandHandler { DescriptionOption = descriptionOption, LogLevelOption = logLevelOption @@ -88,7 +99,7 @@ static async Task Main(string[] args) formatOption, terseOutputOption, settingsFileOption, - logLevelOption, + logLevelOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption, @@ -123,7 +134,7 @@ static async Task Main(string[] args) cleanOutputOption }; - showCommand.Handler = new ShowCommandHandler + showCommand.Handler = new ShowCommandHandler { DescriptionOption = descriptionOption, OutputOption = outputOption, @@ -133,12 +144,7 @@ static async Task Main(string[] args) rootCommand.Add(showCommand); rootCommand.Add(transformCommand); rootCommand.Add(validateCommand); - - // Parse the incoming args and invoke the handler - await rootCommand.InvokeAsync(args); - - //// Wait for logger to write messages to the console before exiting - await Task.Delay(10); - } + return rootCommand; + } } } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index fd1ea0d59..020f0db9c 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -1,10 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System.CommandLine; +using System.CommandLine.Invocation; using System.Text; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Hidi; +using Microsoft.OpenApi.Hidi.Handlers; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.OData; using Microsoft.OpenApi.Services; @@ -104,5 +107,29 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() var output = File.ReadAllText(fileinfo.FullName); Assert.Contains("graph LR", output); } + + [Fact] + public async Task InvokeShowCommand() + { + var rootCommand = Program.CreateRootCommand(); + var args = new string[] { "show", "-d", ".\\UtilityFiles\\SampleOpenApi.yml", "-o", "sample.md" }; + var parseResult = rootCommand.Parse(args); + var handler = rootCommand.Subcommands.Where(c => c.Name == "show").First().Handler; + var context = new InvocationContext(parseResult); + + await handler.InvokeAsync(context); + + var output = File.ReadAllText("sample.md"); + Assert.Contains("graph LR", output); + } + + + // Relatively useless test to keep the code coverage metrics happy + [Fact] + public void CreateRootCommand() + { + var rootCommand = Program.CreateRootCommand(); + Assert.NotNull(rootCommand); + } } } From 776e98faa90ba6f6ad90e8e4d37d357c671ed8b5 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Wed, 11 Jan 2023 21:43:14 -0500 Subject: [PATCH 373/855] Change test to call sync invoke --- .../Services/OpenApiServiceTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 020f0db9c..db30d2eff 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -109,7 +109,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() } [Fact] - public async Task InvokeShowCommand() + public void InvokeShowCommand() { var rootCommand = Program.CreateRootCommand(); var args = new string[] { "show", "-d", ".\\UtilityFiles\\SampleOpenApi.yml", "-o", "sample.md" }; @@ -117,7 +117,7 @@ public async Task InvokeShowCommand() var handler = rootCommand.Subcommands.Where(c => c.Name == "show").First().Handler; var context = new InvocationContext(parseResult); - await handler.InvokeAsync(context); + handler.Invoke(context); var output = File.ReadAllText("sample.md"); Assert.Contains("graph LR", output); From 5bc0bd4dcce47830964714677cbd87e0b7e60f1f Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Wed, 11 Jan 2023 22:18:10 -0500 Subject: [PATCH 374/855] Added back missing parameter config options in parseopenapi --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 73c9fc336..dfd1886a4 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -112,7 +112,7 @@ CancellationToken cancellationToken { stream = await GetStream(openapi, logger, cancellationToken); stopwatch.Restart(); - var result = await ParseOpenApi(openapi, logger, stream); + var result = await ParseOpenApi(openapi, inlineExternal, logger, stream); document = result.OpenApiDocument; openApiFormat = format ?? GetOpenApiFormat(openapi, logger); @@ -238,7 +238,7 @@ public static async Task ValidateOpenApiDocument( } using var stream = await GetStream(openapi, logger, cancellationToken); - var result = await ParseOpenApi(openapi, logger, stream); + var result = await ParseOpenApi(openapi, false, logger, stream); using (logger.BeginScope("Calculating statistics")) { @@ -256,7 +256,7 @@ public static async Task ValidateOpenApiDocument( } } - private static async Task ParseOpenApi(string openApiFile, ILogger logger, Stream stream) + private static async Task ParseOpenApi(string openApiFile, bool inlineExternal, ILogger logger, Stream stream) { ReadResult result; Stopwatch stopwatch = Stopwatch.StartNew(); @@ -266,7 +266,9 @@ private static async Task ParseOpenApi(string openApiFile, ILogger Date: Fri, 13 Jan 2023 21:01:45 +0000 Subject: [PATCH 375/855] Bump FluentAssertions from 6.8.0 to 6.9.0 Bumps [FluentAssertions](https://github.com/fluentassertions/fluentassertions) from 6.8.0 to 6.9.0. - [Release notes](https://github.com/fluentassertions/fluentassertions/releases) - [Changelog](https://github.com/fluentassertions/fluentassertions/blob/develop/AcceptApiChanges.ps1) - [Commits](https://github.com/fluentassertions/fluentassertions/compare/6.8.0...6.9.0) --- updated-dependencies: - dependency-name: FluentAssertions dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 1e46b43bf..9f780f605 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -262,7 +262,7 @@ all - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index f68f77502..7c580d2f1 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -23,7 +23,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + From 8c08c06fc4353e2f28120e8113b171033eec2913 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Jan 2023 21:01:47 +0000 Subject: [PATCH 376/855] Bump Microsoft.OData.Edm from 7.13.0 to 7.14.0 Bumps Microsoft.OData.Edm from 7.13.0 to 7.14.0. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index e23533fbf..232830c37 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From 5ee609586084482613f148c75b4c75f316707ab1 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 14 Jan 2023 20:31:28 -0500 Subject: [PATCH 377/855] Updated SanitizeMermaidNode to handle cases found in Microsoft Graph and GitHub APIs --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index d8d4240f8..870fb36d9 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -327,8 +327,11 @@ private static string SanitizeMermaidNode(string token) .Replace("{", ":") .Replace("}", "") .Replace(".", "_") - .Replace(";", "_") + .Replace("(", "_") + .Replace(")", "_") + .Replace(";", "_") .Replace("-", "_") + .Replace("graph", "gra_ph") // graph is a reserved word .Replace("default", "def_ault"); // default is a reserved word for classes } } From a7c4983e38ab16f4e7bd02f6edb28097354a6130 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 14 Jan 2023 20:33:05 -0500 Subject: [PATCH 378/855] Removed Task.Delay as no longer necessary. #1127 --- src/Microsoft.OpenApi.Hidi/Program.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 03aac121d..056da9ab2 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -22,8 +22,6 @@ static async Task Main(string[] args) // Parse the incoming args and invoke the handler await rootCommand.InvokeAsync(args); - //// Wait for logger to write messages to the console before exiting - await Task.Delay(10); } internal static RootCommand CreateRootCommand() @@ -129,6 +127,8 @@ internal static RootCommand CreateRootCommand() var showCommand = new Command("show") { descriptionOption, + csdlOption, + csdlFilterOption, logLevelOption, outputOption, cleanOutputOption @@ -137,6 +137,8 @@ internal static RootCommand CreateRootCommand() showCommand.Handler = new ShowCommandHandler { DescriptionOption = descriptionOption, + CsdlOption = csdlOption, + CsdlFilterOption = csdlFilterOption, OutputOption = outputOption, LogLevelOption = logLevelOption }; From 7aac03ffd6f5e1fbe6d6c8cb07a280c1bacc47c4 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 14 Jan 2023 20:33:59 -0500 Subject: [PATCH 379/855] Updated commands to enable reading from CSDL url for both transform and show commands --- .../Handlers/ShowCommandHandler.cs | 7 +- .../Handlers/TransformCommandHandler.cs | 2 +- .../Handlers/ValidateCommandHandler.cs | 2 +- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 345 +++++++++++------- .../Services/OpenApiServiceTests.cs | 44 ++- 5 files changed, 254 insertions(+), 146 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs index e6542c34a..6974e76dd 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs @@ -16,6 +16,9 @@ internal class ShowCommandHandler : ICommandHandler public Option DescriptionOption { get; set; } public Option OutputOption { get; set; } public Option LogLevelOption { get; set; } + public Option CsdlOption { get; set; } + public Option CsdlFilterOption { get; set; } + public int Invoke(InvocationContext context) { @@ -26,13 +29,15 @@ public async Task InvokeAsync(InvocationContext context) string openapi = context.ParseResult.GetValueForOption(DescriptionOption); FileInfo output = context.ParseResult.GetValueForOption(OutputOption); LogLevel logLevel = context.ParseResult.GetValueForOption(LogLevelOption); + string csdlFilter = context.ParseResult.GetValueForOption(CsdlFilterOption); + string csdl = context.ParseResult.GetValueForOption(CsdlOption); CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken)); using var loggerFactory = Logger.ConfigureLogger(logLevel); var logger = loggerFactory.CreateLogger(); try { - await OpenApiService.ShowOpenApiDocument(openapi, output, logLevel, cancellationToken); + await OpenApiService.ShowOpenApiDocument(openapi, csdl, csdlFilter, output, logger, cancellationToken); return 0; } diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index e46b34340..d0a49c209 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -57,7 +57,7 @@ public async Task InvokeAsync(InvocationContext context) var logger = loggerFactory.CreateLogger(); try { - await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, settingsFile, logLevel, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, cancellationToken); + await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, settingsFile, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, logger, cancellationToken); return 0; } diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs index 2faa771ea..416471d9e 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs @@ -30,7 +30,7 @@ public async Task InvokeAsync(InvocationContext context) var logger = loggerFactory.CreateLogger(); try { - await OpenApiService.ValidateOpenApiDocument(openapi, logLevel, cancellationToken); + await OpenApiService.ValidateOpenApiDocument(openapi, logger, cancellationToken); return 0; } catch (Exception ex) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index dfd1886a4..c54b65db5 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -28,8 +28,6 @@ using System.Xml; using System.Reflection; using Microsoft.Extensions.Configuration; -using System.Runtime.CompilerServices; -using System.Reflection.Metadata; namespace Microsoft.OpenApi.Hidi { @@ -48,22 +46,21 @@ public static async Task TransformOpenApiDocument( OpenApiFormat? format, bool terseOutput, string settingsFile, - LogLevel logLevel, bool inlineLocal, bool inlineExternal, string filterbyoperationids, string filterbytags, string filterbycollection, + ILogger logger, CancellationToken cancellationToken ) { - using var loggerFactory = Logger.ConfigureLogger(logLevel); - var logger = loggerFactory.CreateLogger(); + try { if (string.IsNullOrEmpty(openapi) && string.IsNullOrEmpty(csdl)) { - throw new ArgumentException("Please input a file path"); + throw new ArgumentException("Please input a file path or URL"); } if (output == null) { @@ -79,122 +76,136 @@ CancellationToken cancellationToken throw new IOException($"The file {output} already exists. Please input a new file path."); } - Stream stream; - OpenApiDocument document; - OpenApiFormat openApiFormat; - OpenApiSpecVersion openApiVersion; - var stopwatch = new Stopwatch(); + // Default to yaml and OpenApiVersion 3 during csdl to OpenApi conversion + OpenApiFormat openApiFormat = format ?? (!string.IsNullOrEmpty(openapi) ? GetOpenApiFormat(openapi, logger) : OpenApiFormat.Yaml); + OpenApiSpecVersion openApiVersion = version != null ? TryParseOpenApiSpecVersion(version) : OpenApiSpecVersion.OpenApi3_0; - if (!string.IsNullOrEmpty(csdl)) - { - using (logger.BeginScope($"Convert CSDL: {csdl}", csdl)) - { - stopwatch.Start(); - // Default to yaml and OpenApiVersion 3 during csdl to OpenApi conversion - openApiFormat = format ?? GetOpenApiFormat(csdl, logger); - openApiVersion = version != null ? TryParseOpenApiSpecVersion(version) : OpenApiSpecVersion.OpenApi3_0; - - stream = await GetStream(csdl, logger, cancellationToken); + OpenApiDocument document = await GetOpenApi(openapi, csdl, csdlFilter, settingsFile, inlineExternal, logger, cancellationToken); + document = await FilterOpenApiDocument(filterbyoperationids, filterbytags, filterbycollection, document, logger, cancellationToken); + WriteOpenApi(output, terseOutput, inlineLocal, inlineExternal, openApiFormat, openApiVersion, document, logger); + } + catch (TaskCanceledException) + { + Console.Error.WriteLine("CTRL+C pressed, aborting the operation."); + } + catch (Exception ex) + { + throw new InvalidOperationException($"Could not transform the document, reason: {ex.Message}", ex); + } + } - if (!string.IsNullOrEmpty(csdlFilter)) - { - XslCompiledTransform transform = GetFilterTransform(); - stream = ApplyFilter(csdl, csdlFilter, transform); - stream.Position = 0; - } + private static void WriteOpenApi(FileInfo output, bool terseOutput, bool inlineLocal, bool inlineExternal, OpenApiFormat openApiFormat, OpenApiSpecVersion openApiVersion, OpenApiDocument document, ILogger logger) + { + using (logger.BeginScope("Output")) + { + using var outputStream = output?.Create(); + var textWriter = outputStream != null ? new StreamWriter(outputStream) : Console.Out; - document = await ConvertCsdlToOpenApi(stream, settingsFile, cancellationToken); - stopwatch.Stop(); - logger.LogTrace("{timestamp}ms: Generated OpenAPI with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); - } - } - else + var settings = new OpenApiWriterSettings() { - stream = await GetStream(openapi, logger, cancellationToken); - stopwatch.Restart(); - var result = await ParseOpenApi(openapi, inlineExternal, logger, stream); - document = result.OpenApiDocument; - - openApiFormat = format ?? GetOpenApiFormat(openapi, logger); - openApiVersion = version != null ? TryParseOpenApiSpecVersion(version) : result.OpenApiDiagnostic.SpecificationVersion; - stopwatch.Stop(); - } + InlineLocalReferences = inlineLocal, + InlineExternalReferences = inlineExternal + }; - using (logger.BeginScope("Filter")) + IOpenApiWriter writer = openApiFormat switch { - Func predicate = null; + OpenApiFormat.Json => terseOutput ? new OpenApiJsonWriter(textWriter, settings, terseOutput) : new OpenApiJsonWriter(textWriter, settings, false), + OpenApiFormat.Yaml => new OpenApiYamlWriter(textWriter, settings), + _ => throw new ArgumentException("Unknown format"), + }; - // Check if filter options are provided, then slice the OpenAPI document - if (!string.IsNullOrEmpty(filterbyoperationids) && !string.IsNullOrEmpty(filterbytags)) - { - throw new InvalidOperationException("Cannot filter by operationIds and tags at the same time."); - } - if (!string.IsNullOrEmpty(filterbyoperationids)) - { - logger.LogTrace("Creating predicate based on the operationIds supplied."); - predicate = OpenApiFilterService.CreatePredicate(operationIds: filterbyoperationids); + logger.LogTrace("Serializing to OpenApi document using the provided spec version and writer"); - } - if (!string.IsNullOrEmpty(filterbytags)) - { - logger.LogTrace("Creating predicate based on the tags supplied."); - predicate = OpenApiFilterService.CreatePredicate(tags: filterbytags); + var stopwatch = new Stopwatch(); + stopwatch.Start(); + document.Serialize(writer, openApiVersion); + stopwatch.Stop(); - } - if (!string.IsNullOrEmpty(filterbycollection)) - { - var fileStream = await GetStream(filterbycollection, logger, cancellationToken); - var requestUrls = ParseJsonCollectionFile(fileStream, logger); + logger.LogTrace($"Finished serializing in {stopwatch.ElapsedMilliseconds}ms"); + textWriter.Flush(); + } + } - logger.LogTrace("Creating predicate based on the paths and Http methods defined in the Postman collection."); - predicate = OpenApiFilterService.CreatePredicate(requestUrls: requestUrls, source: document); - } - if (predicate != null) + // Get OpenAPI document either from OpenAPI or CSDL + private static async Task GetOpenApi(string openapi, string csdl, string csdlFilter, string settingsFile, bool inlineExternal, ILogger logger, CancellationToken cancellationToken) + { + OpenApiDocument document; + Stream stream; + + if (!string.IsNullOrEmpty(csdl)) + { + var stopwatch = new Stopwatch(); + using (logger.BeginScope($"Convert CSDL: {csdl}", csdl)) + { + stopwatch.Start(); + stream = await GetStream(csdl, logger, cancellationToken); + Stream filteredStream = null; + if (!string.IsNullOrEmpty(csdlFilter)) { - stopwatch.Restart(); - document = OpenApiFilterService.CreateFilteredDocument(document, predicate); - stopwatch.Stop(); - logger.LogTrace("{timestamp}ms: Creating filtered OpenApi document with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); + XslCompiledTransform transform = GetFilterTransform(); + filteredStream = ApplyFilterToCsdl(stream, csdlFilter, transform); + filteredStream.Position = 0; + stream.Dispose(); + stream = null; } + + document = await ConvertCsdlToOpenApi(filteredStream ?? stream, settingsFile, cancellationToken); + stopwatch.Stop(); + logger.LogTrace("{timestamp}ms: Generated OpenAPI with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); } + } + else + { + stream = await GetStream(openapi, logger, cancellationToken); + var result = await ParseOpenApi(openapi, inlineExternal, logger, stream); + document = result.OpenApiDocument; + } - using (logger.BeginScope("Output")) - { - ; - using var outputStream = output?.Create(); - var textWriter = outputStream != null ? new StreamWriter(outputStream) : Console.Out; + return document; + } - var settings = new OpenApiWriterSettings() - { - InlineLocalReferences = inlineLocal, - InlineExternalReferences = inlineExternal - }; + private static async Task FilterOpenApiDocument(string filterbyoperationids, string filterbytags, string filterbycollection, OpenApiDocument document, ILogger logger, CancellationToken cancellationToken) + { + using (logger.BeginScope("Filter")) + { + Func predicate = null; - IOpenApiWriter writer = openApiFormat switch - { - OpenApiFormat.Json => terseOutput ? new OpenApiJsonWriter(textWriter, settings, terseOutput) : new OpenApiJsonWriter(textWriter, settings, false), - OpenApiFormat.Yaml => new OpenApiYamlWriter(textWriter, settings), - _ => throw new ArgumentException("Unknown format"), - }; + // Check if filter options are provided, then slice the OpenAPI document + if (!string.IsNullOrEmpty(filterbyoperationids) && !string.IsNullOrEmpty(filterbytags)) + { + throw new InvalidOperationException("Cannot filter by operationIds and tags at the same time."); + } + if (!string.IsNullOrEmpty(filterbyoperationids)) + { + logger.LogTrace("Creating predicate based on the operationIds supplied."); + predicate = OpenApiFilterService.CreatePredicate(operationIds: filterbyoperationids); + + } + if (!string.IsNullOrEmpty(filterbytags)) + { + logger.LogTrace("Creating predicate based on the tags supplied."); + predicate = OpenApiFilterService.CreatePredicate(tags: filterbytags); - logger.LogTrace("Serializing to OpenApi document using the provided spec version and writer"); + } + if (!string.IsNullOrEmpty(filterbycollection)) + { + var fileStream = await GetStream(filterbycollection, logger, cancellationToken); + var requestUrls = ParseJsonCollectionFile(fileStream, logger); + logger.LogTrace("Creating predicate based on the paths and Http methods defined in the Postman collection."); + predicate = OpenApiFilterService.CreatePredicate(requestUrls: requestUrls, source: document); + } + if (predicate != null) + { + var stopwatch = new Stopwatch(); stopwatch.Start(); - document.Serialize(writer, openApiVersion); + document = OpenApiFilterService.CreateFilteredDocument(document, predicate); stopwatch.Stop(); - - logger.LogTrace($"Finished serializing in {stopwatch.ElapsedMilliseconds}ms"); - textWriter.Flush(); + logger.LogTrace("{timestamp}ms: Creating filtered OpenApi document with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); } } - catch(TaskCanceledException) - { - Console.Error.WriteLine("CTRL+C pressed, aborting the operation."); - } - catch (Exception ex) - { - throw new InvalidOperationException($"Could not transform the document, reason: {ex.Message}", ex); - } + + return document; } private static XslCompiledTransform GetFilterTransform() @@ -206,10 +217,10 @@ private static XslCompiledTransform GetFilterTransform() return transform; } - private static Stream ApplyFilter(string csdl, string entitySetOrSingleton, XslCompiledTransform transform) + private static Stream ApplyFilterToCsdl(Stream csdlStream, string entitySetOrSingleton, XslCompiledTransform transform) { Stream stream; - StreamReader inputReader = new(csdl); + StreamReader inputReader = new(csdlStream); XmlReader inputXmlReader = XmlReader.Create(inputReader); MemoryStream filteredStream = new(); StreamWriter writer = new(filteredStream); @@ -225,11 +236,9 @@ private static Stream ApplyFilter(string csdl, string entitySetOrSingleton, XslC ///
public static async Task ValidateOpenApiDocument( string openapi, - LogLevel logLevel, + ILogger logger, CancellationToken cancellationToken) { - using var loggerFactory = Logger.ConfigureLogger(logLevel); - var logger = loggerFactory.CreateLogger(); try { if (string.IsNullOrEmpty(openapi)) @@ -250,13 +259,17 @@ public static async Task ValidateOpenApiDocument( logger.LogInformation(statsVisitor.GetStatisticsReport()); } } + catch (TaskCanceledException) + { + Console.Error.WriteLine("CTRL+C pressed, aborting the operation."); + } catch (Exception ex) { throw new InvalidOperationException($"Could not validate the document, reason: {ex.Message}", ex); } } - private static async Task ParseOpenApi(string openApiFile, bool inlineExternal, ILogger logger, Stream stream) + private static async Task ParseOpenApi(string openApiFile, bool inlineExternal, ILogger logger, Stream stream) { ReadResult result; Stopwatch stopwatch = Stopwatch.StartNew(); @@ -486,57 +499,60 @@ private static string GetInputPathExtension(string openapi = null, string csdl = return extension; } - private static ILoggerFactory ConfigureLoggerInstance(LogLevel loglevel) + internal static async Task ShowOpenApiDocument(string openapi, string csdl, string csdlFilter, FileInfo output, ILogger logger, CancellationToken cancellationToken) { - // Configure logger options -#if DEBUG - loglevel = loglevel > LogLevel.Debug ? LogLevel.Debug : loglevel; -#endif - - return Microsoft.Extensions.Logging.LoggerFactory.Create((builder) => { - builder - .AddSimpleConsole(c => { - c.IncludeScopes = true; - }) -#if DEBUG - .AddDebug() -#endif - .SetMinimumLevel(loglevel); - }); - } - - internal static async Task ShowOpenApiDocument(string openapi, FileInfo output, LogLevel logLevel, CancellationToken cancellationToken) - { - using var loggerFactory = Logger.ConfigureLogger(logLevel); - var logger = loggerFactory.CreateLogger(); try { - if (string.IsNullOrEmpty(openapi)) + if (string.IsNullOrEmpty(openapi) && string.IsNullOrEmpty(csdl)) { - throw new ArgumentNullException(nameof(openapi)); + throw new ArgumentException("Please input a file path or URL"); } - using var stream = await GetStream(openapi, logger, cancellationToken); - var result = await ParseOpenApi(openapi, false, logger, stream); + var document = await GetOpenApi(openapi, csdl, csdlFilter, null, false, logger, cancellationToken); using (logger.BeginScope("Creating diagram")) { - // Create OpenApiUrlTree from document + // If output is null, create a HTML file in the user's temporary directory + if (output == null) + { + var tempPath = Path.GetTempPath(); - using var file = new FileStream(output.FullName, FileMode.Create); - using var writer = new StreamWriter(file); - WriteTreeDocument(openapi, result.OpenApiDocument, writer); + output = new FileInfo(Path.Combine(tempPath, "apitree.html")); + using (var file = new FileStream(output.FullName, FileMode.Create)) + { + using var writer = new StreamWriter(file); + WriteTreeDocumentAsHtml(openapi ?? csdl, document, writer); + } + logger.LogTrace("Created Html document with diagram "); - logger.LogTrace("Finished walking through the OpenApi document. "); + // Launch a browser to display the output html file + var process = new Process(); + process.StartInfo.FileName = output.FullName; + process.StartInfo.UseShellExecute = true; + process.Start(); + } + else // Write diagram as Markdown document to output file + { + using (var file = new FileStream(output.FullName, FileMode.Create)) + { + using var writer = new StreamWriter(file); + WriteTreeDocumentAsMarkdown(openapi ?? csdl, document, writer); + } + logger.LogTrace("Created markdown document with diagram "); + } } } + catch (TaskCanceledException) + { + Console.Error.WriteLine("CTRL+C pressed, aborting the operation."); + } catch (Exception ex) { throw new InvalidOperationException($"Could not generate the document, reason: {ex.Message}", ex); } } - private static void LogErrors(ILogger logger, ReadResult result) + private static void LogErrors(ILogger logger, ReadResult result) { var context = result.OpenApiDiagnostic; if (context.Errors.Count != 0) @@ -551,13 +567,13 @@ private static void LogErrors(ILogger logger, ReadResult result) } } - internal static void WriteTreeDocument(string openapiUrl, OpenApiDocument document, StreamWriter writer) + internal static void WriteTreeDocumentAsMarkdown(string openapiUrl, OpenApiDocument document, StreamWriter writer) { var rootNode = OpenApiUrlTreeNode.Create(document, "main"); writer.WriteLine("# " + document.Info.Title); writer.WriteLine(); - writer.WriteLine("OpenAPI: " + openapiUrl); + writer.WriteLine("API Description: " + openapiUrl); writer.WriteLine(@"
"); // write a span for each mermaidcolorscheme @@ -571,5 +587,54 @@ internal static void WriteTreeDocument(string openapiUrl, OpenApiDocument docume rootNode.WriteMermaid(writer); writer.WriteLine("```"); } + + internal static void WriteTreeDocumentAsHtml(string sourceUrl, OpenApiDocument document, StreamWriter writer, bool asHtmlFile = false) + { + var rootNode = OpenApiUrlTreeNode.Create(document, "main"); + + writer.WriteLine(@" + + + + + + +"); + writer.WriteLine("

" + document.Info.Title + "

"); + writer.WriteLine(); + writer.WriteLine($"

API Description: {sourceUrl}

"); + + writer.WriteLine(@"
"); + // write a span for each mermaidcolorscheme + foreach (var style in OpenApiUrlTreeNode.MermaidNodeStyles) + { + writer.WriteLine($"{style.Key.Replace("_", " ")}"); + } + writer.WriteLine("
"); + writer.WriteLine("
"); + writer.WriteLine(""); + rootNode.WriteMermaid(writer); + writer.WriteLine(""); + + // Write script tag to include JS library for rendering markdown + writer.WriteLine(@""); + // Write script tag to include JS library for rendering mermaid + writer.WriteLine("(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText(fileinfo.FullName); Assert.Contains("graph LR", output); @@ -124,6 +146,22 @@ public void InvokeShowCommand() } + [Fact] + public void InvokeShowCommandWithoutOutput() + { + var rootCommand = Program.CreateRootCommand(); + var args = new string[] { "show", "-d", ".\\UtilityFiles\\SampleOpenApi.yml" }; + var parseResult = rootCommand.Parse(args); + var handler = rootCommand.Subcommands.Where(c => c.Name == "show").First().Handler; + var context = new InvocationContext(parseResult); + + handler.Invoke(context); + + var output = File.ReadAllText(Path.Combine(Path.GetTempPath(), "apitree.html")); + Assert.Contains("graph LR", output); + } + + // Relatively useless test to keep the code coverage metrics happy [Fact] public void CreateRootCommand() From 8e2d470b7b544061d0171e820809f4ac6e4b3eeb Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sat, 14 Jan 2023 21:03:57 -0500 Subject: [PATCH 380/855] Used random file in a hidi folder to address security concerns. --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 12 +++++++++--- .../Services/OpenApiServiceTests.cs | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index c54b65db5..2cc188865 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -515,9 +515,15 @@ internal static async Task ShowOpenApiDocument(string openapi, string csdl, stri // If output is null, create a HTML file in the user's temporary directory if (output == null) { - var tempPath = Path.GetTempPath(); + var tempPath = Path.GetTempPath() + "/hidi/"; + if(!File.Exists(tempPath)) + { + Directory.CreateDirectory(tempPath); + } + + var fileName = Path.GetRandomFileName(); - output = new FileInfo(Path.Combine(tempPath, "apitree.html")); + output = new FileInfo(Path.Combine(tempPath, fileName + ".html")); using (var file = new FileStream(output.FullName, FileMode.Create)) { using var writer = new StreamWriter(file); @@ -526,7 +532,7 @@ internal static async Task ShowOpenApiDocument(string openapi, string csdl, stri logger.LogTrace("Created Html document with diagram "); // Launch a browser to display the output html file - var process = new Process(); + using var process = new Process(); process.StartInfo.FileName = output.FullName; process.StartInfo.UseShellExecute = true; process.Start(); diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 09ac6fb04..aa49ff520 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -80,6 +80,7 @@ public void ReturnOpenApiConvertSettingsWhenSettingsFileIsProvided(string filePa } } + [Fact] public void ShowCommandGeneratesMermaidDiagramAsMarkdown() { @@ -130,6 +131,22 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() Assert.Contains("graph LR", output); } + [Fact] + public void InvokeTransformCommand() + { + var rootCommand = Program.CreateRootCommand(); + var args = new string[] { "transform", "-d", ".\\UtilityFiles\\SampleOpenApi.yml", "-o", "sample.json" }; + var parseResult = rootCommand.Parse(args); + var handler = rootCommand.Subcommands.Where(c => c.Name == "transform").First().Handler; + var context = new InvocationContext(parseResult); + + handler.Invoke(context); + + var output = File.ReadAllText("sample.json"); + Assert.NotEmpty(output); + } + + [Fact] public void InvokeShowCommand() { From c23694cfe43478d77dc2128452e46e21f61fdb03 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 15 Jan 2023 11:11:21 -0500 Subject: [PATCH 381/855] Fixed code smell relating to LogError --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 2cc188865..8d7ea774e 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -567,7 +567,7 @@ private static void LogErrors(ILogger logger, ReadResult result) { foreach (var error in context.Errors) { - logger.LogError(error.ToString()); + logger.LogError($"Detected error during parsing: {error}",error.ToString()); } } } From 6a3dd015694bd07f883fe4e00f6970f9337896a7 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 15 Jan 2023 11:11:48 -0500 Subject: [PATCH 382/855] Added test to call Transform command directly so that code coverage will actually see it. --- .../Services/OpenApiServiceTests.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index aa49ff520..995ce1f02 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -131,6 +131,18 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() Assert.Contains("graph LR", output); } + + [Fact] + public async Task TransformCommandConvertsOpenApi() + { + var fileinfo = new FileInfo("sample.json"); + // create a dummy ILogger instance for testing + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml",null, null, fileinfo, true, null, null,false,null,false,false,null,null,null,new Logger(new LoggerFactory()), new CancellationToken()); + + var output = File.ReadAllText("sample.json"); + Assert.NotEmpty(output); + } + [Fact] public void InvokeTransformCommand() { From 8ff70a18b7f6b3e5568e5501f629c172f301f0d1 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 16 Jan 2023 13:18:00 -0500 Subject: [PATCH 383/855] Removed unnecessary test that was breaking --- .../Services/OpenApiServiceTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 995ce1f02..bdb5827b1 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -147,7 +147,7 @@ public async Task TransformCommandConvertsOpenApi() public void InvokeTransformCommand() { var rootCommand = Program.CreateRootCommand(); - var args = new string[] { "transform", "-d", ".\\UtilityFiles\\SampleOpenApi.yml", "-o", "sample.json" }; + var args = new string[] { "transform", "-d", ".\\UtilityFiles\\SampleOpenApi.yml", "-o", "sample.json","--co" }; var parseResult = rootCommand.Parse(args); var handler = rootCommand.Subcommands.Where(c => c.Name == "transform").First().Handler; var context = new InvocationContext(parseResult); From b95cda39f2a80f50889ded12fc85b3eb23805866 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 16 Jan 2023 13:51:39 -0500 Subject: [PATCH 384/855] This time I included the change --- .../Services/OpenApiServiceTests.cs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index bdb5827b1..be1ca18e8 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -175,20 +175,6 @@ public void InvokeShowCommand() } - [Fact] - public void InvokeShowCommandWithoutOutput() - { - var rootCommand = Program.CreateRootCommand(); - var args = new string[] { "show", "-d", ".\\UtilityFiles\\SampleOpenApi.yml" }; - var parseResult = rootCommand.Parse(args); - var handler = rootCommand.Subcommands.Where(c => c.Name == "show").First().Handler; - var context = new InvocationContext(parseResult); - - handler.Invoke(context); - - var output = File.ReadAllText(Path.Combine(Path.GetTempPath(), "apitree.html")); - Assert.Contains("graph LR", output); - } // Relatively useless test to keep the code coverage metrics happy From 230af2f1009769756ade41e855be6f74e4985898 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 16 Jan 2023 13:57:18 -0500 Subject: [PATCH 385/855] Added missing comments for public APIs --- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 870fb36d9..c8e2da03f 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -341,7 +341,7 @@ private static string SanitizeMermaidNode(string token) public class MermaidNodeStyle { /// - /// + /// Create a style that defines the color and shape of a diagram element /// /// /// @@ -352,18 +352,18 @@ internal MermaidNodeStyle(string color, MermaidNodeShape shape) } /// - /// + /// The CSS color name of the diagram element /// public string Color { get; } /// - /// + /// The shape of the diagram element /// public MermaidNodeShape Shape { get; } } /// - /// + /// Shapes supported by Mermaid diagrams /// public enum MermaidNodeShape { From 2b82a74b805be0a4a9971b3fc0cbc6cd11fa2518 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 16 Jan 2023 14:47:07 -0500 Subject: [PATCH 386/855] Added more tests to meet the coverage gods --- .../Services/OpenApiServiceTests.cs | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index be1ca18e8..dbfbce221 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -131,6 +131,30 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() Assert.Contains("graph LR", output); } + [Fact] + public async Task ShowCommandGeneratesMermaidMarkdownFileFromCsdlWithMermaidDiagram() + { + var fileinfo = new FileInfo("sample.md"); + // create a dummy ILogger instance for testing + await OpenApiService.ShowOpenApiDocument(null, "UtilityFiles\\Todo.xml", "todos", fileinfo, new Logger(new LoggerFactory()), new CancellationToken()); + + var output = File.ReadAllText(fileinfo.FullName); + Assert.Contains("graph LR", output); + } + + [Fact] + public async Task ThrowIfURLIsNotResolvableWhenValidating() + { + var message = Assert.ThrowsAsync(async () => + await OpenApiService.ValidateOpenApiDocument("https://example.org/itdoesnmatter", new Logger(new LoggerFactory()), new CancellationToken())); + } + + [Fact] + public async Task ThrowIfFileDoesNotExistWhenValidating() + { + var message = Assert.ThrowsAsync(async () => + await OpenApiService.ValidateOpenApiDocument("aFileThatBetterNotExist.fake", new Logger(new LoggerFactory()), new CancellationToken())); + } [Fact] public async Task TransformCommandConvertsOpenApi() @@ -175,8 +199,6 @@ public void InvokeShowCommand() } - - // Relatively useless test to keep the code coverage metrics happy [Fact] public void CreateRootCommand() From 45372397dfe9514ac55c1f873919c7587807a599 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 16 Jan 2023 15:07:01 -0500 Subject: [PATCH 387/855] More sacrifices made --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 24 +++++++++------ .../Services/OpenApiServiceTests.cs | 30 +++++++++++++++++-- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 8d7ea774e..c4653353a 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -55,18 +55,19 @@ public static async Task TransformOpenApiDocument( CancellationToken cancellationToken ) { + if (string.IsNullOrEmpty(openapi) && string.IsNullOrEmpty(csdl)) + { + throw new ArgumentException("Please input a file path or URL"); + } try { - if (string.IsNullOrEmpty(openapi) && string.IsNullOrEmpty(csdl)) - { - throw new ArgumentException("Please input a file path or URL"); - } if (output == null) { var inputExtension = GetInputPathExtension(openapi, csdl); output = new FileInfo($"./output{inputExtension}"); }; + if (cleanoutput && output.Exists) { output.Delete(); @@ -87,7 +88,11 @@ CancellationToken cancellationToken catch (TaskCanceledException) { Console.Error.WriteLine("CTRL+C pressed, aborting the operation."); - } + } + catch (IOException) + { + throw; + } catch (Exception ex) { throw new InvalidOperationException($"Could not transform the document, reason: {ex.Message}", ex); @@ -239,12 +244,13 @@ public static async Task ValidateOpenApiDocument( ILogger logger, CancellationToken cancellationToken) { + if (string.IsNullOrEmpty(openapi)) + { + throw new ArgumentNullException(nameof(openapi)); + } + try { - if (string.IsNullOrEmpty(openapi)) - { - throw new ArgumentNullException(nameof(openapi)); - } using var stream = await GetStream(openapi, logger, cancellationToken); var result = await ParseOpenApi(openapi, false, logger, stream); diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index dbfbce221..d397e4163 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -142,20 +142,38 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileFromCsdlWithMermaidDiag Assert.Contains("graph LR", output); } + [Fact] + public async Task ThrowIfOpenApiUrlIsNotProvidedWhenValidating() + { + await Assert.ThrowsAsync(async () => + await OpenApiService.ValidateOpenApiDocument("", new Logger(new LoggerFactory()), new CancellationToken())); + } + + [Fact] public async Task ThrowIfURLIsNotResolvableWhenValidating() { - var message = Assert.ThrowsAsync(async () => + await Assert.ThrowsAsync(async () => await OpenApiService.ValidateOpenApiDocument("https://example.org/itdoesnmatter", new Logger(new LoggerFactory()), new CancellationToken())); } [Fact] public async Task ThrowIfFileDoesNotExistWhenValidating() { - var message = Assert.ThrowsAsync(async () => + await Assert.ThrowsAsync(async () => await OpenApiService.ValidateOpenApiDocument("aFileThatBetterNotExist.fake", new Logger(new LoggerFactory()), new CancellationToken())); } + [Fact] + public async Task ValidateCommandProcessesOpenApi() + { + // create a dummy ILogger instance for testing + await OpenApiService.ValidateOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", new Logger(new LoggerFactory()), new CancellationToken()); + + Assert.True(true); + } + + [Fact] public async Task TransformCommandConvertsOpenApi() { @@ -167,6 +185,14 @@ public async Task TransformCommandConvertsOpenApi() Assert.NotEmpty(output); } + [Fact] + public async Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() + { + await Assert.ThrowsAsync(async () => + await OpenApiService.TransformOpenApiDocument(null, null, null, null, true, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken())); + + } + [Fact] public void InvokeTransformCommand() { From ff554399112e25665162c01e5dea5c90b8d78a9a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Jan 2023 21:01:20 +0000 Subject: [PATCH 388/855] Bump docker/build-push-action from 3.2.0 to 3.3.0 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3.2.0 to 3.3.0. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v3.2.0...v3.3.0) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index b289449cf..2776b607a 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -30,13 +30,13 @@ jobs: id: getversion - name: Push to GitHub Packages - Nightly if: ${{ github.ref == 'refs/heads/vnext' }} - uses: docker/build-push-action@v3.2.0 + uses: docker/build-push-action@v3.3.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly - name: Push to GitHub Packages - Release if: ${{ github.ref == 'refs/heads/master' }} - uses: docker/build-push-action@v3.2.0 + uses: docker/build-push-action@v3.3.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest,${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.getversion.outputs.version }} From 96fae889d55f4c12ea176c4f8d338d6f89d9fdb5 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 16 Jan 2023 16:39:59 -0500 Subject: [PATCH 389/855] Will these be the tests that achieve the magical goal? --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 4 ++-- .../Services/OpenApiServiceTests.cs | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index c4653353a..a952f414b 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -103,8 +103,8 @@ private static void WriteOpenApi(FileInfo output, bool terseOutput, bool inlineL { using (logger.BeginScope("Output")) { - using var outputStream = output?.Create(); - var textWriter = outputStream != null ? new StreamWriter(outputStream) : Console.Out; + using var outputStream = output.Create(); + var textWriter = new StreamWriter(outputStream); var settings = new OpenApiWriterSettings() { diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index d397e4163..11b5bc4f3 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -185,6 +185,26 @@ public async Task TransformCommandConvertsOpenApi() Assert.NotEmpty(output); } + [Fact] + public async Task TransformCommandConvertsOpenApiWithDefaultOutputname() + { + // create a dummy ILogger instance for testing + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + + var output = File.ReadAllText("output.yml"); + Assert.NotEmpty(output); + } + + [Fact] + public async Task TransformCommandConvertsOpenApiWithDefaultOutputnameAndSwitchFormat() + { + // create a dummy ILogger instance for testing + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, "3.0", OpenApiFormat.Yaml, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + + var output = File.ReadAllText("output.yml"); + Assert.NotEmpty(output); + } + [Fact] public async Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() { From 7638805bf8d2c1a5d169bc1900b32e167c1c8b87 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 16 Jan 2023 17:09:37 -0500 Subject: [PATCH 390/855] I am confidence I have enough tests now --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 6 ++- .../Services/OpenApiServiceTests.cs | 42 ++++++++++++++----- 2 files changed, 37 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index a952f414b..64a23dff3 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -505,7 +505,7 @@ private static string GetInputPathExtension(string openapi = null, string csdl = return extension; } - internal static async Task ShowOpenApiDocument(string openapi, string csdl, string csdlFilter, FileInfo output, ILogger logger, CancellationToken cancellationToken) + internal static async Task ShowOpenApiDocument(string openapi, string csdl, string csdlFilter, FileInfo output, ILogger logger, CancellationToken cancellationToken) { try { @@ -542,6 +542,8 @@ internal static async Task ShowOpenApiDocument(string openapi, string csdl, stri process.StartInfo.FileName = output.FullName; process.StartInfo.UseShellExecute = true; process.Start(); + + return output.FullName; } else // Write diagram as Markdown document to output file { @@ -551,6 +553,7 @@ internal static async Task ShowOpenApiDocument(string openapi, string csdl, stri WriteTreeDocumentAsMarkdown(openapi ?? csdl, document, writer); } logger.LogTrace("Created markdown document with diagram "); + return output.FullName; } } } @@ -562,6 +565,7 @@ internal static async Task ShowOpenApiDocument(string openapi, string csdl, stri { throw new InvalidOperationException($"Could not generate the document, reason: {ex.Message}", ex); } + return null; } private static void LogErrors(ILogger logger, ReadResult result) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 11b5bc4f3..ac2048ad1 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -84,11 +84,13 @@ public void ReturnOpenApiConvertSettingsWhenSettingsFileIsProvided(string filePa [Fact] public void ShowCommandGeneratesMermaidDiagramAsMarkdown() { - var openApiDoc = new OpenApiDocument(); - openApiDoc.Info = new OpenApiInfo + var openApiDoc = new OpenApiDocument { - Title = "Test", - Version = "1.0.0" + Info = new OpenApiInfo + { + Title = "Test", + Version = "1.0.0" + } }; var stream = new MemoryStream(); using var writer = new StreamWriter(stream); @@ -101,13 +103,15 @@ public void ShowCommandGeneratesMermaidDiagramAsMarkdown() } [Fact] - public void ShowCommandGeneratesMermaidDiagramAsHtml () + public void ShowCommandGeneratesMermaidDiagramAsHtml() { - var openApiDoc = new OpenApiDocument(); - openApiDoc.Info = new OpenApiInfo + var openApiDoc = new OpenApiDocument { - Title = "Test", - Version = "1.0.0" + Info = new OpenApiInfo + { + Title = "Test", + Version = "1.0.0" + } }; var stream = new MemoryStream(); using var writer = new StreamWriter(stream); @@ -118,7 +122,7 @@ public void ShowCommandGeneratesMermaidDiagramAsHtml () var output = reader.ReadToEnd(); Assert.Contains("graph LR", output); } - + [Fact] public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() @@ -131,6 +135,13 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() Assert.Contains("graph LR", output); } + [Fact] + public async Task ShowCommandGeneratesMermaidHtmlFileWithMermaidDiagram() + { + var filePath = await OpenApiService.ShowOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + Assert.True(File.Exists(filePath)); + } + [Fact] public async Task ShowCommandGeneratesMermaidMarkdownFileFromCsdlWithMermaidDiagram() { @@ -185,6 +196,7 @@ public async Task TransformCommandConvertsOpenApi() Assert.NotEmpty(output); } + [Fact] public async Task TransformCommandConvertsOpenApiWithDefaultOutputname() { @@ -195,6 +207,16 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputname() Assert.NotEmpty(output); } + [Fact] + public async Task TransformCommandConvertsCsdlWithDefaultOutputname() + { + // create a dummy ILogger instance for testing + await OpenApiService.TransformOpenApiDocument(null, "UtilityFiles\\Todo.xml", null, null, true, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + + var output = File.ReadAllText("output.yml"); + Assert.NotEmpty(output); + } + [Fact] public async Task TransformCommandConvertsOpenApiWithDefaultOutputnameAndSwitchFormat() { From a8a693d5d34193a86299946bb6fdf8cee8aa3d64 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 16 Jan 2023 17:43:45 -0500 Subject: [PATCH 391/855] Added a using to dispose a StreamReader --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 64a23dff3..e63a2b9ba 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -225,7 +225,7 @@ private static XslCompiledTransform GetFilterTransform() private static Stream ApplyFilterToCsdl(Stream csdlStream, string entitySetOrSingleton, XslCompiledTransform transform) { Stream stream; - StreamReader inputReader = new(csdlStream); + using StreamReader inputReader = new(csdlStream, leaveOpen: true); XmlReader inputXmlReader = XmlReader.Create(inputReader); MemoryStream filteredStream = new(); StreamWriter writer = new(filteredStream); From 4c4ebd360ee1166760bbf4dae7ee106ae907f0fd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 19 Jan 2023 21:01:35 +0000 Subject: [PATCH 392/855] Bump Verify.Xunit from 19.6.0 to 19.7.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.6.0 to 19.7.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.6.0...19.7.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 7c580d2f1..367042ce2 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From f700fdb7f678445a8d9b56dcaa7fda7c21bbec97 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 20 Jan 2023 21:01:28 +0000 Subject: [PATCH 393/855] Bump Verify.Xunit from 19.7.0 to 19.7.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.7.0 to 19.7.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.7.0...19.7.1) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 367042ce2..e35db421b 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From c4e9f3c5415b7fa110bbd57fdc32c06597326c4c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 20 Jan 2023 21:01:31 +0000 Subject: [PATCH 394/855] Bump Microsoft.OpenApi.OData from 1.2.0-preview9 to 1.2.0 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.2.0-preview9 to 1.2.0. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 232830c37..a53d697b5 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From f57ac37fc42d6e3383d7dbdfecc79a92a45976f1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Jan 2023 21:00:58 +0000 Subject: [PATCH 395/855] Bump docker/build-push-action from 3.3.0 to 4.0.0 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3.3.0 to 4.0.0. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v3.3.0...v4.0.0) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 2776b607a..5d0ed5098 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -30,13 +30,13 @@ jobs: id: getversion - name: Push to GitHub Packages - Nightly if: ${{ github.ref == 'refs/heads/vnext' }} - uses: docker/build-push-action@v3.3.0 + uses: docker/build-push-action@v4.0.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly - name: Push to GitHub Packages - Release if: ${{ github.ref == 'refs/heads/master' }} - uses: docker/build-push-action@v3.3.0 + uses: docker/build-push-action@v4.0.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest,${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.getversion.outputs.version }} From 2445be90350984e9404dadf4897b0463d769f7f8 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 31 Jan 2023 14:43:51 +0300 Subject: [PATCH 396/855] Declare the return type as a task of type int in Main() method for us to get the correct exit code in case of a critical error or unsuccessful operation --- src/Microsoft.OpenApi.Hidi/Program.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 056da9ab2..8d3cc3243 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -15,13 +15,12 @@ namespace Microsoft.OpenApi.Hidi { static class Program { - static async Task Main(string[] args) + static async Task Main(string[] args) { var rootCommand = CreateRootCommand(); // Parse the incoming args and invoke the handler - await rootCommand.InvokeAsync(args); - + return await rootCommand.InvokeAsync(args); } internal static RootCommand CreateRootCommand() From e557a3921d44b037d117ae5aed8a157b66609c2d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 31 Jan 2023 14:44:03 +0300 Subject: [PATCH 397/855] Bump up hidi version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index a53d697b5..072c9d3ee 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.2.0 + 1.2.1 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET From 7bd51e59cfa5f6b18dfa70ca57bde724fc9b2fa7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 31 Jan 2023 17:45:04 +0300 Subject: [PATCH 398/855] use platform-specific character for separating directory levels in a path string --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index e63a2b9ba..c9214030b 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -287,7 +287,7 @@ private static async Task ParseOpenApi(string openApiFile, bool inli { RuleSet = ValidationRuleSet.GetDefaultRuleSet(), LoadExternalRefs = inlineExternal, - BaseUrl = openApiFile.StartsWith("http") ? new Uri(openApiFile) : new Uri("file:" + new FileInfo(openApiFile).DirectoryName + "\\") + BaseUrl = openApiFile.StartsWith("http") ? new Uri(openApiFile) : new Uri("file:" + new FileInfo(openApiFile).DirectoryName + Path.DirectorySeparatorChar) } ).ReadAsync(stream); From 6f06ae470710c6a15d06bd466082044279559da6 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 31 Jan 2023 17:45:19 +0300 Subject: [PATCH 399/855] Update test with correct operationId --- .../Services/OpenApiServiceTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index ac2048ad1..f95acd879 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -38,8 +38,8 @@ public async Task ReturnConvertedCSDLFile() } [Theory] - [InlineData("Todos.Todo.UpdateTodoById",null, 1)] - [InlineData("Todos.Todo.ListTodo",null, 1)] + [InlineData("Todos.Todo.UpdateTodo",null, 1)] + [InlineData("Todos.Todo.ListTodo", null, 1)] [InlineData(null, "Todos.Todo", 4)] public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocument(string operationIds, string tags, int expectedPathCount) { From 3b8f30eb3d1bfc46d52894e8578ca1cba3d35b22 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 31 Jan 2023 18:56:05 +0300 Subject: [PATCH 400/855] Update lib versions --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index e65b857bf..8373654b3 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.5.0 + 1.6.0 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index e13da5d5e..44a556cae 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.5.0 + 1.6.0 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From b128172b6cb8db6e9413fd971aa425f3615e61a3 Mon Sep 17 00:00:00 2001 From: Ztare <60300498+Ztare@users.noreply.github.com> Date: Wed, 1 Feb 2023 10:56:04 +0300 Subject: [PATCH 401/855] Fix loop detector OpenApiSchema. Missed settings.LoopDetector.PopLoop in SerializeAsV2 --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 513b865df..0176ea1d9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -536,6 +536,11 @@ internal void SerializeAsV2( } target.SerializeAsV2WithoutReference(writer, parentRequiredProperties, propertyName); + + if (Reference != null) + { + settings.LoopDetector.PopLoop(); + } } /// From daaa47c9ffb34caef897f604c3771d6ec7e422fd Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 1 Feb 2023 10:21:52 -0500 Subject: [PATCH 402/855] - fixes a bug where the protocol definition would fail on linux OS --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 072c9d3ee..b30d770de 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.2.1 + 1.2.2 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index c9214030b..fa0b5ff51 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -285,9 +285,10 @@ private static async Task ParseOpenApi(string openApiFile, bool inli result = await new OpenApiStreamReader(new OpenApiReaderSettings { - RuleSet = ValidationRuleSet.GetDefaultRuleSet(), LoadExternalRefs = inlineExternal, - BaseUrl = openApiFile.StartsWith("http") ? new Uri(openApiFile) : new Uri("file:" + new FileInfo(openApiFile).DirectoryName + Path.DirectorySeparatorChar) + BaseUrl = openApiFile.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? + new Uri(openApiFile) : + new Uri("file://" + new FileInfo(openApiFile).DirectoryName + Path.DirectorySeparatorChar) } ).ReadAsync(stream); From f0a5fcb2bd7bd02ec98321bfeb81a487105b5daa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Feb 2023 21:02:32 +0000 Subject: [PATCH 403/855] Bump Verify.Xunit from 19.7.1 to 19.8.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.7.1 to 19.8.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.7.1...19.8.1) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index e35db421b..8dd30386d 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From d554cbfe5d427bf9f2637d41ece0a57da6dc50a2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 2 Feb 2023 21:01:20 +0000 Subject: [PATCH 404/855] Bump Verify.Xunit from 19.8.1 to 19.8.2 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.8.1 to 19.8.2. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.8.1...19.8.2) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 8dd30386d..62af2ee60 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 7e4355ebf4ad06cd45cb883f40c8a73abe41f87f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 3 Feb 2023 21:01:22 +0000 Subject: [PATCH 405/855] Bump Verify.Xunit from 19.8.2 to 19.8.3 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.8.2 to 19.8.3. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.8.2...19.8.3) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 62af2ee60..6c31d691b 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From d1ff59924702cb7eb7b23dd8391bfbd55228aeec Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Feb 2023 21:01:48 +0000 Subject: [PATCH 406/855] Bump Verify.Xunit from 19.8.3 to 19.9.2 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.8.3 to 19.9.2. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 6c31d691b..fc9274aea 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 279673c4c8a3c4be4688e90298f2cb185c628d20 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 7 Feb 2023 21:01:54 +0000 Subject: [PATCH 407/855] Bump Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers Bumps [Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers](https://github.com/dotnet/upgrade-assistant) from 0.4.355802 to 0.4.410601. - [Release notes](https://github.com/dotnet/upgrade-assistant/releases) - [Changelog](https://github.com/dotnet/upgrade-assistant/blob/main/CHANGELOG.md) - [Commits](https://github.com/dotnet/upgrade-assistant/commits) --- updated-dependencies: - dependency-name: Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index ad6989d05..c7ab75af4 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -7,7 +7,7 @@ true - + all From 441584b94e9e1b4823a5e6516190483f58a2eabf Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 9 Feb 2023 14:28:19 -0500 Subject: [PATCH 408/855] - fixes a bug where copy constructors would fail on relative urls --- src/Microsoft.OpenApi/Models/OpenApiContact.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiLicense.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs | 8 ++++---- src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs | 8 ++++---- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 352697bf2..93cb11bca 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -46,7 +46,7 @@ public OpenApiContact() { } public OpenApiContact(OpenApiContact contact) { Name = contact?.Name ?? Name; - Url = contact?.Url != null ? new Uri(contact.Url.OriginalString) : null; + Url = contact?.Url != null ? new Uri(contact.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; Email = contact?.Email ?? Email; Extensions = contact?.Extensions != null ? new Dictionary(contact.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 9ad3b9e55..345f07d59 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -32,7 +32,7 @@ public class OpenApiExternalDocs : IOpenApiSerializable, IOpenApiExtensible /// /// Parameter-less constructor /// - public OpenApiExternalDocs() {} + public OpenApiExternalDocs() { } /// /// Initializes a copy of an object @@ -40,7 +40,7 @@ public OpenApiExternalDocs() {} public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) { Description = externalDocs?.Description ?? Description; - Url = externalDocs?.Url != null ? new Uri(externalDocs.Url.OriginalString) : null; + Url = externalDocs?.Url != null ? new Uri(externalDocs.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; Extensions = externalDocs?.Extensions != null ? new Dictionary(externalDocs.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 1a8d1a4d8..866515835 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -32,7 +32,7 @@ public class OpenApiLicense : IOpenApiSerializable, IOpenApiExtensible /// /// Parameterless constructor /// - public OpenApiLicense() {} + public OpenApiLicense() { } /// /// Initializes a copy of an object @@ -40,7 +40,7 @@ public OpenApiLicense() {} public OpenApiLicense(OpenApiLicense license) { Name = license?.Name ?? Name; - Url = license?.Url != null ? new Uri(license.Url.OriginalString) : null; + Url = license?.Url != null ? new Uri(license.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; Extensions = license?.Extensions != null ? new Dictionary(license.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index c6f91fbd8..9c12fb5a9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -44,16 +44,16 @@ public class OpenApiOAuthFlow : IOpenApiSerializable, IOpenApiExtensible /// /// Parameterless constructor /// - public OpenApiOAuthFlow() {} + public OpenApiOAuthFlow() { } /// /// Initializes a copy of an object /// public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) { - AuthorizationUrl = oAuthFlow?.AuthorizationUrl != null ? new Uri(oAuthFlow.AuthorizationUrl.OriginalString) : null; - TokenUrl = oAuthFlow?.TokenUrl != null ? new Uri(oAuthFlow.TokenUrl.OriginalString) : null; - RefreshUrl = oAuthFlow?.RefreshUrl != null ? new Uri(oAuthFlow.RefreshUrl.OriginalString) : null; + AuthorizationUrl = oAuthFlow?.AuthorizationUrl != null ? new Uri(oAuthFlow.AuthorizationUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; + TokenUrl = oAuthFlow?.TokenUrl != null ? new Uri(oAuthFlow.TokenUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; + RefreshUrl = oAuthFlow?.RefreshUrl != null ? new Uri(oAuthFlow.RefreshUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; Scopes = oAuthFlow?.Scopes != null ? new Dictionary(oAuthFlow.Scopes) : null; Extensions = oAuthFlow?.Extensions != null ? new Dictionary(oAuthFlow.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 913e70441..616a6a022 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -77,7 +77,7 @@ public class OpenApiSecurityScheme : IOpenApiSerializable, IOpenApiReferenceable /// /// Parameterless constructor /// - public OpenApiSecurityScheme() {} + public OpenApiSecurityScheme() { } /// /// Initializes a copy of object @@ -91,7 +91,7 @@ public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) Scheme = securityScheme?.Scheme ?? Scheme; BearerFormat = securityScheme?.BearerFormat ?? BearerFormat; Flows = securityScheme?.Flows != null ? new(securityScheme?.Flows) : null; - OpenIdConnectUrl = securityScheme?.OpenIdConnectUrl != null ? new Uri(securityScheme.OpenIdConnectUrl.OriginalString) : null; + OpenIdConnectUrl = securityScheme?.OpenIdConnectUrl != null ? new Uri(securityScheme.OpenIdConnectUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; Extensions = securityScheme?.Extensions != null ? new Dictionary(securityScheme.Extensions) : null; UnresolvedReference = securityScheme?.UnresolvedReference ?? UnresolvedReference; Reference = securityScheme?.Reference != null ? new(securityScheme?.Reference) : null; @@ -107,8 +107,8 @@ public void SerializeAsV3(IOpenApiWriter writer) throw Error.ArgumentNull(nameof(writer)); } - - if (Reference != null) + + if (Reference != null) { Reference.SerializeAsV3(writer); return; From aad81eff4611d9e4b01ac4db3a071e5b84a93ca5 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 9 Feb 2023 14:35:14 -0500 Subject: [PATCH 409/855] - bumps minor versions for copy constructor fix --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 8373654b3..781deb6ee 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.0 + 1.6.1 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 44a556cae..622e7e7b6 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.0 + 1.6.1 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 116b56d16714b3cf25b34d2f5bf8ae0ef6e88c86 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 13 Feb 2023 10:00:16 -0500 Subject: [PATCH 410/855] - fixes failing test Signed-off-by: Vincent Biret --- .../Writers/OpenApiYamlWriterTests.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs index bfaa3da51..1a15ea3b4 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs @@ -618,7 +618,12 @@ public void WriteInlineRecursiveSchemav2() type: object properties: children: - $ref: '#/definitions/thing' + type: object + properties: + children: + $ref: '#/definitions/thing' + related: + type: integer related: type: integer"; // Component schemas that are there due to cycles are still inlined because the items they reference may not exist in the components because they don't have cycles. From f37d3e78d73387da5c46ce3a07726dfdf4a2594f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Feb 2023 21:57:41 +0000 Subject: [PATCH 411/855] Bump FluentAssertions from 6.9.0 to 6.10.0 Bumps [FluentAssertions](https://github.com/fluentassertions/fluentassertions) from 6.9.0 to 6.10.0. - [Release notes](https://github.com/fluentassertions/fluentassertions/releases) - [Changelog](https://github.com/fluentassertions/fluentassertions/blob/develop/AcceptApiChanges.ps1) - [Commits](https://github.com/fluentassertions/fluentassertions/compare/6.9.0...6.10.0) --- updated-dependencies: - dependency-name: FluentAssertions dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 9f780f605..bb4acc5d5 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -262,7 +262,7 @@ all - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index fc9274aea..f1f1d5599 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -23,7 +23,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + From 8de409e67417174ef2ce8126000330f95b0c62a6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 14 Feb 2023 21:57:37 +0000 Subject: [PATCH 412/855] Bump Verify.Xunit from 19.9.2 to 19.9.3 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.9.2 to 19.9.3. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index f1f1d5599..b1cc820b6 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From e0472916ee3154dd4180d82194b442d97f0352e5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 15 Feb 2023 21:57:34 +0000 Subject: [PATCH 413/855] Bump Microsoft.OData.Edm from 7.14.0 to 7.14.1 Bumps Microsoft.OData.Edm from 7.14.0 to 7.14.1. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index b30d770de..6ba69e598 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From 622a6e20d5eed9201f3297d376a2ad497ab19af5 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 20 Feb 2023 15:11:44 -0500 Subject: [PATCH 414/855] - adds missing cancellation token parameter and passes it along --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 8 ++++---- src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs | 8 +++++--- src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs | 6 ++++-- .../OpenApiYamlDocumentReader.cs | 9 +++++---- .../Services/OpenApiWorkspaceLoader.cs | 8 ++++---- 5 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index fa0b5ff51..9fdca3f66 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -162,7 +162,7 @@ private static async Task GetOpenApi(string openapi, string csd else { stream = await GetStream(openapi, logger, cancellationToken); - var result = await ParseOpenApi(openapi, inlineExternal, logger, stream); + var result = await ParseOpenApi(openapi, inlineExternal, logger, stream, cancellationToken); document = result.OpenApiDocument; } @@ -253,7 +253,7 @@ public static async Task ValidateOpenApiDocument( { using var stream = await GetStream(openapi, logger, cancellationToken); - var result = await ParseOpenApi(openapi, false, logger, stream); + var result = await ParseOpenApi(openapi, false, logger, stream, cancellationToken); using (logger.BeginScope("Calculating statistics")) { @@ -275,7 +275,7 @@ public static async Task ValidateOpenApiDocument( } } - private static async Task ParseOpenApi(string openApiFile, bool inlineExternal, ILogger logger, Stream stream) + private static async Task ParseOpenApi(string openApiFile, bool inlineExternal, ILogger logger, Stream stream, CancellationToken cancellationToken) { ReadResult result; Stopwatch stopwatch = Stopwatch.StartNew(); @@ -290,7 +290,7 @@ private static async Task ParseOpenApi(string openApiFile, bool inli new Uri(openApiFile) : new Uri("file://" + new FileInfo(openApiFile).DirectoryName + Path.DirectorySeparatorChar) } - ).ReadAsync(stream); + ).ReadAsync(stream, cancellationToken); logger.LogTrace("{timestamp}ms: Completed parsing.", stopwatch.ElapsedMilliseconds); diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index 13bdbdef8..4529cb57e 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -3,6 +3,7 @@ using System; using System.IO; +using System.Threading; using System.Threading.Tasks; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; @@ -54,8 +55,9 @@ public OpenApiDocument Read(Stream input, out OpenApiDiagnostic diagnostic) /// Reads the stream input and parses it into an Open API document. /// /// Stream containing OpenAPI description to parse. + /// Cancellation token. /// Instance result containing newly created OpenApiDocument and diagnostics object from the process - public async Task ReadAsync(Stream input) + public async Task ReadAsync(Stream input, CancellationToken cancellationToken = default) { MemoryStream bufferedStream; if (input is MemoryStream) @@ -67,13 +69,13 @@ public async Task ReadAsync(Stream input) // Buffer stream so that OpenApiTextReaderReader can process it synchronously // YamlDocument doesn't support async reading. bufferedStream = new MemoryStream(); - await input.CopyToAsync(bufferedStream); + await input.CopyToAsync(bufferedStream, 81920, cancellationToken); bufferedStream.Position = 0; } var reader = new StreamReader(bufferedStream); - return await new OpenApiTextReaderReader(_settings).ReadAsync(reader); + return await new OpenApiTextReaderReader(_settings).ReadAsync(reader, cancellationToken); } /// diff --git a/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs index f4e81dee9..d6722d440 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; @@ -57,8 +58,9 @@ public OpenApiDocument Read(TextReader input, out OpenApiDiagnostic diagnostic) /// Reads the content of the TextReader. If there are references to external documents then they will be read asynchronously. /// /// TextReader containing OpenAPI description to parse. + /// Cancellation token. /// A ReadResult instance that contains the resulting OpenApiDocument and a diagnostics instance. - public async Task ReadAsync(TextReader input) + public async Task ReadAsync(TextReader input, CancellationToken cancellationToken = default) { YamlDocument yamlDocument; @@ -78,7 +80,7 @@ public async Task ReadAsync(TextReader input) }; } - return await new OpenApiYamlDocumentReader(this._settings).ReadAsync(yamlDocument); + return await new OpenApiYamlDocumentReader(this._settings).ReadAsync(yamlDocument, cancellationToken); } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 37113578a..e43c64ac2 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Extensions; @@ -84,7 +85,7 @@ public OpenApiDocument Read(YamlDocument input, out OpenApiDiagnostic diagnostic return document; } - public async Task ReadAsync(YamlDocument input) + public async Task ReadAsync(YamlDocument input, CancellationToken cancellationToken = default) { var diagnostic = new OpenApiDiagnostic(); var context = new ParsingContext(diagnostic) @@ -101,7 +102,7 @@ public async Task ReadAsync(YamlDocument input) if (_settings.LoadExternalRefs) { - await LoadExternalRefs(document); + await LoadExternalRefs(document, cancellationToken); } ResolveReferences(diagnostic, document); @@ -132,7 +133,7 @@ public async Task ReadAsync(YamlDocument input) }; } - private async Task LoadExternalRefs(OpenApiDocument document) + private async Task LoadExternalRefs(OpenApiDocument document, CancellationToken cancellationToken) { // Create workspace for all documents to live in. var openApiWorkSpace = new OpenApiWorkspace(); @@ -140,7 +141,7 @@ private async Task LoadExternalRefs(OpenApiDocument document) // Load this root document into the workspace var streamLoader = new DefaultStreamLoader(_settings.BaseUrl); var workspaceLoader = new OpenApiWorkspaceLoader(openApiWorkSpace, _settings.CustomExternalLoader ?? streamLoader, _settings); - await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document); + await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document, cancellationToken); } private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument document) diff --git a/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs b/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs index def92967e..32e2db128 100644 --- a/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs @@ -3,11 +3,11 @@ using System.IO; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.Interface; using Microsoft.OpenApi.Services; -using SharpYaml.Model; namespace Microsoft.OpenApi.Readers.Services { @@ -24,7 +24,7 @@ public OpenApiWorkspaceLoader(OpenApiWorkspace workspace, IStreamLoader loader, _readerSettings = readerSettings; } - internal async Task LoadAsync(OpenApiReference reference, OpenApiDocument document) + internal async Task LoadAsync(OpenApiReference reference, OpenApiDocument document, CancellationToken cancellationToken) { _workspace.AddDocument(reference.ExternalResource, document); document.Workspace = _workspace; @@ -43,8 +43,8 @@ internal async Task LoadAsync(OpenApiReference reference, OpenApiDocument docume if (!_workspace.Contains(item.ExternalResource)) { var input = await _loader.LoadAsync(new Uri(item.ExternalResource, UriKind.RelativeOrAbsolute)); - var result = await reader.ReadAsync(input); // TODO merge _diagnositics - await LoadAsync(item, result.OpenApiDocument); + var result = await reader.ReadAsync(input, cancellationToken); // TODO merge diagnostics + await LoadAsync(item, result.OpenApiDocument, cancellationToken); } } } From ce1864956f00b3ff7ed12d7f7563c9f5dad3fa48 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 20 Feb 2023 15:16:07 -0500 Subject: [PATCH 415/855] - fixes missing memory stream dispose Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index 4529cb57e..8922be4ce 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -73,9 +73,10 @@ public async Task ReadAsync(Stream input, CancellationToken cancella bufferedStream.Position = 0; } - var reader = new StreamReader(bufferedStream); - - return await new OpenApiTextReaderReader(_settings).ReadAsync(reader, cancellationToken); + using (var reader = new StreamReader(bufferedStream)) + { + return await new OpenApiTextReaderReader(_settings).ReadAsync(reader, cancellationToken); + } } /// From 70d0888e5ad17610aa85794708590f3159bd2016 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 20 Feb 2023 15:37:34 -0500 Subject: [PATCH 416/855] - bumps patch version Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 781deb6ee..e095c6c86 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.1 + 1.6.2 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 622e7e7b6..92de7f8a0 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.1 + 1.6.2 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 22c4ea17b4ec89bca30858f6c0e626e92379595b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Feb 2023 21:57:27 +0000 Subject: [PATCH 417/855] Bump Verify.Xunit from 19.9.3 to 19.10.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.9.3 to 19.10.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits/19.10.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index b1cc820b6..136826032 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From bc0c528a239b81e3f0c7384ddbd24f24fdce279b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Feb 2023 21:57:55 +0000 Subject: [PATCH 418/855] Bump Microsoft.NET.Test.Sdk from 17.4.1 to 17.5.0 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.4.1 to 17.5.0. - [Release notes](https://github.com/microsoft/vstest/releases) - [Changelog](https://github.com/microsoft/vstest/blob/main/docs/releases.md) - [Commits](https://github.com/microsoft/vstest/compare/v17.4.1...v17.5.0) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index aaaa66cba..f9b1a0f2c 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -13,7 +13,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index bb4acc5d5..65833564f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -261,7 +261,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 8e0f1a398..dd8e36a25 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -16,7 +16,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index b1cc820b6..0dfa276e2 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -24,7 +24,7 @@ all - + From 93814dc86a1f54961d9cb0f6f92d5a8d3515369a Mon Sep 17 00:00:00 2001 From: Irvine Sunday <40403681+irvinesunday@users.noreply.github.com> Date: Tue, 28 Feb 2023 15:57:01 +0300 Subject: [PATCH 419/855] [Upgrade] Bumps up conversion lib version Bumps up the `Microsoft.OpenApi.OData` lib. `v1.2.0` to `v1.3.0-preview2` --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 6ba69e598..cc275d5fa 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 5767934f97a546302dcac34ab8ceac513388dea1 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 28 Feb 2023 08:40:35 -0500 Subject: [PATCH 420/855] - bumps hidi version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index cc275d5fa..7d41d9e90 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.2.2 + 1.2.3 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET From f4bab188d5a87ebdb264949a65e4ac4d7a94ab6c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Mar 2023 21:15:34 +0000 Subject: [PATCH 421/855] Bump Microsoft.OData.Edm from 7.14.1 to 7.15.0 Bumps Microsoft.OData.Edm from 7.14.1 to 7.15.0. --- updated-dependencies: - dependency-name: Microsoft.OData.Edm dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 7d41d9e90..2e74545e2 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -42,7 +42,7 @@ - + From 27b76232075639fa60dbd029a71f24c346c1ab1c Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 6 Mar 2023 14:10:32 +0300 Subject: [PATCH 422/855] Add logic to resolve a referenceable security scheme component --- .../V3/OpenApiSecuritySchemeDeserializer.cs | 6 +++++- .../Services/OpenApiWalker.cs | 19 +++++++++++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs index 0e7b1c39c..dd6ad4751 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs @@ -76,7 +76,11 @@ internal static partial class OpenApiV3Deserializer public static OpenApiSecurityScheme LoadSecurityScheme(ParseNode node) { var mapNode = node.CheckMapNode("securityScheme"); - + var pointer = mapNode.GetReferencePointer(); + if (pointer != null) + { + return mapNode.GetReferencedObject(ReferenceType.SecurityScheme, pointer); + } var securityScheme = new OpenApiSecurityScheme(); foreach (var property in mapNode) { diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index 8c469261c..3d9e978c9 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.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; @@ -116,7 +116,18 @@ internal void Walk(OpenApiComponents components) } } }); - + + Walk(OpenApiConstants.SecuritySchemes, () => + { + if (components.SecuritySchemes != null) + { + foreach (var item in components.SecuritySchemes) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + Walk(OpenApiConstants.Callbacks, () => { if (components.Callbacks != null) @@ -996,9 +1007,9 @@ internal void Walk(OpenApiSecurityRequirement securityRequirement) /// /// Visits and child objects /// - internal void Walk(OpenApiSecurityScheme securityScheme) + internal void Walk(OpenApiSecurityScheme securityScheme, bool isComponent = false) { - if (securityScheme == null || ProcessAsReference(securityScheme)) + if (securityScheme == null || ProcessAsReference(securityScheme, isComponent)) { return; } From a6634071da11585772287638bf7c681c84448ea6 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 6 Mar 2023 14:10:55 +0300 Subject: [PATCH 423/855] Add tests to validate --- .../OpenApiYamlDocumentReader.cs | 1 - .../Microsoft.OpenApi.Readers.Tests.csproj | 3 +++ .../V3Tests/OpenApiDocumentTests.cs | 24 +++++++++++++++++-- .../docWithSecuritySchemeReference.yaml | 17 +++++++++++++ 4 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/docWithSecuritySchemeReference.yaml diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index e43c64ac2..f6fd2325e 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -166,7 +166,6 @@ private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument doc } } - /// /// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element. /// diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 65833564f..aef3d92e0 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -137,6 +137,9 @@ Never + + Never + Never diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 362609291..8a0da3481 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; @@ -1334,10 +1335,10 @@ public void DoesNotChangeExternalReferences() { // Arrange using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "documentWithExternalRefs.yaml")); - + // Act var doc = new OpenApiStreamReader( - new OpenApiReaderSettings { ReferenceResolution = ReferenceResolutionSetting.DoNotResolveReferences}) + new OpenApiReaderSettings { ReferenceResolution = ReferenceResolutionSetting.DoNotResolveReferences }) .Read(stream, out var diagnostic); var externalRef = doc.Components.Schemas["Nested"].Properties["AnyOf"].AnyOf.First().Reference.ReferenceV3; @@ -1347,5 +1348,24 @@ public void DoesNotChangeExternalReferences() Assert.Equal("file:///C:/MySchemas.json#/definitions/ArrayObject", externalRef); Assert.Equal("../foo/schemas.yaml#/components/schemas/Number", externalRef2); } + + [Fact] + public void ParseDocumentWithReferencedSecuritySchemeWorks() + { + // Arrange + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "docWithSecuritySchemeReference.yaml")); + + // Act + var doc = new OpenApiStreamReader(new OpenApiReaderSettings + { + ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences + }).Read(stream, out var diagnostic); + + var securityScheme = doc.Components.SecuritySchemes["OAuth2"]; + + // Assert + Assert.False(securityScheme.UnresolvedReference); + Assert.NotNull(securityScheme.Flows); + } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/docWithSecuritySchemeReference.yaml b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/docWithSecuritySchemeReference.yaml new file mode 100644 index 000000000..3608635a2 --- /dev/null +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/Samples/OpenApiDocument/docWithSecuritySchemeReference.yaml @@ -0,0 +1,17 @@ +openapi: 3.0.0 +info: + title: Example API + version: 1.0.0 +paths: { } +components: + securitySchemes: + OAuth2: + $ref: '#/components/securitySchemes/RefOAuth2' + RefOAuth2: + type: oauth2 + flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets \ No newline at end of file From 49a65c362cb5977674e8a60c4330254ff9ed60a9 Mon Sep 17 00:00:00 2001 From: Charles Wahome Date: Mon, 6 Mar 2023 14:40:20 +0300 Subject: [PATCH 424/855] settings will be passed by the apps that need to override --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 22 +------------------- 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 9fdca3f66..4d535ee02 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -324,27 +324,7 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl, stri var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader()); var config = GetConfiguration(settingsFile); - var settings = new OpenApiConvertSettings() - { - AddSingleQuotesForStringParameters = true, - AddEnumDescriptionExtension = true, - DeclarePathParametersOnPathItem = true, - EnableKeyAsSegment = true, - EnableOperationId = true, - ErrorResponsesAsDefault = false, - PrefixEntityTypeNameBeforeKey = true, - TagDepth = 2, - EnablePagination = true, - EnableDiscriminatorValue = true, - EnableDerivedTypesReferencesForRequestBody = false, - EnableDerivedTypesReferencesForResponses = false, - ShowRootPath = false, - ShowLinks = false, - ExpandDerivedTypesNavigationProperties = false, - EnableCount = true, - UseSuccessStatusCodeRange = true, - EnableTypeDisambiguationForDefaultValueOfOdataTypeProperty = true - }; + var settings = new OpenApiConvertSettings(); config.GetSection("OpenApiConvertSettings").Bind(settings); OpenApiDocument document = edmModel.ConvertToOpenApi(settings); From 36f8f596f02281f059588f086526dcad5cf08db2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 21:59:08 +0000 Subject: [PATCH 425/855] Bump PublicApiGenerator from 10.3.0 to 11.0.0 Bumps [PublicApiGenerator](https://github.com/PublicApiGenerator/PublicApiGenerator) from 10.3.0 to 11.0.0. - [Release notes](https://github.com/PublicApiGenerator/PublicApiGenerator/releases) - [Commits](https://github.com/PublicApiGenerator/PublicApiGenerator/compare/10.3.0...11.0.0) --- updated-dependencies: - dependency-name: PublicApiGenerator dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 481a53db8..b153ba204 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -35,7 +35,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - + From f0b8c191e85062eceb9e2e9f7c18b9034d6efafa Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 7 Mar 2023 15:28:52 +0300 Subject: [PATCH 426/855] Bump lib versions --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 2e74545e2..98f250626 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.2.3 + 1.2.4 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index e095c6c86..f037a02e7 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.2 + 1.6.3 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 92de7f8a0..43ef3876f 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.2 + 1.6.3 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 2ec0688b1a615ac6b7af4ac074569786c84ed9d2 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 7 Mar 2023 22:18:56 +0300 Subject: [PATCH 427/855] Replace obsolete ApiGenerator option --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs index fa413cd32..418a526d0 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs @@ -26,7 +26,7 @@ public void ReviewPublicApiChanges() // It takes a human to read the change, determine if it is breaking and update the PublicApi.approved.txt with the new approved API surface // Arrange - var publicApi = typeof(OpenApiSpecVersion).Assembly.GeneratePublicApi(new ApiGeneratorOptions() { WhitelistedNamespacePrefixes = new[] { "Microsoft.OpenApi" } } ); + var publicApi = typeof(OpenApiSpecVersion).Assembly.GeneratePublicApi(new ApiGeneratorOptions() { AllowNamespacePrefixes = new[] { "Microsoft.OpenApi" } } ); // Act var approvedFilePath = Path.Combine("PublicApi", "PublicApi.approved.txt"); From a5e91a592930bad320358d06af50924c052126e4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Mar 2023 21:57:30 +0000 Subject: [PATCH 428/855] Bump Newtonsoft.Json from 13.0.2 to 13.0.3 Bumps [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) from 13.0.2 to 13.0.3. - [Release notes](https://github.com/JamesNK/Newtonsoft.Json/releases) - [Commits](https://github.com/JamesNK/Newtonsoft.Json/compare/13.0.2...13.0.3) --- updated-dependencies: - dependency-name: Newtonsoft.Json dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index aef3d92e0..ded741223 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -267,7 +267,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index dd8e36a25..b2820b16a 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -17,7 +17,7 @@ all - + all diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index b153ba204..68418ca6c 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -26,7 +26,7 @@ - + From ac15d22d2cdd8acec60cd60f2813256fb323ccd2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 10 Mar 2023 21:57:19 +0000 Subject: [PATCH 429/855] Bump Verify.Xunit from 19.10.0 to 19.11.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.10.0 to 19.11.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.10.0...19.11.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 68418ca6c..f1b697deb 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 84f83181f7d565c8261374e7919dcbf97e2151d1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 21:58:58 +0000 Subject: [PATCH 430/855] Bump Verify.Xunit from 19.11.0 to 19.11.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.11.0 to 19.11.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index f1b697deb..969968329 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 416b8ce3fb097600218934df395177b47017b118 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Mar 2023 21:57:19 +0000 Subject: [PATCH 431/855] Bump Microsoft.OpenApi.OData from 1.3.0-preview2 to 1.3.0-preview3 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.3.0-preview2 to 1.3.0-preview3. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 98f250626..ff90f5379 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 48f56b09be2a64fa42e141121a9a7b19d606e4e7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Mar 2023 21:57:24 +0000 Subject: [PATCH 432/855] Bump Verify.Xunit from 19.11.1 to 19.11.2 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.11.1 to 19.11.2. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits/19.11.2) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 969968329..f79d30627 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 5801f23a2135363158735fe9d184e11a1fc05228 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 23 Mar 2023 21:57:16 +0000 Subject: [PATCH 433/855] Bump Microsoft.OpenApi.OData from 1.3.0-preview3 to 1.3.0-preview4 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.3.0-preview3 to 1.3.0-preview4. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index ff90f5379..d21a07947 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 345f13602c512a29f4418acc005cfb52cb1d53fd Mon Sep 17 00:00:00 2001 From: Irvine Sunday Date: Tue, 28 Mar 2023 13:03:03 +0300 Subject: [PATCH 434/855] Add unit test to break copy constructors --- test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index c4876db7a..a1d7cc665 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1344,12 +1344,18 @@ public void CopyConstructorForAdvancedDocumentWorks() // Arrange & Act var doc = new OpenApiDocument(AdvancedDocument); + // Change value of operation id for a given url + // doc.Paths["/pets"].Operations[OperationType.Get].OperationId = "findAllMyPets"; + var docOpId = doc.Paths["/pets"].Operations[OperationType.Get].OperationId = "findAllMyPets"; + var advancedDocOpId = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].OperationId; + // Assert Assert.NotNull(doc.Info); Assert.NotNull(doc.Servers); Assert.NotNull(doc.Paths); Assert.Equal(2, doc.Paths.Count); Assert.NotNull(doc.Components); + Assert.NotEqual(docOpId, advancedDocOpId); } [Fact] From d5a5f8a8890825824f31187355850945416aa7ea Mon Sep 17 00:00:00 2001 From: Irvine Sunday Date: Tue, 28 Mar 2023 14:15:54 +0300 Subject: [PATCH 435/855] Remove commented code --- test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index a1d7cc665..68bb0e037 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1345,7 +1345,6 @@ public void CopyConstructorForAdvancedDocumentWorks() var doc = new OpenApiDocument(AdvancedDocument); // Change value of operation id for a given url - // doc.Paths["/pets"].Operations[OperationType.Get].OperationId = "findAllMyPets"; var docOpId = doc.Paths["/pets"].Operations[OperationType.Get].OperationId = "findAllMyPets"; var advancedDocOpId = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].OperationId; From 61fd3f7579cf949f6b9e346a8c8566f8d47ecaaa Mon Sep 17 00:00:00 2001 From: Daniel Date: Tue, 28 Mar 2023 22:24:50 +0200 Subject: [PATCH 436/855] OpenApiOperation constructor preserve null Fixes #1192 - Fix OpenApiOperation RequestBody and Tags null is not preserved - Add tests for null preserving null on copy constructor - Add tests for copy constructor serialization result to be equal - Fix OpenApiParameter object changes during serialization, so that the serialization result is on consecutive run the same. --- .../Models/OpenApiOperation.cs | 4 +- .../Models/OpenApiParameter.cs | 4 +- ...Works_produceTerseOutput=True.verified.txt | 2 +- ...Works_produceTerseOutput=True.verified.txt | 2 +- .../Models/OpenApiOperationTests.cs | 54 +++++++++++++++++++ ...Async_produceTerseOutput=True.verified.txt | 2 +- 6 files changed, 61 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index d047b9cb6..500c15dfb 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -116,13 +116,13 @@ public OpenApiOperation() {} /// public OpenApiOperation(OpenApiOperation operation) { - Tags = new List(operation?.Tags); + Tags = operation.Tags != null ? new List(operation?.Tags) : null; Summary = operation?.Summary ?? Summary; Description = operation?.Description ?? Description; ExternalDocs = operation?.ExternalDocs != null ? new(operation?.ExternalDocs) : null; OperationId = operation?.OperationId ?? OperationId; Parameters = operation?.Parameters != null ? new List(operation.Parameters) : null; - RequestBody = new(operation?.RequestBody); + RequestBody = operation?.RequestBody != null ? new(operation?.RequestBody) : null; Responses = operation?.Responses != null ? new(operation?.Responses) : null; Callbacks = operation?.Callbacks != null ? new Dictionary(operation.Callbacks) : null; Deprecated = operation?.Deprecated ?? Deprecated; diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index fa62f0b79..616422165 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -243,11 +243,11 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) // style if (_style.HasValue) { - writer.WriteProperty(OpenApiConstants.Style, Style.Value.GetDisplayName()); + writer.WriteProperty(OpenApiConstants.Style, _style.Value.GetDisplayName()); } // explode - writer.WriteProperty(OpenApiConstants.Explode, Explode, Style.HasValue && Style.Value == ParameterStyle.Form); + writer.WriteProperty(OpenApiConstants.Explode, _explode, _style.HasValue && _style.Value == ParameterStyle.Form); // allowReserved writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=True.verified.txt index 2ac8e39bb..be8dcc627 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeAdvancedDocumentWithReferenceAsV3JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","style":"form","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","style":"form","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/pet"}}},"application/xml":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/pet"}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/newPet"}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/pet"}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"style":"simple","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/pet"}},"application/xml":{"schema":{"$ref":"#/components/schemas/pet"}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"style":"simple","schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file +{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"description":"Returns all pets from the system that the user has access to","operationId":"findPets","parameters":[{"name":"tags","in":"query","description":"tags to filter by","schema":{"type":"array","items":{"type":"string"}}},{"name":"limit","in":"query","description":"maximum number of results to return","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/pet"}}},"application/xml":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/pet"}}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}},"post":{"description":"Creates a new pet in the store. Duplicates are allowed","operationId":"addPet","requestBody":{"description":"Pet to add to the store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/newPet"}}},"required":true},"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/pet"}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}}},"/pets/{id}":{"get":{"description":"Returns a user based on a single ID, if the user does not have access to the pet","operationId":"findPetById","parameters":[{"name":"id","in":"path","description":"ID of pet to fetch","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/pet"}},"application/xml":{"schema":{"$ref":"#/components/schemas/pet"}}}},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}},"delete":{"description":"deletes a single pet based on the ID supplied","operationId":"deletePet","parameters":[{"name":"id","in":"path","description":"ID of pet to delete","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"204":{"description":"pet deleted"},"4XX":{"description":"unexpected client error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}},"5XX":{"description":"unexpected server error","content":{"text/html":{"schema":{"$ref":"#/components/schemas/errorModel"}}}}}}}},"components":{"schemas":{"pet":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"newPet":{"required":["name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}},"errorModel":{"required":["code","message"],"type":"object","properties":{"code":{"type":"integer","format":"int32"},"message":{"type":"string"}}}}}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=True.verified.txt index c1eca99f6..da61a8817 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.SerializeDuplicateExtensionsAsV3JsonWorks_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/add/{operand1}/{operand2}":{"get":{"operationId":"addByOperand1AndByOperand2","parameters":[{"name":"operand1","in":"path","description":"The first operand","required":true,"style":"simple","schema":{"type":"integer","my-extension":4},"my-extension":4},{"name":"operand2","in":"path","description":"The second operand","required":true,"style":"simple","schema":{"type":"integer","my-extension":4},"my-extension":4}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}}}}}}} \ No newline at end of file +{"openapi":"3.0.1","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","version":"1.0.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/add/{operand1}/{operand2}":{"get":{"operationId":"addByOperand1AndByOperand2","parameters":[{"name":"operand1","in":"path","description":"The first operand","required":true,"schema":{"type":"integer","my-extension":4},"my-extension":4},{"name":"operand2","in":"path","description":"The second operand","required":true,"schema":{"type":"integer","my-extension":4},"my-extension":4}],"responses":{"200":{"description":"pet response","content":{"application/json":{"schema":{"type":"array","items":{"required":["id","name"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}}}}}}}} \ No newline at end of file diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index 2079a3122..de56df52e 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -6,6 +6,7 @@ using FluentAssertions; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; +using NuGet.Frameworks; using Xunit; using Xunit.Abstractions; @@ -793,5 +794,58 @@ public void EnsureOpenApiOperationCopyConstructorCopiesResponsesObject() Assert.NotNull(operation.Responses); Assert.Equal(2, operation.Responses.Count); } + + [Fact] + public void EnsureOpenApiOperationCopyConstructorCopiesNull() + { + // Arrange + _basicOperation.Parameters = null; + _basicOperation.Tags = null; + _basicOperation.Responses = null; + _basicOperation.Callbacks = null; + _basicOperation.Security = null; + _basicOperation.Servers = null; + _basicOperation.Extensions = null; + + // Act + var operation = new OpenApiOperation(_basicOperation); + + // Assert + Assert.Null(operation.Tags); + Assert.Null(operation.Summary); + Assert.Null(operation.Description); + Assert.Null(operation.ExternalDocs); + Assert.Null(operation.OperationId); + Assert.Null(operation.Parameters); + Assert.Null(operation.RequestBody); + Assert.Null(operation.Responses); + Assert.Null(operation.Callbacks); + Assert.Null(operation.Security); + Assert.Null(operation.Servers); + Assert.Null(operation.Extensions); + } + + [Fact] + public void EnsureOpenApiOperationCopyConstructor_SerializationResultsInSame() + { + var operations = new[] + { + _basicOperation, + _operationWithBody, + _operationWithFormData, + _advancedOperationWithTagsAndSecurity + }; + + foreach (var operation in operations) + { + // Act + var expected = operation.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); + var openApiOperation = new OpenApiOperation(operation); + var actual = openApiOperation.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); + + // Assert + actual.Should().Be(expected); + } + } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=True.verified.txt b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=True.verified.txt index 703bc6613..ec654beb0 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=True.verified.txt +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync_produceTerseOutput=True.verified.txt @@ -1 +1 @@ -{"name":"name1","in":"path","style":"simple"} \ No newline at end of file +{"name":"name1","in":"path"} \ No newline at end of file From d479ec3533df40a5b52671d474785627fe022b01 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 29 Mar 2023 12:48:50 +0300 Subject: [PATCH 437/855] Update src/Microsoft.OpenApi/Models/OpenApiOperation.cs --- src/Microsoft.OpenApi/Models/OpenApiOperation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 500c15dfb..a1d822a8e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -116,7 +116,7 @@ public OpenApiOperation() {} /// public OpenApiOperation(OpenApiOperation operation) { - Tags = operation.Tags != null ? new List(operation?.Tags) : null; + Tags = operation?.Tags != null ? new List(operation?.Tags) : null; Summary = operation?.Summary ?? Summary; Description = operation?.Description ?? Description; ExternalDocs = operation?.ExternalDocs != null ? new(operation?.ExternalDocs) : null; From 9765d0634aa798263f6079b4774aa53c0af934f9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 29 Mar 2023 15:44:35 +0300 Subject: [PATCH 438/855] Adds a metadata version parameter as a commandline option --- .../Handlers/TransformCommandHandler.cs | 4 +++- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 19 ++++++++++++------- src/Microsoft.OpenApi.Hidi/Program.cs | 7 ++++++- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index d0a49c209..e00cd7efa 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -19,6 +19,7 @@ internal class TransformCommandHandler : ICommandHandler public Option OutputOption { get; set; } public Option CleanOutputOption { get; set; } public Option VersionOption { get; set; } + public Option MetadataVersionOption { get; set; } public Option FormatOption { get; set; } public Option TerseOutputOption { get; set; } public Option SettingsFileOption { get; set; } @@ -41,6 +42,7 @@ public async Task InvokeAsync(InvocationContext context) FileInfo output = context.ParseResult.GetValueForOption(OutputOption); bool cleanOutput = context.ParseResult.GetValueForOption(CleanOutputOption); string? version = context.ParseResult.GetValueForOption(VersionOption); + string metadataVersion = context.ParseResult.GetValueForOption(MetadataVersionOption); OpenApiFormat? format = context.ParseResult.GetValueForOption(FormatOption); bool terseOutput = context.ParseResult.GetValueForOption(TerseOutputOption); string settingsFile = context.ParseResult.GetValueForOption(SettingsFileOption); @@ -57,7 +59,7 @@ public async Task InvokeAsync(InvocationContext context) var logger = loggerFactory.CreateLogger(); try { - await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, settingsFile, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, logger, cancellationToken); + await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, metadataVersion, format, terseOutput, settingsFile, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, logger, cancellationToken); return 0; } diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 4d535ee02..5d5ec95d4 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; -using System.Linq; using System.Net; using System.Net.Http; using System.Security; @@ -20,7 +19,6 @@ using Microsoft.OpenApi.OData; using Microsoft.OpenApi.Readers; using Microsoft.OpenApi.Services; -using Microsoft.OpenApi.Validations; using Microsoft.OpenApi.Writers; using static Microsoft.OpenApi.Hidi.OpenApiSpecVersionHelper; using System.Threading; @@ -43,6 +41,7 @@ public static async Task TransformOpenApiDocument( FileInfo output, bool cleanoutput, string? version, + string metadataVersion, OpenApiFormat? format, bool terseOutput, string settingsFile, @@ -81,7 +80,7 @@ CancellationToken cancellationToken OpenApiFormat openApiFormat = format ?? (!string.IsNullOrEmpty(openapi) ? GetOpenApiFormat(openapi, logger) : OpenApiFormat.Yaml); OpenApiSpecVersion openApiVersion = version != null ? TryParseOpenApiSpecVersion(version) : OpenApiSpecVersion.OpenApi3_0; - OpenApiDocument document = await GetOpenApi(openapi, csdl, csdlFilter, settingsFile, inlineExternal, logger, cancellationToken); + OpenApiDocument document = await GetOpenApi(openapi, csdl, csdlFilter, settingsFile, inlineExternal, logger, cancellationToken, metadataVersion); document = await FilterOpenApiDocument(filterbyoperationids, filterbytags, filterbycollection, document, logger, cancellationToken); WriteOpenApi(output, terseOutput, inlineLocal, inlineExternal, openApiFormat, openApiVersion, document, logger); } @@ -132,11 +131,11 @@ private static void WriteOpenApi(FileInfo output, bool terseOutput, bool inlineL } // Get OpenAPI document either from OpenAPI or CSDL - private static async Task GetOpenApi(string openapi, string csdl, string csdlFilter, string settingsFile, bool inlineExternal, ILogger logger, CancellationToken cancellationToken) + private static async Task GetOpenApi(string openapi, string csdl, string csdlFilter, string settingsFile, bool inlineExternal, ILogger logger, CancellationToken cancellationToken, string metadataVersion = null) { OpenApiDocument document; Stream stream; - + if (!string.IsNullOrEmpty(csdl)) { var stopwatch = new Stopwatch(); @@ -154,7 +153,7 @@ private static async Task GetOpenApi(string openapi, string csd stream = null; } - document = await ConvertCsdlToOpenApi(filteredStream ?? stream, settingsFile, cancellationToken); + document = await ConvertCsdlToOpenApi(filteredStream ?? stream, metadataVersion, settingsFile, cancellationToken); stopwatch.Stop(); logger.LogTrace("{timestamp}ms: Generated OpenAPI with {paths} paths.", stopwatch.ElapsedMilliseconds, document.Paths.Count); } @@ -317,7 +316,7 @@ internal static IConfiguration GetConfiguration(string settingsFile) /// /// The CSDL stream. /// An OpenAPI document. - public static async Task ConvertCsdlToOpenApi(Stream csdl, string settingsFile = null, CancellationToken token = default) + public static async Task ConvertCsdlToOpenApi(Stream csdl, string metadataVersion = null, string settingsFile = null, CancellationToken token = default) { using var reader = new StreamReader(csdl); var csdlText = await reader.ReadToEndAsync(token); @@ -325,6 +324,12 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl, stri var config = GetConfiguration(settingsFile); var settings = new OpenApiConvertSettings(); + + if (!string.IsNullOrEmpty(metadataVersion)) + { + settings.SemVerVersion = metadataVersion; + } + config.GetSection("OpenApiConvertSettings").Bind(settings); OpenApiDocument document = edmModel.ConvertToOpenApi(settings); diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 8d3cc3243..9929983ee 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -46,9 +46,12 @@ internal static RootCommand CreateRootCommand() var versionOption = new Option("--version", "OpenAPI specification version"); versionOption.AddAlias("-v"); + var metadataVersionOption = new Option("--metadata-version", "Graph metadata version to use. Defaults to v1.0"); + metadataVersionOption.AddAlias("--mv"); + var formatOption = new Option("--format", "File format"); formatOption.AddAlias("-f"); - + var terseOutputOption = new Option("--terse-output", "Produce terse json output"); terseOutputOption.AddAlias("--to"); @@ -93,6 +96,7 @@ internal static RootCommand CreateRootCommand() outputOption, cleanOutputOption, versionOption, + metadataVersionOption, formatOption, terseOutputOption, settingsFileOption, @@ -112,6 +116,7 @@ internal static RootCommand CreateRootCommand() OutputOption = outputOption, CleanOutputOption = cleanOutputOption, VersionOption = versionOption, + MetadataVersionOption = metadataVersionOption, FormatOption = formatOption, TerseOutputOption = terseOutputOption, SettingsFileOption = settingsFileOption, From 03870b559a07f71a7c3a32eb5a197ad9330de1b8 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 29 Mar 2023 15:44:49 +0300 Subject: [PATCH 439/855] Bump lib to latest version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index d21a07947..dc0c3a0cc 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 667f2414fd0b1a9ee1fb68f42517ca5ba1df066f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 29 Mar 2023 16:22:19 +0300 Subject: [PATCH 440/855] Clean up tests --- .../Services/OpenApiServiceTests.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index f95acd879..85910465e 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -190,7 +190,7 @@ public async Task TransformCommandConvertsOpenApi() { var fileinfo = new FileInfo("sample.json"); // create a dummy ILogger instance for testing - await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml",null, null, fileinfo, true, null, null,false,null,false,false,null,null,null,new Logger(new LoggerFactory()), new CancellationToken()); + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml",null, null, fileinfo, true, null, null, null,false,null,false,false,null,null,null,new Logger(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText("sample.json"); Assert.NotEmpty(output); @@ -201,7 +201,7 @@ public async Task TransformCommandConvertsOpenApi() public async Task TransformCommandConvertsOpenApiWithDefaultOutputname() { // create a dummy ILogger instance for testing - await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, null, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText("output.yml"); Assert.NotEmpty(output); @@ -211,7 +211,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputname() public async Task TransformCommandConvertsCsdlWithDefaultOutputname() { // create a dummy ILogger instance for testing - await OpenApiService.TransformOpenApiDocument(null, "UtilityFiles\\Todo.xml", null, null, true, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + await OpenApiService.TransformOpenApiDocument(null, "UtilityFiles\\Todo.xml", null, null, true, null, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText("output.yml"); Assert.NotEmpty(output); @@ -221,7 +221,7 @@ public async Task TransformCommandConvertsCsdlWithDefaultOutputname() public async Task TransformCommandConvertsOpenApiWithDefaultOutputnameAndSwitchFormat() { // create a dummy ILogger instance for testing - await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, "3.0", OpenApiFormat.Yaml, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, "3.0", null, OpenApiFormat.Yaml, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText("output.yml"); Assert.NotEmpty(output); @@ -231,7 +231,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputnameAndSwitchF public async Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() { await Assert.ThrowsAsync(async () => - await OpenApiService.TransformOpenApiDocument(null, null, null, null, true, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken())); + await OpenApiService.TransformOpenApiDocument(null, null, null, null, true, null, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken())); } From 4e6a9866e87ffc72be0c60f1fa42628261edb513 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 29 Mar 2023 17:02:51 +0300 Subject: [PATCH 441/855] Update path count for test to pass --- .../Services/OpenApiServiceTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 85910465e..9081c49f5 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -38,9 +38,9 @@ public async Task ReturnConvertedCSDLFile() } [Theory] - [InlineData("Todos.Todo.UpdateTodo",null, 1)] + [InlineData("Todos.Todo.UpdateTodo", null, 1)] [InlineData("Todos.Todo.ListTodo", null, 1)] - [InlineData(null, "Todos.Todo", 4)] + [InlineData(null, "Todos.Todo", 5)] public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocument(string operationIds, string tags, int expectedPathCount) { // Arrange From 8befb8175d3c8bbe9223768672c1abfa000dbfbc Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 29 Mar 2023 17:16:32 +0300 Subject: [PATCH 442/855] Update src/Microsoft.OpenApi.Hidi/Program.cs Remove unnecessary section in description Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi.Hidi/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index 9929983ee..5c5bf691a 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -46,7 +46,7 @@ internal static RootCommand CreateRootCommand() var versionOption = new Option("--version", "OpenAPI specification version"); versionOption.AddAlias("-v"); - var metadataVersionOption = new Option("--metadata-version", "Graph metadata version to use. Defaults to v1.0"); + var metadataVersionOption = new Option("--metadata-version", "Graph metadata version to use."); metadataVersionOption.AddAlias("--mv"); var formatOption = new Option("--format", "File format"); From b854063aa977dae9a8d671ebde220a609d1f88c0 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 30 Mar 2023 13:26:01 +0300 Subject: [PATCH 443/855] Update lib versions --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index dc0c3a0cc..a018775cb 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.2.4 + 1.2.5-preview1 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index f037a02e7..e73151943 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.3 + 1.6.4-preview1 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 43ef3876f..86f49db98 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.3 + 1.6.4-preview1 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From cfff3a4610290ee9bdb0e6022b462fdce740c52e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 31 Mar 2023 21:12:29 +0000 Subject: [PATCH 444/855] Bump Verify.Xunit from 19.11.2 to 19.12.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.11.2 to 19.12.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.11.2...19.12.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index f79d30627..fb7ee1bd6 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -1,4 +1,4 @@ - + net7.0 false @@ -28,7 +28,7 @@ - + all From e518515584fd3713fc00efcea2c907ed1745c0be Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 3 Apr 2023 15:40:34 +0300 Subject: [PATCH 445/855] Adds a dictionary clone helper to help us deep clone all the values of the key value pairs in a dictionary --- .../Helpers/DictionaryCloneHelper.cs | 37 +++++++++++++++++++ .../Models/OpenApiOperation.cs | 3 +- .../Models/OpenApiPathItem.cs | 4 +- src/Microsoft.OpenApi/Models/OpenApiPaths.cs | 7 +++- .../Models/OpenApiResponses.cs | 4 +- 5 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs new file mode 100644 index 000000000..13d32e184 --- /dev/null +++ b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; + +namespace Microsoft.OpenApi.Helpers +{ + /// + /// Helper class for deep cloning dictionaries. + /// + public class DictionaryCloneHelper + { + /// + /// Deep clone key value pairs in a dictionary. + /// + /// + /// + /// + /// + public static Dictionary Clone(IDictionary dictionary) + { + var clonedDictionary = new Dictionary(); + + if (dictionary != null) + { + foreach (var kvp in dictionary) + { + // Create instance of the specified type using the constructor matching the specified parameter types. + clonedDictionary[kvp.Key] = (U)Activator.CreateInstance(kvp.Value.GetType(), kvp.Value); + } + } + + return clonedDictionary; + } + } +} diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index d047b9cb6..d46dc598e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -124,7 +125,7 @@ public OpenApiOperation(OpenApiOperation operation) Parameters = operation?.Parameters != null ? new List(operation.Parameters) : null; RequestBody = new(operation?.RequestBody); Responses = operation?.Responses != null ? new(operation?.Responses) : null; - Callbacks = operation?.Callbacks != null ? new Dictionary(operation.Callbacks) : null; + Callbacks = operation?.Callbacks != null ? DictionaryCloneHelper.Clone(operation.Callbacks) : null; Deprecated = operation?.Deprecated ?? Deprecated; Security = operation?.Security != null ? new List(operation.Security) : null; Servers = operation?.Servers != null ? new List(operation.Servers) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index ddd358dc2..61de36c7c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -1,8 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Collections.Generic; using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -77,7 +79,7 @@ public OpenApiPathItem(OpenApiPathItem pathItem) { Summary = pathItem?.Summary ?? Summary; Description = pathItem?.Description ?? Description; - Operations = pathItem?.Operations != null ? new Dictionary(pathItem.Operations) : null; + Operations = pathItem?.Operations != null ? DictionaryCloneHelper.Clone(pathItem?.Operations) : null; Servers = pathItem?.Servers != null ? new List(pathItem.Servers) : null; Parameters = pathItem?.Parameters != null ? new List(pathItem.Parameters) : null; Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem.Extensions) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs index 9b48b4908..53f56c5ad 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs @@ -1,6 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; +using System.Collections; +using System.Collections.Generic; +using Microsoft.OpenApi.Helpers; + namespace Microsoft.OpenApi.Models { /// @@ -17,6 +22,6 @@ public OpenApiPaths() {} /// Initializes a copy of object /// /// The . - public OpenApiPaths(OpenApiPaths paths) : base(dictionary: paths) {} + public OpenApiPaths(OpenApiPaths paths) : base(DictionaryCloneHelper.Clone(paths)) { } } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs index aa7a8c984..86b484408 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using Microsoft.OpenApi.Helpers; + namespace Microsoft.OpenApi.Models { /// @@ -17,6 +19,6 @@ public OpenApiResponses() { } /// Initializes a copy of object /// /// The - public OpenApiResponses(OpenApiResponses openApiResponses) : base(dictionary: openApiResponses) {} + public OpenApiResponses(OpenApiResponses openApiResponses) : base(DictionaryCloneHelper.Clone(openApiResponses)) {} } } From b1f06d75c239e7113fcdcc9136734603bb125ee7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 3 Apr 2023 15:40:53 +0300 Subject: [PATCH 446/855] Add test suite; update public API --- .../Models/OpenApiDocumentTests.cs | 5 ++++- .../PublicApi/PublicApi.approved.txt | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 68bb0e037..8450da0b0 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -12,6 +12,7 @@ using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers; +using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Writers; using VerifyXunit; using Xunit; @@ -1344,9 +1345,10 @@ public void CopyConstructorForAdvancedDocumentWorks() // Arrange & Act var doc = new OpenApiDocument(AdvancedDocument); - // Change value of operation id for a given url var docOpId = doc.Paths["/pets"].Operations[OperationType.Get].OperationId = "findAllMyPets"; var advancedDocOpId = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].OperationId; + var docResponse = doc.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Description = "MyPet"; + var advancedDocResponse = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Description; // Assert Assert.NotNull(doc.Info); @@ -1355,6 +1357,7 @@ public void CopyConstructorForAdvancedDocumentWorks() Assert.Equal(2, doc.Paths.Count); Assert.NotNull(doc.Components); Assert.NotEqual(docOpId, advancedDocOpId); + Assert.NotEqual(docResponse, advancedDocResponse); } [Fact] diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 63cd0f535..d66155389 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -292,6 +292,14 @@ namespace Microsoft.OpenApi.Extensions public static T GetEnumFromDisplayName(this string displayName) { } } } +namespace Microsoft.OpenApi.Helpers +{ + public class DictionaryCloneHelper + { + public DictionaryCloneHelper() { } + public static System.Collections.Generic.Dictionary Clone(System.Collections.Generic.IDictionary dictionary) { } + } +} namespace Microsoft.OpenApi.Interfaces { public interface IEffective @@ -587,6 +595,7 @@ namespace Microsoft.OpenApi.Models { protected OpenApiExtensibleDictionary() { } protected OpenApiExtensibleDictionary(System.Collections.Generic.Dictionary dictionary = null, System.Collections.Generic.IDictionary extensions = null) { } + public System.Collections.Generic.IDictionary Dictionary { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } From 8a93c141697f83b8e998ae9be78651eac26abe27 Mon Sep 17 00:00:00 2001 From: Irvine Sunday Date: Mon, 3 Apr 2023 17:08:18 +0300 Subject: [PATCH 447/855] Use DictionaryCloneHelper --- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 5177e4f45..f80e976cb 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -8,6 +8,7 @@ using System.Security.Cryptography; using System.Text; using Microsoft.OpenApi.Exceptions; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Writers; @@ -88,7 +89,7 @@ public OpenApiDocument(OpenApiDocument document) SecurityRequirements = document?.SecurityRequirements != null ? new List(document.SecurityRequirements) : null; Tags = document?.Tags != null ? new List(document.Tags) : null; ExternalDocs = document?.ExternalDocs != null ? new(document?.ExternalDocs) : null; - Extensions = document?.Extensions != null ? new Dictionary(document.Extensions) : null; + Extensions = document?.Extensions != null ? DictionaryCloneHelper.Clone(document.Extensions) : null; } /// From 608d908664008641983f76a0b764cb1789a92007 Mon Sep 17 00:00:00 2001 From: Irvine Sunday Date: Mon, 3 Apr 2023 17:10:45 +0300 Subject: [PATCH 448/855] Updates XML summary --- src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs index 13d32e184..80ae9af67 100644 --- a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs +++ b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs @@ -14,10 +14,10 @@ public class DictionaryCloneHelper /// /// Deep clone key value pairs in a dictionary. /// - /// - /// - /// - /// + /// The type of the key of the dictionary. + /// The type of the value of the dictionary. + /// The target dictionary to clone. + /// The cloned dictionary. public static Dictionary Clone(IDictionary dictionary) { var clonedDictionary = new Dictionary(); From be998b06d4f7a79fd30bacce587e9a0db1920a8e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 3 Apr 2023 17:24:16 +0300 Subject: [PATCH 449/855] Use DictionaryCloneHelper cloning method for all dictionary copies --- src/Microsoft.OpenApi/Models/OpenApiEncoding.cs | 5 +++-- src/Microsoft.OpenApi/Models/OpenApiExample.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 7 ++++--- src/Microsoft.OpenApi/Models/OpenApiMediaType.cs | 7 ++++--- src/Microsoft.OpenApi/Models/OpenApiResponse.cs | 9 +++++---- 5 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index ddb4162bc..d16b6bb56 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -64,11 +65,11 @@ public OpenApiEncoding() {} public OpenApiEncoding(OpenApiEncoding encoding) { ContentType = encoding?.ContentType ?? ContentType; - Headers = encoding?.Headers != null ? new Dictionary(encoding.Headers) : null; + Headers = encoding?.Headers != null ? DictionaryCloneHelper.Clone(encoding.Headers) : null; Style = encoding?.Style ?? Style; Explode = encoding?.Explode ?? Explode; AllowReserved = encoding?.AllowReserved ?? AllowReserved; - Extensions = encoding?.Extensions != null ? new Dictionary(encoding.Extensions) : null; + Extensions = encoding?.Extensions != null ? DictionaryCloneHelper.Clone(encoding.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 4d091a361..722e1e0d8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -68,7 +69,7 @@ public OpenApiExample(OpenApiExample example) Description = example?.Description ?? Description; Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example?.Value); ExternalValue = example?.ExternalValue ?? ExternalValue; - Extensions = example?.Extensions != null ? new Dictionary(example.Extensions) : null; + Extensions = example?.Extensions != null ? DictionaryCloneHelper.Clone(example.Extensions) : null; Reference = example?.Reference != null ? new(example?.Reference) : null; UnresolvedReference = example?.UnresolvedReference ?? UnresolvedReference; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index fb4411478..6277a24b7 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -107,9 +108,9 @@ public OpenApiHeader(OpenApiHeader header) AllowReserved = header?.AllowReserved ?? AllowReserved; Schema = header?.Schema != null ? new(header?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header?.Example); - Examples = header?.Examples != null ? new Dictionary(header.Examples) : null; - Content = header?.Content != null ? new Dictionary(header.Content) : null; - Extensions = header?.Extensions != null ? new Dictionary(header.Extensions) : null; + Examples = header?.Examples != null ? DictionaryCloneHelper.Clone(header.Examples) : null; + Content = header?.Content != null ? DictionaryCloneHelper.Clone(header.Content) : null; + Extensions = header?.Extensions != null ? DictionaryCloneHelper.Clone(header.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 63a58cd02..c141a36f1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -55,9 +56,9 @@ public OpenApiMediaType(OpenApiMediaType mediaType) { Schema = mediaType?.Schema != null ? new(mediaType?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType?.Example); - Examples = mediaType?.Examples != null ? new Dictionary(mediaType.Examples) : null; - Encoding = mediaType?.Encoding != null ? new Dictionary(mediaType.Encoding) : null; - Extensions = mediaType?.Extensions != null ? new Dictionary(mediaType.Extensions) : null; + Examples = mediaType?.Examples != null ? DictionaryCloneHelper.Clone(mediaType.Examples) : null; + Encoding = mediaType?.Encoding != null ? DictionaryCloneHelper.Clone(mediaType.Encoding) : null; + Extensions = mediaType?.Extensions != null ? DictionaryCloneHelper.Clone(mediaType.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index a173f6c1a..2d4a7ac3e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -62,10 +63,10 @@ public OpenApiResponse() {} public OpenApiResponse(OpenApiResponse response) { Description = response?.Description ?? Description; - Headers = response?.Headers != null ? new Dictionary(response.Headers) : null; - Content = response?.Content != null ? new Dictionary(response.Content) : null; - Links = response?.Links != null ? new Dictionary(response.Links) : null; - Extensions = response?.Extensions != null ? new Dictionary(response.Extensions) : null; + Headers = response?.Headers != null ? DictionaryCloneHelper.Clone(response.Headers) : null; + Content = response?.Content != null ? DictionaryCloneHelper.Clone(response.Content) : null; + Links = response?.Links != null ? DictionaryCloneHelper.Clone(response.Links) : null; + Extensions = response?.Extensions != null ? DictionaryCloneHelper.Clone(response.Extensions) : null; UnresolvedReference = response?.UnresolvedReference ?? UnresolvedReference; Reference = response?.Reference != null ? new(response?.Reference) : null; } From 8d835728baf9457240279109f0a1d8ac2721d29e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 3 Apr 2023 17:24:34 +0300 Subject: [PATCH 450/855] Add test case for content media type --- test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 8450da0b0..ceed06bb9 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1347,8 +1347,8 @@ public void CopyConstructorForAdvancedDocumentWorks() var docOpId = doc.Paths["/pets"].Operations[OperationType.Get].OperationId = "findAllMyPets"; var advancedDocOpId = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].OperationId; - var docResponse = doc.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Description = "MyPet"; - var advancedDocResponse = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Description; + var responseSchemaTypeCopy = doc.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema.Type = "object"; + var advancedDocResponseSchemaType = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema.Type; // Assert Assert.NotNull(doc.Info); @@ -1357,7 +1357,7 @@ public void CopyConstructorForAdvancedDocumentWorks() Assert.Equal(2, doc.Paths.Count); Assert.NotNull(doc.Components); Assert.NotEqual(docOpId, advancedDocOpId); - Assert.NotEqual(docResponse, advancedDocResponse); + Assert.NotEqual(responseSchemaTypeCopy, advancedDocResponseSchemaType); } [Fact] From 6a65cf4c02b13eee81d076c82dcd2214bf65bb0a Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 3 Apr 2023 17:28:52 +0300 Subject: [PATCH 451/855] Update public API --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index d66155389..df9ef4393 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -595,7 +595,6 @@ namespace Microsoft.OpenApi.Models { protected OpenApiExtensibleDictionary() { } protected OpenApiExtensibleDictionary(System.Collections.Generic.Dictionary dictionary = null, System.Collections.Generic.IDictionary extensions = null) { } - public System.Collections.Generic.IDictionary Dictionary { get; set; } public System.Collections.Generic.IDictionary Extensions { get; set; } public void SerializeAsV2(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SerializeAsV3(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } From 264611d48707c3367e07e44597e229bc8c0cc896 Mon Sep 17 00:00:00 2001 From: Irvine Sunday Date: Mon, 3 Apr 2023 18:40:56 +0300 Subject: [PATCH 452/855] Use DictionaryCloneHelper.Clone() method --- .../Models/OpenApiComponents.cs | 23 +++++++++---------- .../Models/OpenApiParameter.cs | 7 +++--- .../Models/OpenApiRequestBody.cs | 5 ++-- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 5 ++-- 4 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 1f41080bc..dd6ee8914 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -1,10 +1,9 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using System.Linq; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -78,15 +77,15 @@ public OpenApiComponents() { } /// public OpenApiComponents(OpenApiComponents components) { - Schemas = components?.Schemas != null ? new Dictionary(components.Schemas) : null; - Responses = components?.Responses != null ? new Dictionary(components.Responses) : null; - Parameters = components?.Parameters != null ? new Dictionary(components.Parameters) : null; - Examples = components?.Examples != null ? new Dictionary(components.Examples) : null; - RequestBodies = components?.RequestBodies != null ? new Dictionary(components.RequestBodies) : null; - Headers = components?.Headers != null ? new Dictionary(components.Headers) : null; - SecuritySchemes = components?.SecuritySchemes != null ? new Dictionary(components.SecuritySchemes) : null; - Links = components?.Links != null ? new Dictionary(components.Links) : null; - Callbacks = components?.Callbacks != null ? new Dictionary(components.Callbacks) : null; + Schemas = components?.Schemas != null ? DictionaryCloneHelper.Clone(components.Schemas) : null; + Responses = components?.Responses != null ? DictionaryCloneHelper.Clone(components.Responses) : null; + Parameters = components?.Parameters != null ? DictionaryCloneHelper.Clone(components.Parameters) : null; + Examples = components?.Examples != null ? DictionaryCloneHelper.Clone(components.Examples) : null; + RequestBodies = components?.RequestBodies != null ? DictionaryCloneHelper.Clone(components.RequestBodies) : null; + Headers = components?.Headers != null ? DictionaryCloneHelper.Clone(components.Headers) : null; + SecuritySchemes = components?.SecuritySchemes != null ? DictionaryCloneHelper.Clone(components.SecuritySchemes) : null; + Links = components?.Links != null ? DictionaryCloneHelper.Clone(components.Links) : null; + Callbacks = components?.Callbacks != null ? DictionaryCloneHelper.Clone(components.Callbacks) : null; Extensions = components?.Extensions != null ? new Dictionary(components.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index fa62f0b79..061081752 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.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; @@ -6,6 +6,7 @@ using System.Runtime; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -162,9 +163,9 @@ public OpenApiParameter(OpenApiParameter parameter) Explode = parameter?.Explode ?? Explode; AllowReserved = parameter?.AllowReserved ?? AllowReserved; Schema = parameter?.Schema != null ? new(parameter?.Schema) : null; - Examples = parameter?.Examples != null ? new Dictionary(parameter.Examples) : null; + Examples = parameter?.Examples != null ? DictionaryCloneHelper.Clone(parameter.Examples) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); - Content = parameter?.Content != null ? new Dictionary(parameter.Content) : null; + Content = parameter?.Content != null ? DictionaryCloneHelper.Clone(parameter.Content) : null; Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; AllowEmptyValue = parameter?.AllowEmptyValue ?? AllowEmptyValue; Deprecated = parameter?.Deprecated ?? Deprecated; diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 70f1f742a..1209c33c7 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -1,10 +1,11 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -61,7 +62,7 @@ public OpenApiRequestBody(OpenApiRequestBody requestBody) Reference = requestBody?.Reference != null ? new(requestBody?.Reference) : null; Description = requestBody?.Description ?? Description; Required = requestBody?.Required ?? Required; - Content = requestBody?.Content != null ? new Dictionary(requestBody.Content) : null; + Content = requestBody?.Content != null ? DictionaryCloneHelper.Clone(requestBody.Content) : null; Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index b3b1d1287..d009e7a14 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -1,8 +1,9 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -48,7 +49,7 @@ public OpenApiServer(OpenApiServer server) { Description = server?.Description ?? Description; Url = server?.Url ?? Url; - Variables = server?.Variables != null ? new Dictionary(server.Variables) : null; + Variables = server?.Variables != null ? DictionaryCloneHelper.Clone(server.Variables) : null; Extensions = server?.Extensions != null ? new Dictionary(server.Extensions) : null; } From 08acaaa791194bcee20bea329e1901b894db8b27 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 4 Apr 2023 10:25:18 +0300 Subject: [PATCH 453/855] Clean up dictionary cloning logic --- src/Microsoft.OpenApi/Models/OpenApiComponents.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiContact.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiLicense.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs | 5 +++-- src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiOperation.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiPathItem.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiTag.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiXml.cs | 3 ++- 18 files changed, 35 insertions(+), 23 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index dd6ee8914..5c4a56d56 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.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; @@ -86,7 +86,7 @@ public OpenApiComponents(OpenApiComponents components) SecuritySchemes = components?.SecuritySchemes != null ? DictionaryCloneHelper.Clone(components.SecuritySchemes) : null; Links = components?.Links != null ? DictionaryCloneHelper.Clone(components.Links) : null; Callbacks = components?.Callbacks != null ? DictionaryCloneHelper.Clone(components.Callbacks) : null; - Extensions = components?.Extensions != null ? new Dictionary(components.Extensions) : null; + Extensions = components?.Extensions != null ? DictionaryCloneHelper.Clone(components.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 93cb11bca..1d89237e3 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -48,7 +49,7 @@ public OpenApiContact(OpenApiContact contact) Name = contact?.Name ?? Name; Url = contact?.Url != null ? new Uri(contact.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; Email = contact?.Email ?? Email; - Extensions = contact?.Extensions != null ? new Dictionary(contact.Extensions) : null; + Extensions = contact?.Extensions != null ? DictionaryCloneHelper.Clone(contact.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs index 40c26d429..b07cca7c6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.Collections.Generic; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -30,7 +31,7 @@ protected OpenApiExtensibleDictionary( Dictionary dictionary = null, IDictionary extensions = null) : base (dictionary) { - Extensions = extensions != null ? new Dictionary(extensions) : null; + Extensions = extensions != null ? DictionaryCloneHelper.Clone(extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 345f07d59..4a438de8f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -41,7 +42,7 @@ public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) { Description = externalDocs?.Description ?? Description; Url = externalDocs?.Url != null ? new Uri(externalDocs.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; - Extensions = externalDocs?.Extensions != null ? new Dictionary(externalDocs.Extensions) : null; + Extensions = externalDocs?.Extensions != null ? DictionaryCloneHelper.Clone(externalDocs.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index df0aa0a49..08548310f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -65,7 +66,7 @@ public OpenApiInfo(OpenApiInfo info) TermsOfService = info?.TermsOfService ?? TermsOfService; Contact = info?.Contact != null ? new(info?.Contact) : null; License = info?.License != null ? new(info?.License) : null; - Extensions = info?.Extensions != null ? new Dictionary(info.Extensions) : null; + Extensions = info?.Extensions != null ? DictionaryCloneHelper.Clone(info.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 866515835..0ea58e333 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -41,7 +42,7 @@ public OpenApiLicense(OpenApiLicense license) { Name = license?.Name ?? Name; Url = license?.Url != null ? new Uri(license.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; - Extensions = license?.Extensions != null ? new Dictionary(license.Extensions) : null; + Extensions = license?.Extensions != null ? DictionaryCloneHelper.Clone(license.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index b682744e9..5d9e1b5e1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -77,7 +78,7 @@ public OpenApiLink(OpenApiLink link) RequestBody = link?.RequestBody != null ? new(link?.RequestBody) : null; Description = link?.Description ?? Description; Server = link?.Server != null ? new(link?.Server) : null; - Extensions = link?.Extensions != null ? new Dictionary(link.Extensions) : null; + Extensions = link?.Extensions != null ? DictionaryCloneHelper.Clone(link.Extensions) : null; UnresolvedReference = link?.UnresolvedReference ?? UnresolvedReference; Reference = link?.Reference != null ? new(link?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index 9c12fb5a9..f71e7eaf2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -54,8 +55,8 @@ public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) AuthorizationUrl = oAuthFlow?.AuthorizationUrl != null ? new Uri(oAuthFlow.AuthorizationUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; TokenUrl = oAuthFlow?.TokenUrl != null ? new Uri(oAuthFlow.TokenUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; RefreshUrl = oAuthFlow?.RefreshUrl != null ? new Uri(oAuthFlow.RefreshUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; - Scopes = oAuthFlow?.Scopes != null ? new Dictionary(oAuthFlow.Scopes) : null; - Extensions = oAuthFlow?.Extensions != null ? new Dictionary(oAuthFlow.Extensions) : null; + Scopes = oAuthFlow?.Scopes != null ? DictionaryCloneHelper.Clone(oAuthFlow.Scopes) : null; + Extensions = oAuthFlow?.Extensions != null ? DictionaryCloneHelper.Clone(oAuthFlow.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index 8443e6730..b8cb626e8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -53,7 +54,7 @@ public OpenApiOAuthFlows(OpenApiOAuthFlows oAuthFlows) Password = oAuthFlows?.Password != null ? new(oAuthFlows?.Password) : null; ClientCredentials = oAuthFlows?.ClientCredentials != null ? new(oAuthFlows?.ClientCredentials) : null; AuthorizationCode = oAuthFlows?.AuthorizationCode != null ? new(oAuthFlows?.AuthorizationCode) : null; - Extensions = oAuthFlows?.Extensions != null ? new Dictionary(oAuthFlows.Extensions) : null; + Extensions = oAuthFlows?.Extensions != null ? DictionaryCloneHelper.Clone(oAuthFlows.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index d46dc598e..cabb61d68 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -129,7 +129,7 @@ public OpenApiOperation(OpenApiOperation operation) Deprecated = operation?.Deprecated ?? Deprecated; Security = operation?.Security != null ? new List(operation.Security) : null; Servers = operation?.Servers != null ? new List(operation.Servers) : null; - Extensions = operation?.Extensions != null ? new Dictionary(operation.Extensions) : null; + Extensions = operation?.Extensions != null ? DictionaryCloneHelper.Clone(operation.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 061081752..16e9a32c1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.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; @@ -166,7 +166,7 @@ public OpenApiParameter(OpenApiParameter parameter) Examples = parameter?.Examples != null ? DictionaryCloneHelper.Clone(parameter.Examples) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); Content = parameter?.Content != null ? DictionaryCloneHelper.Clone(parameter.Content) : null; - Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; + Extensions = parameter?.Extensions != null ? DictionaryCloneHelper.Clone(parameter.Extensions) : null; AllowEmptyValue = parameter?.AllowEmptyValue ?? AllowEmptyValue; Deprecated = parameter?.Deprecated ?? Deprecated; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index 61de36c7c..c0e93cad4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -82,7 +82,7 @@ public OpenApiPathItem(OpenApiPathItem pathItem) Operations = pathItem?.Operations != null ? DictionaryCloneHelper.Clone(pathItem?.Operations) : null; Servers = pathItem?.Servers != null ? new List(pathItem.Servers) : null; Parameters = pathItem?.Parameters != null ? new List(pathItem.Parameters) : null; - Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem.Extensions) : null; + Extensions = pathItem?.Extensions != null ? DictionaryCloneHelper.Clone(pathItem.Extensions) : null; UnresolvedReference = pathItem?.UnresolvedReference ?? UnresolvedReference; Reference = pathItem?.Reference != null ? new(pathItem?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 1209c33c7..f437f9097 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.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; @@ -63,7 +63,7 @@ public OpenApiRequestBody(OpenApiRequestBody requestBody) Description = requestBody?.Description ?? Description; Required = requestBody?.Required ?? Required; Content = requestBody?.Content != null ? DictionaryCloneHelper.Clone(requestBody.Content) : null; - Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody.Extensions) : null; + Extensions = requestBody?.Extensions != null ? DictionaryCloneHelper.Clone(requestBody.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 616a6a022..de924ff7e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -6,6 +6,7 @@ using System.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -92,7 +93,7 @@ public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) BearerFormat = securityScheme?.BearerFormat ?? BearerFormat; Flows = securityScheme?.Flows != null ? new(securityScheme?.Flows) : null; OpenIdConnectUrl = securityScheme?.OpenIdConnectUrl != null ? new Uri(securityScheme.OpenIdConnectUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; - Extensions = securityScheme?.Extensions != null ? new Dictionary(securityScheme.Extensions) : null; + Extensions = securityScheme?.Extensions != null ? DictionaryCloneHelper.Clone(securityScheme.Extensions) : null; UnresolvedReference = securityScheme?.UnresolvedReference ?? UnresolvedReference; Reference = securityScheme?.Reference != null ? new(securityScheme?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index d009e7a14..a736543a2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.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; @@ -50,7 +50,7 @@ public OpenApiServer(OpenApiServer server) Description = server?.Description ?? Description; Url = server?.Url ?? Url; Variables = server?.Variables != null ? DictionaryCloneHelper.Clone(server.Variables) : null; - Extensions = server?.Extensions != null ? new Dictionary(server.Extensions) : null; + Extensions = server?.Extensions != null ? DictionaryCloneHelper.Clone(server.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index 70164bc59..a78759310 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -47,7 +48,7 @@ public OpenApiServerVariable(OpenApiServerVariable serverVariable) Description = serverVariable?.Description; Default = serverVariable?.Default; Enum = serverVariable?.Enum != null ? new List(serverVariable?.Enum) : serverVariable?.Enum; - Extensions = serverVariable?.Extensions != null ? new Dictionary(serverVariable?.Extensions) : serverVariable?.Extensions; + Extensions = serverVariable?.Extensions != null ? DictionaryCloneHelper.Clone(serverVariable?.Extensions) : serverVariable?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index ba4129142..78003c4a1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -56,7 +57,7 @@ public OpenApiTag(OpenApiTag tag) Name = tag?.Name ?? Name; Description = tag?.Description ?? Description; ExternalDocs = tag?.ExternalDocs != null ? new(tag?.ExternalDocs) : null; - Extensions = tag?.Extensions != null ? new Dictionary(tag.Extensions) : null; + Extensions = tag?.Extensions != null ? DictionaryCloneHelper.Clone(tag.Extensions) : null; UnresolvedReference = tag?.UnresolvedReference ?? UnresolvedReference; Reference = tag?.Reference != null ? new(tag?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index c6719d85e..7a2f2cde8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -61,7 +62,7 @@ public OpenApiXml(OpenApiXml xml) Prefix = xml?.Prefix ?? Prefix; Attribute = xml?.Attribute ?? Attribute; Wrapped = xml?.Wrapped ?? Wrapped; - Extensions = xml?.Extensions != null ? new Dictionary(xml.Extensions) : null; + Extensions = xml?.Extensions != null ? DictionaryCloneHelper.Clone(xml.Extensions) : null; } /// From 9af76212e48bf7555bb2b586ca5d1497d57edef7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 4 Apr 2023 10:26:42 +0300 Subject: [PATCH 454/855] Clean up code --- src/Microsoft.OpenApi/Models/OpenApiCallback.cs | 3 ++- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index 2dcae12d1..b300a7215 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Expressions; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -48,7 +49,7 @@ public OpenApiCallback(OpenApiCallback callback) PathItems = callback?.PathItems != null ? new(callback?.PathItems) : null; UnresolvedReference = callback?.UnresolvedReference ?? UnresolvedReference; Reference = callback?.Reference != null ? new(callback?.Reference) : null; - Extensions = callback?.Extensions != null ? new Dictionary(callback.Extensions) : null; + Extensions = callback?.Extensions != null ? DictionaryCloneHelper.Clone(callback.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 0176ea1d9..ddb916404 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -276,7 +277,7 @@ public OpenApiSchema(OpenApiSchema schema) MaxItems = schema?.MaxItems ?? MaxItems; MinItems = schema?.MinItems ?? MinItems; UniqueItems = schema?.UniqueItems ?? UniqueItems; - Properties = schema?.Properties != null ? new Dictionary(schema.Properties) : null; + Properties = schema?.Properties != null ? DictionaryCloneHelper.Clone(schema.Properties) : null; MaxProperties = schema?.MaxProperties ?? MaxProperties; MinProperties = schema?.MinProperties ?? MinProperties; AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? AdditionalPropertiesAllowed; From da9cd6af867f4f9f69e2bc70fad46b8b1e5b7c04 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 4 Apr 2023 10:25:18 +0300 Subject: [PATCH 455/855] Revert "Clean up dictionary cloning logic " This reverts commit 08acaaa791194bcee20bea329e1901b894db8b27. --- src/Microsoft.OpenApi/Models/OpenApiComponents.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiContact.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiLicense.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs | 5 ++--- src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiOperation.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiPathItem.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiTag.cs | 3 +-- src/Microsoft.OpenApi/Models/OpenApiXml.cs | 3 +-- 18 files changed, 23 insertions(+), 35 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 5c4a56d56..dd6ee8914 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.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; @@ -86,7 +86,7 @@ public OpenApiComponents(OpenApiComponents components) SecuritySchemes = components?.SecuritySchemes != null ? DictionaryCloneHelper.Clone(components.SecuritySchemes) : null; Links = components?.Links != null ? DictionaryCloneHelper.Clone(components.Links) : null; Callbacks = components?.Callbacks != null ? DictionaryCloneHelper.Clone(components.Callbacks) : null; - Extensions = components?.Extensions != null ? DictionaryCloneHelper.Clone(components.Extensions) : null; + Extensions = components?.Extensions != null ? new Dictionary(components.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 1d89237e3..93cb11bca 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -49,7 +48,7 @@ public OpenApiContact(OpenApiContact contact) Name = contact?.Name ?? Name; Url = contact?.Url != null ? new Uri(contact.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; Email = contact?.Email ?? Email; - Extensions = contact?.Extensions != null ? DictionaryCloneHelper.Clone(contact.Extensions) : null; + Extensions = contact?.Extensions != null ? new Dictionary(contact.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs index b07cca7c6..40c26d429 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -31,7 +30,7 @@ protected OpenApiExtensibleDictionary( Dictionary dictionary = null, IDictionary extensions = null) : base (dictionary) { - Extensions = extensions != null ? DictionaryCloneHelper.Clone(extensions) : null; + Extensions = extensions != null ? new Dictionary(extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 4a438de8f..345f07d59 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -42,7 +41,7 @@ public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) { Description = externalDocs?.Description ?? Description; Url = externalDocs?.Url != null ? new Uri(externalDocs.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; - Extensions = externalDocs?.Extensions != null ? DictionaryCloneHelper.Clone(externalDocs.Extensions) : null; + Extensions = externalDocs?.Extensions != null ? new Dictionary(externalDocs.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index 08548310f..df0aa0a49 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -66,7 +65,7 @@ public OpenApiInfo(OpenApiInfo info) TermsOfService = info?.TermsOfService ?? TermsOfService; Contact = info?.Contact != null ? new(info?.Contact) : null; License = info?.License != null ? new(info?.License) : null; - Extensions = info?.Extensions != null ? DictionaryCloneHelper.Clone(info.Extensions) : null; + Extensions = info?.Extensions != null ? new Dictionary(info.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 0ea58e333..866515835 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -42,7 +41,7 @@ public OpenApiLicense(OpenApiLicense license) { Name = license?.Name ?? Name; Url = license?.Url != null ? new Uri(license.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; - Extensions = license?.Extensions != null ? DictionaryCloneHelper.Clone(license.Extensions) : null; + Extensions = license?.Extensions != null ? new Dictionary(license.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index 5d9e1b5e1..b682744e9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -78,7 +77,7 @@ public OpenApiLink(OpenApiLink link) RequestBody = link?.RequestBody != null ? new(link?.RequestBody) : null; Description = link?.Description ?? Description; Server = link?.Server != null ? new(link?.Server) : null; - Extensions = link?.Extensions != null ? DictionaryCloneHelper.Clone(link.Extensions) : null; + Extensions = link?.Extensions != null ? new Dictionary(link.Extensions) : null; UnresolvedReference = link?.UnresolvedReference ?? UnresolvedReference; Reference = link?.Reference != null ? new(link?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index f71e7eaf2..9c12fb5a9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -55,8 +54,8 @@ public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) AuthorizationUrl = oAuthFlow?.AuthorizationUrl != null ? new Uri(oAuthFlow.AuthorizationUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; TokenUrl = oAuthFlow?.TokenUrl != null ? new Uri(oAuthFlow.TokenUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; RefreshUrl = oAuthFlow?.RefreshUrl != null ? new Uri(oAuthFlow.RefreshUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; - Scopes = oAuthFlow?.Scopes != null ? DictionaryCloneHelper.Clone(oAuthFlow.Scopes) : null; - Extensions = oAuthFlow?.Extensions != null ? DictionaryCloneHelper.Clone(oAuthFlow.Extensions) : null; + Scopes = oAuthFlow?.Scopes != null ? new Dictionary(oAuthFlow.Scopes) : null; + Extensions = oAuthFlow?.Extensions != null ? new Dictionary(oAuthFlow.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index b8cb626e8..8443e6730 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -54,7 +53,7 @@ public OpenApiOAuthFlows(OpenApiOAuthFlows oAuthFlows) Password = oAuthFlows?.Password != null ? new(oAuthFlows?.Password) : null; ClientCredentials = oAuthFlows?.ClientCredentials != null ? new(oAuthFlows?.ClientCredentials) : null; AuthorizationCode = oAuthFlows?.AuthorizationCode != null ? new(oAuthFlows?.AuthorizationCode) : null; - Extensions = oAuthFlows?.Extensions != null ? DictionaryCloneHelper.Clone(oAuthFlows.Extensions) : null; + Extensions = oAuthFlows?.Extensions != null ? new Dictionary(oAuthFlows.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index cabb61d68..d46dc598e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -129,7 +129,7 @@ public OpenApiOperation(OpenApiOperation operation) Deprecated = operation?.Deprecated ?? Deprecated; Security = operation?.Security != null ? new List(operation.Security) : null; Servers = operation?.Servers != null ? new List(operation.Servers) : null; - Extensions = operation?.Extensions != null ? DictionaryCloneHelper.Clone(operation.Extensions) : null; + Extensions = operation?.Extensions != null ? new Dictionary(operation.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 16e9a32c1..061081752 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.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; @@ -166,7 +166,7 @@ public OpenApiParameter(OpenApiParameter parameter) Examples = parameter?.Examples != null ? DictionaryCloneHelper.Clone(parameter.Examples) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); Content = parameter?.Content != null ? DictionaryCloneHelper.Clone(parameter.Content) : null; - Extensions = parameter?.Extensions != null ? DictionaryCloneHelper.Clone(parameter.Extensions) : null; + Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; AllowEmptyValue = parameter?.AllowEmptyValue ?? AllowEmptyValue; Deprecated = parameter?.Deprecated ?? Deprecated; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index c0e93cad4..61de36c7c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -82,7 +82,7 @@ public OpenApiPathItem(OpenApiPathItem pathItem) Operations = pathItem?.Operations != null ? DictionaryCloneHelper.Clone(pathItem?.Operations) : null; Servers = pathItem?.Servers != null ? new List(pathItem.Servers) : null; Parameters = pathItem?.Parameters != null ? new List(pathItem.Parameters) : null; - Extensions = pathItem?.Extensions != null ? DictionaryCloneHelper.Clone(pathItem.Extensions) : null; + Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem.Extensions) : null; UnresolvedReference = pathItem?.UnresolvedReference ?? UnresolvedReference; Reference = pathItem?.Reference != null ? new(pathItem?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index f437f9097..1209c33c7 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.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; @@ -63,7 +63,7 @@ public OpenApiRequestBody(OpenApiRequestBody requestBody) Description = requestBody?.Description ?? Description; Required = requestBody?.Required ?? Required; Content = requestBody?.Content != null ? DictionaryCloneHelper.Clone(requestBody.Content) : null; - Extensions = requestBody?.Extensions != null ? DictionaryCloneHelper.Clone(requestBody.Extensions) : null; + Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index de924ff7e..616a6a022 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -6,7 +6,6 @@ using System.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -93,7 +92,7 @@ public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) BearerFormat = securityScheme?.BearerFormat ?? BearerFormat; Flows = securityScheme?.Flows != null ? new(securityScheme?.Flows) : null; OpenIdConnectUrl = securityScheme?.OpenIdConnectUrl != null ? new Uri(securityScheme.OpenIdConnectUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; - Extensions = securityScheme?.Extensions != null ? DictionaryCloneHelper.Clone(securityScheme.Extensions) : null; + Extensions = securityScheme?.Extensions != null ? new Dictionary(securityScheme.Extensions) : null; UnresolvedReference = securityScheme?.UnresolvedReference ?? UnresolvedReference; Reference = securityScheme?.Reference != null ? new(securityScheme?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index a736543a2..d009e7a14 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.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; @@ -50,7 +50,7 @@ public OpenApiServer(OpenApiServer server) Description = server?.Description ?? Description; Url = server?.Url ?? Url; Variables = server?.Variables != null ? DictionaryCloneHelper.Clone(server.Variables) : null; - Extensions = server?.Extensions != null ? DictionaryCloneHelper.Clone(server.Extensions) : null; + Extensions = server?.Extensions != null ? new Dictionary(server.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index a78759310..70164bc59 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -48,7 +47,7 @@ public OpenApiServerVariable(OpenApiServerVariable serverVariable) Description = serverVariable?.Description; Default = serverVariable?.Default; Enum = serverVariable?.Enum != null ? new List(serverVariable?.Enum) : serverVariable?.Enum; - Extensions = serverVariable?.Extensions != null ? DictionaryCloneHelper.Clone(serverVariable?.Extensions) : serverVariable?.Extensions; + Extensions = serverVariable?.Extensions != null ? new Dictionary(serverVariable?.Extensions) : serverVariable?.Extensions; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index 78003c4a1..ba4129142 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -57,7 +56,7 @@ public OpenApiTag(OpenApiTag tag) Name = tag?.Name ?? Name; Description = tag?.Description ?? Description; ExternalDocs = tag?.ExternalDocs != null ? new(tag?.ExternalDocs) : null; - Extensions = tag?.Extensions != null ? DictionaryCloneHelper.Clone(tag.Extensions) : null; + Extensions = tag?.Extensions != null ? new Dictionary(tag.Extensions) : null; UnresolvedReference = tag?.UnresolvedReference ?? UnresolvedReference; Reference = tag?.Reference != null ? new(tag?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index 7a2f2cde8..c6719d85e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -62,7 +61,7 @@ public OpenApiXml(OpenApiXml xml) Prefix = xml?.Prefix ?? Prefix; Attribute = xml?.Attribute ?? Attribute; Wrapped = xml?.Wrapped ?? Wrapped; - Extensions = xml?.Extensions != null ? DictionaryCloneHelper.Clone(xml.Extensions) : null; + Extensions = xml?.Extensions != null ? new Dictionary(xml.Extensions) : null; } /// From b97ef997e608a31af406f0f3819b088b4c4dc45b Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 5 Apr 2023 14:54:33 +0300 Subject: [PATCH 456/855] Code cleanup --- src/Microsoft.OpenApi/Models/OpenApiCallback.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index b300a7215..b25ed8578 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -49,7 +49,7 @@ public OpenApiCallback(OpenApiCallback callback) PathItems = callback?.PathItems != null ? new(callback?.PathItems) : null; UnresolvedReference = callback?.UnresolvedReference ?? UnresolvedReference; Reference = callback?.Reference != null ? new(callback?.Reference) : null; - Extensions = callback?.Extensions != null ? DictionaryCloneHelper.Clone(callback.Extensions) : null; + Extensions = callback?.Extensions != null ? new Dictionary(callback.Extensions) : null; } /// From 6d60b73af02d85d986efb14d735a477ef2d4ef38 Mon Sep 17 00:00:00 2001 From: Irvine Sunday <40403681+irvinesunday@users.noreply.github.com> Date: Wed, 5 Apr 2023 16:52:11 +0300 Subject: [PATCH 457/855] Update conversion lib. version to `1.4.0-preview1` --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index a018775cb..8ac62a9a2 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 089d181d14e8e12ff1b495cf35293366e0b7c55a Mon Sep 17 00:00:00 2001 From: Irvine Sunday <40403681+irvinesunday@users.noreply.github.com> Date: Wed, 5 Apr 2023 16:55:43 +0300 Subject: [PATCH 458/855] Bump up hidi version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 8ac62a9a2..092c782a7 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.2.5-preview1 + 1.2.5-preview2 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET From fb297a105c1f20a93feb05990959b1ce6f865f0e Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 6 Apr 2023 15:26:19 +0300 Subject: [PATCH 459/855] Address PR feedback --- .../Helpers/DictionaryCloneHelper.cs | 8 ++++---- .../Models/OpenApiComponents.cs | 20 +++++++++---------- .../Models/OpenApiDocument.cs | 2 +- .../Models/OpenApiEncoding.cs | 4 ++-- .../Models/OpenApiExample.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 6 +++--- .../Models/OpenApiMediaType.cs | 6 +++--- .../Models/OpenApiOperation.cs | 2 +- .../Models/OpenApiParameter.cs | 6 +++--- .../Models/OpenApiPathItem.cs | 2 +- .../Models/OpenApiRequestBody.cs | 4 ++-- .../Models/OpenApiResponse.cs | 8 ++++---- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 4 ++-- 14 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs index 80ae9af67..bda087d08 100644 --- a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs +++ b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs @@ -9,7 +9,7 @@ namespace Microsoft.OpenApi.Helpers /// /// Helper class for deep cloning dictionaries. /// - public class DictionaryCloneHelper + internal class DictionaryCloneHelper { /// /// Deep clone key value pairs in a dictionary. @@ -18,9 +18,9 @@ public class DictionaryCloneHelper /// The type of the value of the dictionary. /// The target dictionary to clone. /// The cloned dictionary. - public static Dictionary Clone(IDictionary dictionary) - { - var clonedDictionary = new Dictionary(); + internal static Dictionary Clone(IDictionary dictionary) + { + var clonedDictionary = dictionary is null ? null : new Dictionary(); if (dictionary != null) { diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index dd6ee8914..1b1b91abe 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.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; @@ -77,15 +77,15 @@ public OpenApiComponents() { } /// public OpenApiComponents(OpenApiComponents components) { - Schemas = components?.Schemas != null ? DictionaryCloneHelper.Clone(components.Schemas) : null; - Responses = components?.Responses != null ? DictionaryCloneHelper.Clone(components.Responses) : null; - Parameters = components?.Parameters != null ? DictionaryCloneHelper.Clone(components.Parameters) : null; - Examples = components?.Examples != null ? DictionaryCloneHelper.Clone(components.Examples) : null; - RequestBodies = components?.RequestBodies != null ? DictionaryCloneHelper.Clone(components.RequestBodies) : null; - Headers = components?.Headers != null ? DictionaryCloneHelper.Clone(components.Headers) : null; - SecuritySchemes = components?.SecuritySchemes != null ? DictionaryCloneHelper.Clone(components.SecuritySchemes) : null; - Links = components?.Links != null ? DictionaryCloneHelper.Clone(components.Links) : null; - Callbacks = components?.Callbacks != null ? DictionaryCloneHelper.Clone(components.Callbacks) : null; + Schemas = DictionaryCloneHelper.Clone(components.Schemas); + Responses = DictionaryCloneHelper.Clone(components.Responses); + Parameters = DictionaryCloneHelper.Clone(components.Parameters); + Examples = DictionaryCloneHelper.Clone(components.Examples); + RequestBodies = DictionaryCloneHelper.Clone(components.RequestBodies); + Headers = DictionaryCloneHelper.Clone(components.Headers); + SecuritySchemes = DictionaryCloneHelper.Clone(components.SecuritySchemes); + Links = DictionaryCloneHelper.Clone(components.Links); + Callbacks = DictionaryCloneHelper.Clone(components.Callbacks); Extensions = components?.Extensions != null ? new Dictionary(components.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index f80e976cb..2bf5dd2f2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -89,7 +89,7 @@ public OpenApiDocument(OpenApiDocument document) SecurityRequirements = document?.SecurityRequirements != null ? new List(document.SecurityRequirements) : null; Tags = document?.Tags != null ? new List(document.Tags) : null; ExternalDocs = document?.ExternalDocs != null ? new(document?.ExternalDocs) : null; - Extensions = document?.Extensions != null ? DictionaryCloneHelper.Clone(document.Extensions) : null; + Extensions = document?.Extensions != null ? new Dictionary(document.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index d16b6bb56..23a45653a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -65,11 +65,11 @@ public OpenApiEncoding() {} public OpenApiEncoding(OpenApiEncoding encoding) { ContentType = encoding?.ContentType ?? ContentType; - Headers = encoding?.Headers != null ? DictionaryCloneHelper.Clone(encoding.Headers) : null; + Headers = DictionaryCloneHelper.Clone(encoding.Headers); Style = encoding?.Style ?? Style; Explode = encoding?.Explode ?? Explode; AllowReserved = encoding?.AllowReserved ?? AllowReserved; - Extensions = encoding?.Extensions != null ? DictionaryCloneHelper.Clone(encoding.Extensions) : null; + Extensions = DictionaryCloneHelper.Clone(encoding.Extensions); } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 722e1e0d8..73f63a0ab 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -69,7 +69,7 @@ public OpenApiExample(OpenApiExample example) Description = example?.Description ?? Description; Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example?.Value); ExternalValue = example?.ExternalValue ?? ExternalValue; - Extensions = example?.Extensions != null ? DictionaryCloneHelper.Clone(example.Extensions) : null; + Extensions = DictionaryCloneHelper.Clone(example.Extensions); Reference = example?.Reference != null ? new(example?.Reference) : null; UnresolvedReference = example?.UnresolvedReference ?? UnresolvedReference; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index 6277a24b7..a2d388a6a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -108,9 +108,9 @@ public OpenApiHeader(OpenApiHeader header) AllowReserved = header?.AllowReserved ?? AllowReserved; Schema = header?.Schema != null ? new(header?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header?.Example); - Examples = header?.Examples != null ? DictionaryCloneHelper.Clone(header.Examples) : null; - Content = header?.Content != null ? DictionaryCloneHelper.Clone(header.Content) : null; - Extensions = header?.Extensions != null ? DictionaryCloneHelper.Clone(header.Extensions) : null; + Examples = DictionaryCloneHelper.Clone(header.Examples); + Content = DictionaryCloneHelper.Clone(header.Content); + Extensions = header?.Extensions != null ? new Dictionary(header.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index c141a36f1..06ba9a745 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -56,9 +56,9 @@ public OpenApiMediaType(OpenApiMediaType mediaType) { Schema = mediaType?.Schema != null ? new(mediaType?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType?.Example); - Examples = mediaType?.Examples != null ? DictionaryCloneHelper.Clone(mediaType.Examples) : null; - Encoding = mediaType?.Encoding != null ? DictionaryCloneHelper.Clone(mediaType.Encoding) : null; - Extensions = mediaType?.Extensions != null ? DictionaryCloneHelper.Clone(mediaType.Extensions) : null; + Examples = DictionaryCloneHelper.Clone(mediaType.Examples); + Encoding = DictionaryCloneHelper.Clone(mediaType.Encoding); + Extensions = mediaType?.Extensions != null ? new Dictionary(mediaType.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index d46dc598e..99438574c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -125,7 +125,7 @@ public OpenApiOperation(OpenApiOperation operation) Parameters = operation?.Parameters != null ? new List(operation.Parameters) : null; RequestBody = new(operation?.RequestBody); Responses = operation?.Responses != null ? new(operation?.Responses) : null; - Callbacks = operation?.Callbacks != null ? DictionaryCloneHelper.Clone(operation.Callbacks) : null; + Callbacks = DictionaryCloneHelper.Clone(operation.Callbacks); Deprecated = operation?.Deprecated ?? Deprecated; Security = operation?.Security != null ? new List(operation.Security) : null; Servers = operation?.Servers != null ? new List(operation.Servers) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 061081752..194a68b3f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.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; @@ -163,9 +163,9 @@ public OpenApiParameter(OpenApiParameter parameter) Explode = parameter?.Explode ?? Explode; AllowReserved = parameter?.AllowReserved ?? AllowReserved; Schema = parameter?.Schema != null ? new(parameter?.Schema) : null; - Examples = parameter?.Examples != null ? DictionaryCloneHelper.Clone(parameter.Examples) : null; + Examples = DictionaryCloneHelper.Clone(parameter.Examples); Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); - Content = parameter?.Content != null ? DictionaryCloneHelper.Clone(parameter.Content) : null; + Content = DictionaryCloneHelper.Clone(parameter.Content); Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; AllowEmptyValue = parameter?.AllowEmptyValue ?? AllowEmptyValue; Deprecated = parameter?.Deprecated ?? Deprecated; diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index 61de36c7c..a669c67bc 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -79,7 +79,7 @@ public OpenApiPathItem(OpenApiPathItem pathItem) { Summary = pathItem?.Summary ?? Summary; Description = pathItem?.Description ?? Description; - Operations = pathItem?.Operations != null ? DictionaryCloneHelper.Clone(pathItem?.Operations) : null; + Operations = DictionaryCloneHelper.Clone(pathItem?.Operations); Servers = pathItem?.Servers != null ? new List(pathItem.Servers) : null; Parameters = pathItem?.Parameters != null ? new List(pathItem.Parameters) : null; Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem.Extensions) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 1209c33c7..025422077 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.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; @@ -62,7 +62,7 @@ public OpenApiRequestBody(OpenApiRequestBody requestBody) Reference = requestBody?.Reference != null ? new(requestBody?.Reference) : null; Description = requestBody?.Description ?? Description; Required = requestBody?.Required ?? Required; - Content = requestBody?.Content != null ? DictionaryCloneHelper.Clone(requestBody.Content) : null; + Content = DictionaryCloneHelper.Clone(requestBody.Content); Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index 2d4a7ac3e..928492da6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -63,10 +63,10 @@ public OpenApiResponse() {} public OpenApiResponse(OpenApiResponse response) { Description = response?.Description ?? Description; - Headers = response?.Headers != null ? DictionaryCloneHelper.Clone(response.Headers) : null; - Content = response?.Content != null ? DictionaryCloneHelper.Clone(response.Content) : null; - Links = response?.Links != null ? DictionaryCloneHelper.Clone(response.Links) : null; - Extensions = response?.Extensions != null ? DictionaryCloneHelper.Clone(response.Extensions) : null; + Headers = DictionaryCloneHelper.Clone(response.Headers); + Content = DictionaryCloneHelper.Clone(response.Content); + Links = DictionaryCloneHelper.Clone(response.Links); + Extensions = response?.Extensions != null ? new Dictionary(response.Extensions) : null; UnresolvedReference = response?.UnresolvedReference ?? UnresolvedReference; Reference = response?.Reference != null ? new(response?.Reference) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index ddb916404..1843c90ff 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -277,7 +277,7 @@ public OpenApiSchema(OpenApiSchema schema) MaxItems = schema?.MaxItems ?? MaxItems; MinItems = schema?.MinItems ?? MinItems; UniqueItems = schema?.UniqueItems ?? UniqueItems; - Properties = schema?.Properties != null ? DictionaryCloneHelper.Clone(schema.Properties) : null; + Properties = DictionaryCloneHelper.Clone(schema.Properties); MaxProperties = schema?.MaxProperties ?? MaxProperties; MinProperties = schema?.MinProperties ?? MinProperties; AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? AdditionalPropertiesAllowed; diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index d009e7a14..05dd67ae1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.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; @@ -49,7 +49,7 @@ public OpenApiServer(OpenApiServer server) { Description = server?.Description ?? Description; Url = server?.Url ?? Url; - Variables = server?.Variables != null ? DictionaryCloneHelper.Clone(server.Variables) : null; + Variables = DictionaryCloneHelper.Clone(server.Variables); Extensions = server?.Extensions != null ? new Dictionary(server.Extensions) : null; } From 52873821f29f1bf1dc23ce6b50619788bb3a1ccc Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 6 Apr 2023 16:52:01 +0300 Subject: [PATCH 460/855] Update src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs index bda087d08..a1976bd70 100644 --- a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs +++ b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs @@ -20,7 +20,8 @@ internal class DictionaryCloneHelper /// The cloned dictionary. internal static Dictionary Clone(IDictionary dictionary) { - var clonedDictionary = dictionary is null ? null : new Dictionary(); + if (dictionary is null) return null; + var clonedDictionary = new Dictionary(); if (dictionary != null) { From 90461163140a953dbca6587f022e9cdd9f80384f Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 6 Apr 2023 17:03:09 +0300 Subject: [PATCH 461/855] Add null propagation --- .../Models/OpenApiComponents.cs | 18 +++++++++--------- .../Models/OpenApiEncoding.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiExample.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 4 ++-- .../Models/OpenApiMediaType.cs | 4 ++-- .../Models/OpenApiOperation.cs | 2 +- .../Models/OpenApiParameter.cs | 2 +- .../Models/OpenApiRequestBody.cs | 2 +- .../Models/OpenApiResponse.cs | 6 +++--- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 2 +- 10 files changed, 23 insertions(+), 23 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 1b1b91abe..9a397b1b0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -77,15 +77,15 @@ public OpenApiComponents() { } /// public OpenApiComponents(OpenApiComponents components) { - Schemas = DictionaryCloneHelper.Clone(components.Schemas); - Responses = DictionaryCloneHelper.Clone(components.Responses); - Parameters = DictionaryCloneHelper.Clone(components.Parameters); - Examples = DictionaryCloneHelper.Clone(components.Examples); - RequestBodies = DictionaryCloneHelper.Clone(components.RequestBodies); - Headers = DictionaryCloneHelper.Clone(components.Headers); - SecuritySchemes = DictionaryCloneHelper.Clone(components.SecuritySchemes); - Links = DictionaryCloneHelper.Clone(components.Links); - Callbacks = DictionaryCloneHelper.Clone(components.Callbacks); + Schemas = DictionaryCloneHelper.Clone(components?.Schemas); + Responses = DictionaryCloneHelper.Clone(components?.Responses); + Parameters = DictionaryCloneHelper.Clone(components?.Parameters); + Examples = DictionaryCloneHelper.Clone(components?.Examples); + RequestBodies = DictionaryCloneHelper.Clone(components?.RequestBodies); + Headers = DictionaryCloneHelper.Clone(components?.Headers); + SecuritySchemes = DictionaryCloneHelper.Clone(components?.SecuritySchemes); + Links = DictionaryCloneHelper.Clone(components?.Links); + Callbacks = DictionaryCloneHelper.Clone(components?.Callbacks); Extensions = components?.Extensions != null ? new Dictionary(components.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index 23a45653a..94c8e5888 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -65,11 +65,11 @@ public OpenApiEncoding() {} public OpenApiEncoding(OpenApiEncoding encoding) { ContentType = encoding?.ContentType ?? ContentType; - Headers = DictionaryCloneHelper.Clone(encoding.Headers); + Headers = DictionaryCloneHelper.Clone(encoding?.Headers); Style = encoding?.Style ?? Style; Explode = encoding?.Explode ?? Explode; AllowReserved = encoding?.AllowReserved ?? AllowReserved; - Extensions = DictionaryCloneHelper.Clone(encoding.Extensions); + Extensions = encoding?.Extensions != null ? new Dictionary(encoding.Extensions) : null; } /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 73f63a0ab..b0d15f18a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -69,7 +69,7 @@ public OpenApiExample(OpenApiExample example) Description = example?.Description ?? Description; Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example?.Value); ExternalValue = example?.ExternalValue ?? ExternalValue; - Extensions = DictionaryCloneHelper.Clone(example.Extensions); + Extensions = example?.Extensions != null ? new Dictionary(example.Extensions) : null; ; Reference = example?.Reference != null ? new(example?.Reference) : null; UnresolvedReference = example?.UnresolvedReference ?? UnresolvedReference; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index a2d388a6a..91882aade 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -108,8 +108,8 @@ public OpenApiHeader(OpenApiHeader header) AllowReserved = header?.AllowReserved ?? AllowReserved; Schema = header?.Schema != null ? new(header?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header?.Example); - Examples = DictionaryCloneHelper.Clone(header.Examples); - Content = DictionaryCloneHelper.Clone(header.Content); + Examples = DictionaryCloneHelper.Clone(header?.Examples); + Content = DictionaryCloneHelper.Clone(header?.Content); Extensions = header?.Extensions != null ? new Dictionary(header.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 06ba9a745..a8a0497f4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -56,8 +56,8 @@ public OpenApiMediaType(OpenApiMediaType mediaType) { Schema = mediaType?.Schema != null ? new(mediaType?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType?.Example); - Examples = DictionaryCloneHelper.Clone(mediaType.Examples); - Encoding = DictionaryCloneHelper.Clone(mediaType.Encoding); + Examples = DictionaryCloneHelper.Clone(mediaType?.Examples); + Encoding = DictionaryCloneHelper.Clone(mediaType?.Encoding); Extensions = mediaType?.Extensions != null ? new Dictionary(mediaType.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 99438574c..1491b3aec 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -125,7 +125,7 @@ public OpenApiOperation(OpenApiOperation operation) Parameters = operation?.Parameters != null ? new List(operation.Parameters) : null; RequestBody = new(operation?.RequestBody); Responses = operation?.Responses != null ? new(operation?.Responses) : null; - Callbacks = DictionaryCloneHelper.Clone(operation.Callbacks); + Callbacks = DictionaryCloneHelper.Clone(operation?.Callbacks); Deprecated = operation?.Deprecated ?? Deprecated; Security = operation?.Security != null ? new List(operation.Security) : null; Servers = operation?.Servers != null ? new List(operation.Servers) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 194a68b3f..fdeb4d9f6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -163,7 +163,7 @@ public OpenApiParameter(OpenApiParameter parameter) Explode = parameter?.Explode ?? Explode; AllowReserved = parameter?.AllowReserved ?? AllowReserved; Schema = parameter?.Schema != null ? new(parameter?.Schema) : null; - Examples = DictionaryCloneHelper.Clone(parameter.Examples); + Examples = DictionaryCloneHelper.Clone(parameter?.Examples); Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); Content = DictionaryCloneHelper.Clone(parameter.Content); Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 025422077..10603256c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -62,7 +62,7 @@ public OpenApiRequestBody(OpenApiRequestBody requestBody) Reference = requestBody?.Reference != null ? new(requestBody?.Reference) : null; Description = requestBody?.Description ?? Description; Required = requestBody?.Required ?? Required; - Content = DictionaryCloneHelper.Clone(requestBody.Content); + Content = DictionaryCloneHelper.Clone(requestBody?.Content); Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index 928492da6..958f20f61 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -63,9 +63,9 @@ public OpenApiResponse() {} public OpenApiResponse(OpenApiResponse response) { Description = response?.Description ?? Description; - Headers = DictionaryCloneHelper.Clone(response.Headers); - Content = DictionaryCloneHelper.Clone(response.Content); - Links = DictionaryCloneHelper.Clone(response.Links); + Headers = DictionaryCloneHelper.Clone(response?.Headers); + Content = DictionaryCloneHelper.Clone(response?.Content); + Links = DictionaryCloneHelper.Clone(response?.Links); Extensions = response?.Extensions != null ? new Dictionary(response.Extensions) : null; UnresolvedReference = response?.UnresolvedReference ?? UnresolvedReference; Reference = response?.Reference != null ? new(response?.Reference) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index 05dd67ae1..8f9baed45 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -49,7 +49,7 @@ public OpenApiServer(OpenApiServer server) { Description = server?.Description ?? Description; Url = server?.Url ?? Url; - Variables = DictionaryCloneHelper.Clone(server.Variables); + Variables = DictionaryCloneHelper.Clone(server?.Variables); Extensions = server?.Extensions != null ? new Dictionary(server.Extensions) : null; } From 32d0cd4c2ddd8e0f3fd0f9bdb822ff9ce0215928 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 6 Apr 2023 17:11:56 +0300 Subject: [PATCH 462/855] Push uncommitted code and clean up code --- .../Helpers/DictionaryCloneHelper.cs | 14 ++++++-------- src/Microsoft.OpenApi/Models/OpenApiExample.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 2 +- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs index a1976bd70..279e4639d 100644 --- a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs +++ b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs @@ -21,16 +21,14 @@ internal class DictionaryCloneHelper internal static Dictionary Clone(IDictionary dictionary) { if (dictionary is null) return null; - var clonedDictionary = new Dictionary(); - - if (dictionary != null) + var clonedDictionary = new Dictionary(dictionary.Keys.Count); + + foreach (var kvp in dictionary) { - foreach (var kvp in dictionary) - { - // Create instance of the specified type using the constructor matching the specified parameter types. - clonedDictionary[kvp.Key] = (U)Activator.CreateInstance(kvp.Value.GetType(), kvp.Value); - } + // Create instance of the specified type using the constructor matching the specified parameter types. + clonedDictionary[kvp.Key] = (U)Activator.CreateInstance(kvp.Value.GetType(), kvp.Value); } + return clonedDictionary; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index b0d15f18a..d8ac064c0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -69,7 +69,7 @@ public OpenApiExample(OpenApiExample example) Description = example?.Description ?? Description; Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example?.Value); ExternalValue = example?.ExternalValue ?? ExternalValue; - Extensions = example?.Extensions != null ? new Dictionary(example.Extensions) : null; ; + Extensions = example?.Extensions != null ? new Dictionary(example.Extensions) : null; Reference = example?.Reference != null ? new(example?.Reference) : null; UnresolvedReference = example?.UnresolvedReference ?? UnresolvedReference; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index fdeb4d9f6..64dda5445 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -165,7 +165,7 @@ public OpenApiParameter(OpenApiParameter parameter) Schema = parameter?.Schema != null ? new(parameter?.Schema) : null; Examples = DictionaryCloneHelper.Clone(parameter?.Examples); Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); - Content = DictionaryCloneHelper.Clone(parameter.Content); + Content = DictionaryCloneHelper.Clone(parameter?.Content); Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; AllowEmptyValue = parameter?.AllowEmptyValue ?? AllowEmptyValue; Deprecated = parameter?.Deprecated ?? Deprecated; diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 1843c90ff..0b1722bc4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -277,7 +277,7 @@ public OpenApiSchema(OpenApiSchema schema) MaxItems = schema?.MaxItems ?? MaxItems; MinItems = schema?.MinItems ?? MinItems; UniqueItems = schema?.UniqueItems ?? UniqueItems; - Properties = DictionaryCloneHelper.Clone(schema.Properties); + Properties = DictionaryCloneHelper.Clone(schema?.Properties); MaxProperties = schema?.MaxProperties ?? MaxProperties; MinProperties = schema?.MinProperties ?? MinProperties; AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? AdditionalPropertiesAllowed; From 1a9e58cc5b26c6d9863ec12db5775958e44fd726 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 6 Apr 2023 17:24:30 +0300 Subject: [PATCH 463/855] Clean up public API surface --- .../PublicApi/PublicApi.approved.txt | 8 -------- 1 file changed, 8 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index df9ef4393..63cd0f535 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -292,14 +292,6 @@ namespace Microsoft.OpenApi.Extensions public static T GetEnumFromDisplayName(this string displayName) { } } } -namespace Microsoft.OpenApi.Helpers -{ - public class DictionaryCloneHelper - { - public DictionaryCloneHelper() { } - public static System.Collections.Generic.Dictionary Clone(System.Collections.Generic.IDictionary dictionary) { } - } -} namespace Microsoft.OpenApi.Interfaces { public interface IEffective From fde82b81db58b778b3eda60e54d2dea404aa3070 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 6 Apr 2023 16:46:29 -0400 Subject: [PATCH 464/855] - makes Path of OpenApiUrlTreeNode Writeable Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 2 +- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index e73151943..69597d978 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.4-preview1 + 1.6.4-preview2 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 86f49db98..c996acbaf 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.4-preview1 + 1.6.4-preview2 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index c8e2da03f..9f4ccb8be 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -26,7 +26,7 @@ public class OpenApiUrlTreeNode /// /// The relative directory path of the current node from the root node. /// - public string Path { get; private set; } = ""; + public string Path { get; set; } = ""; /// /// Dictionary of labels and Path Item objects that describe the operations available on a node. diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 63cd0f535..d993a259e 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1111,7 +1111,7 @@ namespace Microsoft.OpenApi.Services public System.Collections.Generic.IDictionary> AdditionalData { get; set; } public System.Collections.Generic.IDictionary Children { get; } public bool IsParameter { get; } - public string Path { get; } + public string Path { get; set; } public System.Collections.Generic.IDictionary PathItems { get; } public string Segment { get; } public void AddAdditionalData(System.Collections.Generic.Dictionary> additionalData) { } From 2c21e3ef7b97847a4a4f4decdd56ed545c1ade96 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Apr 2023 21:57:09 +0000 Subject: [PATCH 465/855] Bump Verify.Xunit from 19.12.0 to 19.12.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.12.0 to 19.12.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.12.0...19.12.1) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index fb7ee1bd6..89c2bacf2 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From acf67415b8d5faeec5b0d9934c22d0de9e773dd1 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 11 Apr 2023 11:08:15 -0400 Subject: [PATCH 466/855] - fixes a bug where the base path would be forcibly set to the description --- .../V2/OpenApiDocumentDeserializer.cs | 6 ++++ .../V2Tests/OpenApiServerTests.cs | 29 +++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 02e868412..fa3aa7224 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -139,6 +139,12 @@ private static void MakeServers(IList servers, ParsingContext con var schemes = context.GetFromTempStorage>("schemes"); Uri defaultUrl = rootNode.Context.BaseUrl; + // so we don't default to the document path when a host is provided + if (string.IsNullOrEmpty(basePath) && !string.IsNullOrEmpty(host)) + { + basePath = "/"; + } + // If nothing is provided, don't create a server if (host == null && basePath == null && schemes == null) { diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs index c87b491ab..1b917fde7 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs @@ -74,6 +74,31 @@ public void JustHostNoDefault() Assert.Equal("//www.foo.com", server.Url); } + [Fact] + public void NoBasePath() + { + var input = @" +swagger: 2.0 +info: + title: test + version: 1.0.0 +host: www.foo.com +schemes: + - http +paths: {} +"; + var reader = new OpenApiStringReader(new OpenApiReaderSettings() + { + BaseUrl = new Uri("https://www.foo.com/spec.yaml") + }); + + var doc = reader.Read(input, out var diagnostic); + + var server = doc.Servers.First(); + Assert.Equal(1, doc.Servers.Count); + Assert.Equal("http://www.foo.com", server.Url); + } + [Fact] public void JustBasePathNoDefault() { @@ -203,14 +228,14 @@ public void JustHostWithCustomHostWithApi() "; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { - BaseUrl = new Uri("https://dev.bing.com/api") + BaseUrl = new Uri("https://dev.bing.com/api/description.yaml") }); var doc = reader.Read(input, out var diagnostic); var server = doc.Servers.First(); Assert.Equal(1, doc.Servers.Count); - Assert.Equal("https://prod.bing.com/api", server.Url); + Assert.Equal("https://prod.bing.com", server.Url); } [Fact] From d6fbdacdef9425074a10e2fdb7b79a0d8556b367 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 11 Apr 2023 21:57:16 +0000 Subject: [PATCH 467/855] Bump Microsoft.Windows.Compatibility from 7.0.0 to 7.0.1 Bumps [Microsoft.Windows.Compatibility](https://github.com/dotnet/runtime) from 7.0.0 to 7.0.1. - [Release notes](https://github.com/dotnet/runtime/releases) - [Commits](https://github.com/dotnet/runtime/compare/v7.0.0...v7.0.1) --- updated-dependencies: - dependency-name: Microsoft.Windows.Compatibility dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index c7ab75af4..88f12fcb9 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -1,4 +1,4 @@ - + net7.0-windows WinExe @@ -10,7 +10,7 @@ all - + From b5cfd7ecb7b8e6c8ecda60982a59c1fc29960f13 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 12 Apr 2023 12:09:03 +0300 Subject: [PATCH 468/855] Store already cloned objects in a dictionary to avoid circular dependency during cloning --- .../Helpers/DictionaryCloneHelper.cs | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs index 279e4639d..a87765896 100644 --- a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs +++ b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs @@ -21,14 +21,26 @@ internal class DictionaryCloneHelper internal static Dictionary Clone(IDictionary dictionary) { if (dictionary is null) return null; + var clonedDictionary = new Dictionary(dictionary.Keys.Count); + var clonedObjects = new Dictionary(); - foreach (var kvp in dictionary) + foreach (var keyValuePair in dictionary) { - // Create instance of the specified type using the constructor matching the specified parameter types. - clonedDictionary[kvp.Key] = (U)Activator.CreateInstance(kvp.Value.GetType(), kvp.Value); - } - + // If the object has already been cloned, use the cloned object instead of cloning it again + if (clonedObjects.TryGetValue(keyValuePair.Value, out var clonedValue)) + { + clonedDictionary[keyValuePair.Key] = (U)clonedValue; + } + else + { + // Create instance of the specified type using the constructor matching the specified parameter types. + clonedDictionary[keyValuePair.Key] = (U)Activator.CreateInstance(keyValuePair.Value.GetType(), keyValuePair.Value); + + // Add the cloned object to the dictionary of cloned objects + clonedObjects.Add(keyValuePair.Value, clonedDictionary[keyValuePair.Key]); + } + } return clonedDictionary; } From e739083b7f975ef603eab17f7b36f2262d310803 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 12 Apr 2023 12:25:52 +0300 Subject: [PATCH 469/855] Adds a static class modifier --- src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs index a87765896..1af7bc8c4 100644 --- a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs +++ b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs @@ -9,7 +9,7 @@ namespace Microsoft.OpenApi.Helpers /// /// Helper class for deep cloning dictionaries. /// - internal class DictionaryCloneHelper + internal static class DictionaryCloneHelper { /// /// Deep clone key value pairs in a dictionary. From 178bb469ca3ea509142ac9c24d17bf3afc25a597 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 12 Apr 2023 15:40:30 +0300 Subject: [PATCH 470/855] Bump lib versions --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 69597d978..b3c482215 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.4-preview2 + 1.6.4-preview3 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index c996acbaf..4a291f120 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.4-preview2 + 1.6.4-preview3 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From e3312eabf418caeff9a143ab95911b75efe6c9fb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 13 Apr 2023 21:57:27 +0000 Subject: [PATCH 471/855] Bump Microsoft.OpenApi.OData from 1.4.0-preview1 to 1.4.0-preview2 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.4.0-preview1 to 1.4.0-preview2. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 092c782a7..aad865a3a 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -1,4 +1,4 @@ - + Exe @@ -43,7 +43,7 @@ - + From 4e406ceaa6755d640bbebae934ef485455c9ea8a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 13 Apr 2023 21:57:34 +0000 Subject: [PATCH 472/855] Bump Verify.Xunit from 19.12.1 to 19.12.2 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.12.1 to 19.12.2. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.12.1...19.12.2) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 89c2bacf2..5a177d8f0 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From d940bf627bf368733b558dab088f32e3c7c82306 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 17 Apr 2023 11:34:23 +0300 Subject: [PATCH 473/855] Revert dictionary clone helper logic in the copy constructors to unblock kiota --- .../Any/OpenApiAnyCloneHelper.cs | 5 ++- .../Helpers/DictionaryCloneHelper.cs | 12 +++--- .../Microsoft.OpenApi.csproj | 3 ++ .../Models/OpenApiComponents.cs | 18 ++++----- .../Models/OpenApiEncoding.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 4 +- .../Models/OpenApiMediaType.cs | 4 +- .../Models/OpenApiOperation.cs | 2 +- .../Models/OpenApiParameter.cs | 4 +- .../Models/OpenApiPathItem.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiPaths.cs | 2 +- .../Models/OpenApiRequestBody.cs | 2 +- .../Models/OpenApiResponse.cs | 6 +-- .../Models/OpenApiResponses.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 2 +- .../Models/OpenApiDocumentTests.cs | 40 +++++++++---------- 17 files changed, 59 insertions(+), 53 deletions(-) diff --git a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs index 4a67e074e..8e75c9d39 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs @@ -2,6 +2,9 @@ // Licensed under the MIT license. using System.Reflection; +using Microsoft.OpenApi.Helpers; +using System.Text.Json.Serialization; +using System.Text.Json; namespace Microsoft.OpenApi.Any { @@ -27,7 +30,7 @@ public static IOpenApiAny CloneFromCopyConstructor(IOpenApiAny obj) { return (IOpenApiAny)ci.Invoke(new object[] { obj }); } - } + } } return obj; diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs index 1af7bc8c4..ef349a477 100644 --- a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs +++ b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs @@ -19,12 +19,12 @@ internal static class DictionaryCloneHelper /// The target dictionary to clone. /// The cloned dictionary. internal static Dictionary Clone(IDictionary dictionary) - { + { if (dictionary is null) return null; - + var clonedDictionary = new Dictionary(dictionary.Keys.Count); var clonedObjects = new Dictionary(); - + foreach (var keyValuePair in dictionary) { // If the object has already been cloned, use the cloned object instead of cloning it again @@ -36,11 +36,11 @@ internal static Dictionary Clone(IDictionary dictionary) { // Create instance of the specified type using the constructor matching the specified parameter types. clonedDictionary[keyValuePair.Key] = (U)Activator.CreateInstance(keyValuePair.Value.GetType(), keyValuePair.Value); - + // Add the cloned object to the dictionary of cloned objects clonedObjects.Add(keyValuePair.Value, clonedDictionary[keyValuePair.Key]); - } - } + } + } return clonedDictionary; } diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 4a291f120..ba72031e6 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -33,6 +33,9 @@ true + + + diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 9a397b1b0..b8877eeff 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -77,15 +77,15 @@ public OpenApiComponents() { } /// public OpenApiComponents(OpenApiComponents components) { - Schemas = DictionaryCloneHelper.Clone(components?.Schemas); - Responses = DictionaryCloneHelper.Clone(components?.Responses); - Parameters = DictionaryCloneHelper.Clone(components?.Parameters); - Examples = DictionaryCloneHelper.Clone(components?.Examples); - RequestBodies = DictionaryCloneHelper.Clone(components?.RequestBodies); - Headers = DictionaryCloneHelper.Clone(components?.Headers); - SecuritySchemes = DictionaryCloneHelper.Clone(components?.SecuritySchemes); - Links = DictionaryCloneHelper.Clone(components?.Links); - Callbacks = DictionaryCloneHelper.Clone(components?.Callbacks); + Schemas = components?.Schemas != null ? new Dictionary(components.Schemas) : null; + Responses = components?.Responses != null ? new Dictionary(components.Responses) : null; + Parameters = components?.Parameters != null ? new Dictionary(components.Parameters) : null; + Examples = components?.Examples != null ? new Dictionary(components.Examples) : null; + RequestBodies = components?.RequestBodies != null ? new Dictionary(components.RequestBodies) : null; + Headers = components?.Headers != null ? new Dictionary(components.Headers) : null; + SecuritySchemes = components?.SecuritySchemes != null ? new Dictionary(components.SecuritySchemes) : null; + Links = components?.Links != null ? new Dictionary(components.Links) : null; + Callbacks = components?.Callbacks != null ? new Dictionary(components.Callbacks) : null; Extensions = components?.Extensions != null ? new Dictionary(components.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index 94c8e5888..e039a04ee 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -65,7 +65,7 @@ public OpenApiEncoding() {} public OpenApiEncoding(OpenApiEncoding encoding) { ContentType = encoding?.ContentType ?? ContentType; - Headers = DictionaryCloneHelper.Clone(encoding?.Headers); + Headers = encoding?.Headers != null ? new Dictionary(encoding.Headers) : null; Style = encoding?.Style ?? Style; Explode = encoding?.Explode ?? Explode; AllowReserved = encoding?.AllowReserved ?? AllowReserved; diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index 91882aade..359c1c70c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -108,8 +108,8 @@ public OpenApiHeader(OpenApiHeader header) AllowReserved = header?.AllowReserved ?? AllowReserved; Schema = header?.Schema != null ? new(header?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header?.Example); - Examples = DictionaryCloneHelper.Clone(header?.Examples); - Content = DictionaryCloneHelper.Clone(header?.Content); + Examples = header?.Examples != null ? new Dictionary(header.Examples) : null; + Content = header?.Content != null ? new Dictionary(header.Content) : null; Extensions = header?.Extensions != null ? new Dictionary(header.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index a8a0497f4..276cc3807 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -56,8 +56,8 @@ public OpenApiMediaType(OpenApiMediaType mediaType) { Schema = mediaType?.Schema != null ? new(mediaType?.Schema) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType?.Example); - Examples = DictionaryCloneHelper.Clone(mediaType?.Examples); - Encoding = DictionaryCloneHelper.Clone(mediaType?.Encoding); + Examples = mediaType?.Examples != null ? new Dictionary(mediaType.Examples) : null; + Encoding = mediaType?.Encoding != null ? new Dictionary(mediaType.Encoding) : null; Extensions = mediaType?.Extensions != null ? new Dictionary(mediaType.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 526e4c7ca..a1c4da652 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -125,7 +125,7 @@ public OpenApiOperation(OpenApiOperation operation) Parameters = operation?.Parameters != null ? new List(operation.Parameters) : null; RequestBody = operation?.RequestBody != null ? new(operation?.RequestBody) : null; Responses = operation?.Responses != null ? new(operation?.Responses) : null; - Callbacks = DictionaryCloneHelper.Clone(operation?.Callbacks); + Callbacks = operation?.Callbacks != null ? new Dictionary(operation.Callbacks) : null; Deprecated = operation?.Deprecated ?? Deprecated; Security = operation?.Security != null ? new List(operation.Security) : null; Servers = operation?.Servers != null ? new List(operation.Servers) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index e140e1f35..6c926de88 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -163,9 +163,9 @@ public OpenApiParameter(OpenApiParameter parameter) Explode = parameter?.Explode ?? Explode; AllowReserved = parameter?.AllowReserved ?? AllowReserved; Schema = parameter?.Schema != null ? new(parameter?.Schema) : null; - Examples = DictionaryCloneHelper.Clone(parameter?.Examples); + Examples = parameter?.Examples != null ? new Dictionary(parameter.Examples) : null; Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); - Content = DictionaryCloneHelper.Clone(parameter?.Content); + Content = parameter?.Content != null ? new Dictionary(parameter.Content) : null; Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; AllowEmptyValue = parameter?.AllowEmptyValue ?? AllowEmptyValue; Deprecated = parameter?.Deprecated ?? Deprecated; diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index a669c67bc..86ed5c4b0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -79,7 +79,7 @@ public OpenApiPathItem(OpenApiPathItem pathItem) { Summary = pathItem?.Summary ?? Summary; Description = pathItem?.Description ?? Description; - Operations = DictionaryCloneHelper.Clone(pathItem?.Operations); + Operations = pathItem?.Operations != null ? new Dictionary(pathItem.Operations) : null; Servers = pathItem?.Servers != null ? new List(pathItem.Servers) : null; Parameters = pathItem?.Parameters != null ? new List(pathItem.Parameters) : null; Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem.Extensions) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs index 53f56c5ad..e73579eaf 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs @@ -22,6 +22,6 @@ public OpenApiPaths() {} /// Initializes a copy of object /// /// The . - public OpenApiPaths(OpenApiPaths paths) : base(DictionaryCloneHelper.Clone(paths)) { } + public OpenApiPaths(OpenApiPaths paths) : base(dictionary: paths) { } } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 10603256c..e6abf5d5c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -62,7 +62,7 @@ public OpenApiRequestBody(OpenApiRequestBody requestBody) Reference = requestBody?.Reference != null ? new(requestBody?.Reference) : null; Description = requestBody?.Description ?? Description; Required = requestBody?.Required ?? Required; - Content = DictionaryCloneHelper.Clone(requestBody?.Content); + Content = requestBody?.Content != null ? new Dictionary(requestBody.Content) : null; Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody.Extensions) : null; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index 958f20f61..a48b14163 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -63,9 +63,9 @@ public OpenApiResponse() {} public OpenApiResponse(OpenApiResponse response) { Description = response?.Description ?? Description; - Headers = DictionaryCloneHelper.Clone(response?.Headers); - Content = DictionaryCloneHelper.Clone(response?.Content); - Links = DictionaryCloneHelper.Clone(response?.Links); + Headers = response?.Headers != null ? new Dictionary(response.Headers) : null; + Content = response?.Content != null ? new Dictionary(response.Content) : null; + Links = response?.Links != null ? new Dictionary(response.Links) : null; Extensions = response?.Extensions != null ? new Dictionary(response.Extensions) : null; UnresolvedReference = response?.UnresolvedReference ?? UnresolvedReference; Reference = response?.Reference != null ? new(response?.Reference) : null; diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs index 86b484408..b6f3d71d7 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs @@ -19,6 +19,6 @@ public OpenApiResponses() { } /// Initializes a copy of object /// /// The - public OpenApiResponses(OpenApiResponses openApiResponses) : base(DictionaryCloneHelper.Clone(openApiResponses)) {} + public OpenApiResponses(OpenApiResponses openApiResponses) : base(dictionary: openApiResponses) {} } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 0b1722bc4..050c6d4bf 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -277,7 +277,7 @@ public OpenApiSchema(OpenApiSchema schema) MaxItems = schema?.MaxItems ?? MaxItems; MinItems = schema?.MinItems ?? MinItems; UniqueItems = schema?.UniqueItems ?? UniqueItems; - Properties = DictionaryCloneHelper.Clone(schema?.Properties); + Properties = schema?.Properties != null ? new Dictionary(schema.Properties) : null; MaxProperties = schema?.MaxProperties ?? MaxProperties; MinProperties = schema?.MinProperties ?? MinProperties; AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? AdditionalPropertiesAllowed; diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index 8f9baed45..94119bc24 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -49,7 +49,7 @@ public OpenApiServer(OpenApiServer server) { Description = server?.Description ?? Description; Url = server?.Url ?? Url; - Variables = DictionaryCloneHelper.Clone(server?.Variables); + Variables = server?.Variables != null ? new Dictionary(server.Variables) : null; Extensions = server?.Extensions != null ? new Dictionary(server.Extensions) : null; } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index ceed06bb9..6e3200957 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1339,26 +1339,26 @@ private static OpenApiDocument ParseInputFile(string filePath) return openApiDoc; } - [Fact] - public void CopyConstructorForAdvancedDocumentWorks() - { - // Arrange & Act - var doc = new OpenApiDocument(AdvancedDocument); - - var docOpId = doc.Paths["/pets"].Operations[OperationType.Get].OperationId = "findAllMyPets"; - var advancedDocOpId = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].OperationId; - var responseSchemaTypeCopy = doc.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema.Type = "object"; - var advancedDocResponseSchemaType = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema.Type; - - // Assert - Assert.NotNull(doc.Info); - Assert.NotNull(doc.Servers); - Assert.NotNull(doc.Paths); - Assert.Equal(2, doc.Paths.Count); - Assert.NotNull(doc.Components); - Assert.NotEqual(docOpId, advancedDocOpId); - Assert.NotEqual(responseSchemaTypeCopy, advancedDocResponseSchemaType); - } + //[Fact] + //public void CopyConstructorForAdvancedDocumentWorks() + //{ + // // Arrange & Act + // var doc = new OpenApiDocument(AdvancedDocument); + + // var docOpId = doc.Paths["/pets"].Operations[OperationType.Get].OperationId = "findAllMyPets"; + // var advancedDocOpId = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].OperationId; + // var responseSchemaTypeCopy = doc.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema.Type = "object"; + // var advancedDocResponseSchemaType = AdvancedDocument.Paths["/pets"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema.Type; + + // // Assert + // Assert.NotNull(doc.Info); + // Assert.NotNull(doc.Servers); + // Assert.NotNull(doc.Paths); + // Assert.Equal(2, doc.Paths.Count); + // Assert.NotNull(doc.Components); + // Assert.NotEqual(docOpId, advancedDocOpId); + // Assert.NotEqual(responseSchemaTypeCopy, advancedDocResponseSchemaType); + //} [Fact] public void SerializeV2DocumentWithNonArraySchemaTypeDoesNotWriteOutCollectionFormat() From a66db83a210ecc4915e430cda066bee14fe5159f Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 17 Apr 2023 09:01:50 -0400 Subject: [PATCH 474/855] - removes unused file --- .../Helpers/DictionaryCloneHelper.cs | 48 ------------------- 1 file changed, 48 deletions(-) delete mode 100644 src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs diff --git a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs b/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs deleted file mode 100644 index ef349a477..000000000 --- a/src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Collections.Generic; - -namespace Microsoft.OpenApi.Helpers -{ - /// - /// Helper class for deep cloning dictionaries. - /// - internal static class DictionaryCloneHelper - { - /// - /// Deep clone key value pairs in a dictionary. - /// - /// The type of the key of the dictionary. - /// The type of the value of the dictionary. - /// The target dictionary to clone. - /// The cloned dictionary. - internal static Dictionary Clone(IDictionary dictionary) - { - if (dictionary is null) return null; - - var clonedDictionary = new Dictionary(dictionary.Keys.Count); - var clonedObjects = new Dictionary(); - - foreach (var keyValuePair in dictionary) - { - // If the object has already been cloned, use the cloned object instead of cloning it again - if (clonedObjects.TryGetValue(keyValuePair.Value, out var clonedValue)) - { - clonedDictionary[keyValuePair.Key] = (U)clonedValue; - } - else - { - // Create instance of the specified type using the constructor matching the specified parameter types. - clonedDictionary[keyValuePair.Key] = (U)Activator.CreateInstance(keyValuePair.Value.GetType(), keyValuePair.Value); - - // Add the cloned object to the dictionary of cloned objects - clonedObjects.Add(keyValuePair.Value, clonedDictionary[keyValuePair.Key]); - } - } - - return clonedDictionary; - } - } -} From 542a0341eacb61d6d610c13e7054575190d692ab Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 17 Apr 2023 16:10:43 +0300 Subject: [PATCH 475/855] Remove unnecessary usings --- src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs | 3 --- src/Microsoft.OpenApi/Models/OpenApiCallback.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiComponents.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiEncoding.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiExample.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiMediaType.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiPathItem.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiPaths.cs | 5 ----- src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiResponse.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiResponses.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiServer.cs | 2 -- 16 files changed, 28 deletions(-) diff --git a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs index 8e75c9d39..5e499ccac 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs @@ -2,9 +2,6 @@ // Licensed under the MIT license. using System.Reflection; -using Microsoft.OpenApi.Helpers; -using System.Text.Json.Serialization; -using System.Text.Json; namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index b25ed8578..e6aa5d075 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -2,9 +2,7 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Expressions; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index b8877eeff..a6bfef594 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 2bf5dd2f2..5177e4f45 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -8,7 +8,6 @@ using System.Security.Cryptography; using System.Text; using Microsoft.OpenApi.Exceptions; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index e039a04ee..13b6e3a0a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -2,9 +2,7 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index d8ac064c0..4d091a361 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index 359c1c70c..fb4411478 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 276cc3807..63a58cd02 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 6c926de88..2efd0c747 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -3,10 +3,8 @@ using System; using System.Collections.Generic; -using System.Runtime; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index 86ed5c4b0..ddd358dc2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -1,10 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs index e73579eaf..8aae74883 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs @@ -1,11 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; -using System.Collections; -using System.Collections.Generic; -using Microsoft.OpenApi.Helpers; - namespace Microsoft.OpenApi.Models { /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index e6abf5d5c..70f1f742a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index a48b14163..a173f6c1a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs index b6f3d71d7..aa7a8c984 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using Microsoft.OpenApi.Helpers; - namespace Microsoft.OpenApi.Models { /// diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 050c6d4bf..0176ea1d9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index 94119bc24..a13a6fb2d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -2,8 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; From 6eac7c0211f2b01331d90018475bed9d5966b09d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 17 Apr 2023 16:24:29 +0300 Subject: [PATCH 476/855] Remove unnecesary using; bump lib versions --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- src/Microsoft.OpenApi/Models/OpenApiOperation.cs | 2 -- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index b3c482215..9651dd6d7 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.4-preview3 + 1.6.4-preview4 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index ba72031e6..3a72d738e 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.4-preview3 + 1.6.4-preview4 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index a1c4da652..9336662d8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Helpers; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; From 67245931a3e438de296842740180956166a0f6eb Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Mon, 17 Apr 2023 16:27:00 +0300 Subject: [PATCH 477/855] clean up --- src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs index 5e499ccac..e34fb8cbf 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs @@ -29,7 +29,7 @@ public static IOpenApiAny CloneFromCopyConstructor(IOpenApiAny obj) } } } - + return obj; } } diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 3a72d738e..00d336626 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -33,9 +33,6 @@ true - - - From eacfd8ade5395a1c1eed3a0def048ef2cf6fbe8b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Apr 2023 21:57:29 +0000 Subject: [PATCH 478/855] Bump Microsoft.OpenApi.OData from 1.4.0-preview2 to 1.4.0-preview3 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.4.0-preview2 to 1.4.0-preview3. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index aad865a3a..0986f3216 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 27b81b94629236752651042f8de428b2ae66a4ec Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Apr 2023 21:57:35 +0000 Subject: [PATCH 479/855] Bump Verify.Xunit from 19.12.2 to 19.12.3 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.12.2 to 19.12.3. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.12.2...19.12.3) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 5a177d8f0..cd07a777b 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 3dc4536a68d74f62817dfd8affd9ffdfcc5dfe22 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 18 Apr 2023 21:57:10 +0000 Subject: [PATCH 480/855] Bump Microsoft.OpenApi.OData from 1.4.0-preview3 to 1.4.0-preview4 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.4.0-preview3 to 1.4.0-preview4. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 0986f3216..19ea9a867 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 04b357c083715afff893af2a08d922058838dcd1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 20 Apr 2023 21:57:09 +0000 Subject: [PATCH 481/855] Bump Microsoft.OpenApi.OData from 1.4.0-preview4 to 1.4.0-preview5 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.4.0-preview4 to 1.4.0-preview5. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 19ea9a867..e131a5021 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 38aa759f0c00b68c0aa55a3b1e4cf8bf262f0815 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 20 Apr 2023 21:57:14 +0000 Subject: [PATCH 482/855] Bump Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers Bumps [Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers](https://github.com/dotnet/upgrade-assistant) from 0.4.410601 to 0.4.421302. - [Release notes](https://github.com/dotnet/upgrade-assistant/releases) - [Changelog](https://github.com/dotnet/upgrade-assistant/blob/main/CHANGELOG.md) - [Commits](https://github.com/dotnet/upgrade-assistant/commits) --- updated-dependencies: - dependency-name: Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Workbench.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index 88f12fcb9..d6ae3260e 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -7,7 +7,7 @@ true - + all From 8d71459b1eb5f0fb8b5cc78f588b3842f1307917 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 20 Apr 2023 21:57:20 +0000 Subject: [PATCH 483/855] Bump FluentAssertions from 6.10.0 to 6.11.0 Bumps [FluentAssertions](https://github.com/fluentassertions/fluentassertions) from 6.10.0 to 6.11.0. - [Release notes](https://github.com/fluentassertions/fluentassertions/releases) - [Changelog](https://github.com/fluentassertions/fluentassertions/blob/develop/AcceptApiChanges.ps1) - [Commits](https://github.com/fluentassertions/fluentassertions/compare/6.10.0...6.11.0) --- updated-dependencies: - dependency-name: FluentAssertions dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index ded741223..bde45294c 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -265,7 +265,7 @@ all - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index cd07a777b..3bf21a492 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -23,7 +23,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + From 798fc08a2d1c8a0f5b5bd3211b035bdae9ce4749 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Apr 2023 21:12:10 +0000 Subject: [PATCH 484/855] Bump Verify.Xunit from 19.12.3 to 19.13.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.12.3 to 19.13.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 3bf21a492..49bd7631f 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 408eed77572094487ae8193fb67f0a812db9a6fa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 27 Apr 2023 21:57:07 +0000 Subject: [PATCH 485/855] Bump Microsoft.OpenApi.OData from 1.4.0-preview5 to 1.4.0-preview6 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.4.0-preview5 to 1.4.0-preview6. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index e131a5021..2cf28b26a 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 4acf416d6f1ca212894fb36979db3fe07d7cdb24 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 27 Apr 2023 21:57:12 +0000 Subject: [PATCH 486/855] Bump Verify.Xunit from 19.13.0 to 19.13.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.13.0 to 19.13.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits/19.13.1) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 49bd7631f..2dcf347ba 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From ae0c151e2de71b6bdc56688779df334fecd822ee Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 2 May 2023 21:57:12 +0000 Subject: [PATCH 487/855] Bump Microsoft.OpenApi.OData from 1.4.0-preview6 to 1.4.0-preview7 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.4.0-preview6 to 1.4.0-preview7. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 2cf28b26a..77a215d96 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -43,7 +43,7 @@ - + From 316c365db351f3100b6dd5a2e8a3da91fe8f8b14 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 2 May 2023 21:57:18 +0000 Subject: [PATCH 488/855] Bump Verify.Xunit from 19.13.1 to 19.14.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 19.13.1 to 19.14.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/19.13.1...19.14.1) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 2dcf347ba..36369938b 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 79a773db70d63982a048e087041ba0181ca90e16 Mon Sep 17 00:00:00 2001 From: Irvine Sunday Date: Wed, 3 May 2023 10:16:12 +0300 Subject: [PATCH 489/855] Bump up lib. version --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 77a215d96..e370c84bb 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -15,7 +15,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.2.5-preview2 + 1.2.5-preview3 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET @@ -43,7 +43,7 @@ - + From 28b44e6fe8701cbcf2eba450846140ee8f8dc66a Mon Sep 17 00:00:00 2001 From: Eastman Date: Wed, 3 May 2023 10:22:16 +0300 Subject: [PATCH 490/855] Update CODEOWNERS --- .github/CODEOWNERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 7cb46ae19..e55e35b9a 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1 @@ -* @irvinesunday @darrelmiller @peombwa @zengin @baywet @millicentachieng @MaggieKimani1 +* @irvinesunday @darrelmiller @peombwa @zengin @baywet @millicentachieng @MaggieKimani1 @andrueastman From 8b7d1c8e3870234e4e8bf6ba2557260e53005255 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 3 May 2023 13:22:35 +0300 Subject: [PATCH 491/855] Update README.md with guidelines on using workbench tool --- README.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/README.md b/README.md index 0190e572d..baf262999 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ |--|--| |Models and Writers|[![nuget](https://img.shields.io/nuget/v/Microsoft.OpenApi.svg)](https://www.nuget.org/packages/Microsoft.OpenApi/) | |Readers | [![nuget](https://img.shields.io/nuget/v/Microsoft.OpenApi.Readers.svg)](https://www.nuget.org/packages/Microsoft.OpenApi.Readers/) | +|Hidi|[![nuget](https://img.shields.io/nuget/v/Microsoft.OpenApi.Hidi.svg)](https://www.nuget.org/packages/Microsoft.OpenApi.Hidi/) The **OpenAPI.NET** SDK contains a useful object model for OpenAPI documents in .NET along with common serializers to extract raw OpenAPI JSON and YAML documents from the model. @@ -90,6 +91,28 @@ var outputString = openApiDocument.Serialize(OpenApiSpecVersion.OpenApi2_0, Open ``` +# Validating/Testing OpenApi descriptions +In order to test the validity of an OpenApi document, we avail the following tools: +- [Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenApi.Hidi) + + A commandline tool for validating and transforming OpenApi descriptions. [Installation guidelines and documentation](https://github.com/microsoft/OpenAPI.NET/blob/vnext/src/Microsoft.OpenApi.Hidi/readme.md) + +- Microsoft.OpenApi.Workbench + + A workbench tool consisting of a GUI where you can test and convert OpenApi descriptions in both Json and Yaml from v2-->v3 and vice versa. + + #### Installation guidelines: + 1. Clone the repo locally by running this command: + `git clone https://github.com/microsoft/OpenAPI.NET.git` + 2. Open the solution file `(.sln)` in the root of the project with Visual Studio + 3. Navigate to the `src/Microsoft.OpenApi.Workbench` directory and set it as the startup project + 4. Run the project and you'll see a GUI pop up resembling the one below: + + + + + 5. Copy paste your OpenApi descriptions or paste the path to the descriptions file and click on `convert` to render the results. + # Build Status |**master**| From f80d52e599d3e713a6f08b23ba53d85560abc8b6 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 3 May 2023 15:44:25 +0300 Subject: [PATCH 492/855] Update README.md Co-authored-by: Irvine Sunday <40403681+irvinesunday@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index baf262999..07f4553c9 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ In order to test the validity of an OpenApi document, we avail the following too - 5. Copy paste your OpenApi descriptions or paste the path to the descriptions file and click on `convert` to render the results. + 5. Copy and paste your OpenApi descriptions in the **Input Content** window or paste the path to the descriptions file in the **Input File** textbox and click on `convert` to render the results. # Build Status From 8686088d17d62d62bb530b52e0d6846c080cd795 Mon Sep 17 00:00:00 2001 From: Andrew Omondi Date: Thu, 4 May 2023 16:08:19 +0300 Subject: [PATCH 493/855] Bumps lib versions --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 9651dd6d7..7a1681459 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.4-preview4 + 1.6.4 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 00d336626..bb7e7103f 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.4-preview4 + 1.6.4 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From 998590255ae8c178834ca65eb2516a6cc118ca17 Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Mon, 8 May 2023 16:20:24 -0700 Subject: [PATCH 494/855] Add OpenAPI formatter for PS --- .../Formatters/PowerShellFormatter.cs | 210 ++++++++++++++++++ .../Handlers/TransformCommandHandler.cs | 4 +- .../Microsoft.OpenApi.Hidi.csproj | 1 + src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 69 +++--- src/Microsoft.OpenApi.Hidi/Program.cs | 14 +- .../Services/OpenApiServiceTests.cs | 26 +-- 6 files changed, 272 insertions(+), 52 deletions(-) create mode 100644 src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs diff --git a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs new file mode 100644 index 000000000..df8fbb948 --- /dev/null +++ b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using Humanizer; +using Humanizer.Inflections; +using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Services; + +namespace Microsoft.OpenApi.Hidi.Formatters +{ + internal class PowerShellFormatter : OpenApiVisitorBase + { + private const string DefaultPutPrefix = ".Update"; + private const string PowerShellPutPrefix = ".Set"; + private readonly Stack _schemaLoop = new(); + private static readonly Regex s_oDataCastRegex = new("(.*(?<=[a-z]))\\.(As(?=[A-Z]).*)", RegexOptions.Compiled, TimeSpan.FromSeconds(5)); + private static readonly Regex s_hashSuffixRegex = new(@"^[^-]+", RegexOptions.Compiled, TimeSpan.FromSeconds(5)); + private static readonly Regex s_oDataRefRegex = new("(?<=[a-z])Ref(?=[A-Z])", RegexOptions.Compiled, TimeSpan.FromSeconds(5)); + + static PowerShellFormatter() + { + // Add singularization exclusions. + // TODO: Read exclusions from a user provided file. + Vocabularies.Default.AddSingular("(drive)s$", "$1"); // drives does not properly singularize to drive. + Vocabularies.Default.AddSingular("(data)$", "$1"); // exclude the following from singularization. + Vocabularies.Default.AddSingular("(delta)$", "$1"); + Vocabularies.Default.AddSingular("(quota)$", "$1"); + Vocabularies.Default.AddSingular("(statistics)$", "$1"); + } + + //TODO: FHL for PS + // Fixes (Order matters): + // 1. Singularize operationId operationIdSegments. + // 2. Add '_' to verb in an operationId. + // 3. Fix odata cast operationIds. + // 4. Fix hash suffix in operationIds. + // 5. Fix Put operation id should have -> {xxx}_Set{Yyy} + // 5. Fix anyOf and oneOf schema. + // 6. Add AdditionalProperties to object schemas. + + public override void Visit(OpenApiSchema schema) + { + AddAddtionalPropertiesToSchema(schema); + ResolveAnyOfSchema(schema); + ResolveOneOfSchema(schema); + + base.Visit(schema); + } + + public override void Visit(OpenApiPathItem pathItem) + { + if (pathItem.Operations.ContainsKey(OperationType.Put)) + { + var operationId = pathItem.Operations[OperationType.Put].OperationId; + pathItem.Operations[OperationType.Put].OperationId = ResolvePutOperationId(operationId); + } + + base.Visit(pathItem); + } + + public override void Visit(OpenApiOperation operation) + { + if (operation.OperationId == null) + throw new ArgumentNullException(nameof(operation.OperationId), $"OperationId is required {PathString}"); + + var operationId = operation.OperationId; + + operationId = RemoveHashSuffix(operationId); + operationId = ResolveODataCastOperationId(operationId); + operationId = ResolveByRefOperationId(operationId); + + + var operationIdSegments = operationId.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + operationId = SingularizeAndDeduplicateOperationId(operationIdSegments); + + operation.OperationId = operationId; + base.Visit(operation); + } + + private void AddAddtionalPropertiesToSchema(OpenApiSchema schema) + { + if (schema != null && !_schemaLoop.Contains(schema) && "object".Equals(schema?.Type, StringComparison.OrdinalIgnoreCase)) + { + schema.AdditionalProperties = new OpenApiSchema() { Type = "object" }; + + /* Because 'additionalProperties' are now being walked, + * we need a way to keep track of visited schemas to avoid + * endlessly creating and walking them in an infinite recursion. + */ + _schemaLoop.Push(schema.AdditionalProperties); + } + } + + private static void ResolveOneOfSchema(OpenApiSchema schema) + { + if (schema.OneOf?.Any() ?? false) + { + var newSchema = schema.OneOf.FirstOrDefault(); + schema.OneOf = null; + FlattenSchema(schema, newSchema); + } + } + + private static void ResolveAnyOfSchema(OpenApiSchema schema) + { + if (schema.AnyOf?.Any() ?? false) + { + var newSchema = schema.AnyOf.FirstOrDefault(); + schema.AnyOf = null; + FlattenSchema(schema, newSchema); + } + } + + private static string ResolvePutOperationId(string operationId) + { + return operationId.Contains(DefaultPutPrefix) ? + operationId.Replace(DefaultPutPrefix, PowerShellPutPrefix) : operationId; + } + + private static string ResolveByRefOperationId(string operationId) + { + // Update $ref path operationId name + // Ref key word is enclosed between lower-cased and upper-cased letters + // Ex.: applications_GetRefCreatedOnBehalfOf to applications_GetCreatedOnBehalfOfByRef + return s_oDataRefRegex.Match(operationId).Success ? $"{s_oDataRefRegex.Replace(operationId, string.Empty)}ByRef" : operationId; + } + + private static string ResolveODataCastOperationId(string operationId) + { + var match = s_oDataCastRegex.Match(operationId); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : operationId; + } + + private static string SingularizeAndDeduplicateOperationId(IList operationIdSegments) + { + var segmentsCount = operationIdSegments.Count; + var lastSegmentIndex = segmentsCount - 1; + var singularizedSegments = new List(); + + for (int x = 0; x < segmentsCount; x++) + { + var segment = operationIdSegments[x].Singularize(inputIsKnownToBePlural: false); + + // If a segment name is contained in the previous segment, the latter is considered a duplicate. + // The last segment is ignored as a rule. + if ((x > 0 && x < lastSegmentIndex) && singularizedSegments.Last().Equals(segment, StringComparison.OrdinalIgnoreCase)) + continue; + + singularizedSegments.Add(segment); + } + return string.Join(".", singularizedSegments); + } + + private static string RemoveHashSuffix(string operationId) + { + // Remove hash suffix values from OperationIds. + return s_hashSuffixRegex.Match(operationId).Value; + } + + private static void FlattenSchema(OpenApiSchema schema, OpenApiSchema newSchema) + { + if (newSchema != null) + { + if (newSchema.Reference != null) + { + schema.Reference = newSchema.Reference; + schema.UnresolvedReference = true; + } + else + { + // Copies schema properties based on https://github.com/microsoft/OpenAPI.NET.OData/pull/264. + CopySchema(schema, newSchema); + } + } + } + + private static void CopySchema(OpenApiSchema schema, OpenApiSchema newSchema) + { + schema.Title ??= newSchema.Title; + schema.Type ??= newSchema.Type; + schema.Format ??= newSchema.Format; + schema.Description ??= newSchema.Description; + schema.Maximum ??= newSchema.Maximum; + schema.ExclusiveMaximum ??= newSchema.ExclusiveMaximum; + schema.Minimum ??= newSchema.Minimum; + schema.ExclusiveMinimum ??= newSchema.ExclusiveMinimum; + schema.MaxLength ??= newSchema.MaxLength; + schema.MinLength ??= newSchema.MinLength; + schema.Pattern ??= newSchema.Pattern; + schema.MultipleOf ??= newSchema.MultipleOf; + schema.Not ??= newSchema.Not; + schema.Required ??= newSchema.Required; + schema.Items ??= newSchema.Items; + schema.MaxItems ??= newSchema.MaxItems; + schema.MinItems ??= newSchema.MinItems; + schema.UniqueItems ??= newSchema.UniqueItems; + schema.Properties ??= newSchema.Properties; + schema.MaxProperties ??= newSchema.MaxProperties; + schema.MinProperties ??= newSchema.MinProperties; + schema.Discriminator ??= newSchema.Discriminator; + schema.ExternalDocs ??= newSchema.ExternalDocs; + schema.Enum ??= newSchema.Enum; + schema.ReadOnly = !schema.ReadOnly ? newSchema.ReadOnly : schema.ReadOnly; + schema.WriteOnly = !schema.WriteOnly ? newSchema.WriteOnly : schema.WriteOnly; + schema.Nullable = !schema.Nullable ? newSchema.Nullable : schema.Nullable; + schema.Deprecated = !schema.Deprecated ? newSchema.Deprecated : schema.Deprecated; + } + } +} diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index e00cd7efa..1c4262ba5 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -29,6 +29,7 @@ internal class TransformCommandHandler : ICommandHandler public Option FilterByCollectionOption { get; set; } public Option InlineLocalOption { get; set; } public Option InlineExternalOption { get; set; } + public Option LanguageFormatOption { get; set; } public int Invoke(InvocationContext context) { @@ -49,6 +50,7 @@ public async Task InvokeAsync(InvocationContext context) LogLevel logLevel = context.ParseResult.GetValueForOption(LogLevelOption); bool inlineLocal = context.ParseResult.GetValueForOption(InlineLocalOption); bool inlineExternal = context.ParseResult.GetValueForOption(InlineExternalOption); + string? languageFormatOption = context.ParseResult.GetValueForOption(LanguageFormatOption); string filterbyoperationids = context.ParseResult.GetValueForOption(FilterByOperationIdsOption); string filterbytags = context.ParseResult.GetValueForOption(FilterByTagsOption); string filterbycollection = context.ParseResult.GetValueForOption(FilterByCollectionOption); @@ -59,7 +61,7 @@ public async Task InvokeAsync(InvocationContext context) var logger = loggerFactory.CreateLogger(); try { - await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, metadataVersion, format, terseOutput, settingsFile, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, logger, cancellationToken); + await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, metadataVersion, format, terseOutput, settingsFile, inlineLocal, inlineExternal, languageFormatOption, filterbyoperationids, filterbytags, filterbycollection, logger, cancellationToken); return 0; } diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index e370c84bb..2cc6ceae6 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -37,6 +37,7 @@ + diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 5d5ec95d4..73d12806c 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -26,6 +26,7 @@ using System.Xml; using System.Reflection; using Microsoft.Extensions.Configuration; +using Microsoft.OpenApi.Hidi.Formatters; namespace Microsoft.OpenApi.Hidi { @@ -47,6 +48,7 @@ public static async Task TransformOpenApiDocument( string settingsFile, bool inlineLocal, bool inlineExternal, + string? languageFormatOption, string filterbyoperationids, string filterbytags, string filterbycollection, @@ -82,6 +84,13 @@ CancellationToken cancellationToken OpenApiDocument document = await GetOpenApi(openapi, csdl, csdlFilter, settingsFile, inlineExternal, logger, cancellationToken, metadataVersion); document = await FilterOpenApiDocument(filterbyoperationids, filterbytags, filterbycollection, document, logger, cancellationToken); + if (!string.IsNullOrWhiteSpace(languageFormatOption) && languageFormatOption.Equals("PowerShell", StringComparison.InvariantCultureIgnoreCase)) + { + // PowerShell Walker. + var powerShellFormatter = new PowerShellFormatter(); + var walker = new OpenApiWalker(powerShellFormatter); + walker.Walk(document); + } WriteOpenApi(output, terseOutput, inlineLocal, inlineExternal, openApiFormat, openApiVersion, document, logger); } catch (TaskCanceledException) @@ -98,7 +107,7 @@ CancellationToken cancellationToken } } - private static void WriteOpenApi(FileInfo output, bool terseOutput, bool inlineLocal, bool inlineExternal, OpenApiFormat openApiFormat, OpenApiSpecVersion openApiVersion, OpenApiDocument document, ILogger logger) + private static void WriteOpenApi(FileInfo output, bool terseOutput, bool inlineLocal, bool inlineExternal, OpenApiFormat openApiFormat, OpenApiSpecVersion openApiVersion, OpenApiDocument document, ILogger logger) { using (logger.BeginScope("Output")) { @@ -135,7 +144,7 @@ private static async Task GetOpenApi(string openapi, string csd { OpenApiDocument document; Stream stream; - + if (!string.IsNullOrEmpty(csdl)) { var stopwatch = new Stopwatch(); @@ -168,7 +177,7 @@ private static async Task GetOpenApi(string openapi, string csd return document; } - private static async Task FilterOpenApiDocument(string filterbyoperationids, string filterbytags, string filterbycollection, OpenApiDocument document, ILogger logger, CancellationToken cancellationToken) + private static async Task FilterOpenApiDocument(string filterbyoperationids, string filterbytags, string filterbycollection, OpenApiDocument document, ILogger logger, CancellationToken cancellationToken) { using (logger.BeginScope("Filter")) { @@ -239,8 +248,8 @@ private static Stream ApplyFilterToCsdl(Stream csdlStream, string entitySetOrSin /// Implementation of the validate command /// public static async Task ValidateOpenApiDocument( - string openapi, - ILogger logger, + string openapi, + ILogger logger, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(openapi)) @@ -285,7 +294,7 @@ private static async Task ParseOpenApi(string openApiFile, bool inli result = await new OpenApiStreamReader(new OpenApiReaderSettings { LoadExternalRefs = inlineExternal, - BaseUrl = openApiFile.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? + BaseUrl = openApiFile.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? new Uri(openApiFile) : new Uri("file://" + new FileInfo(openApiFile).DirectoryName + Path.DirectorySeparatorChar) } @@ -296,7 +305,7 @@ private static async Task ParseOpenApi(string openApiFile, bool inli LogErrors(logger, result); stopwatch.Stop(); } - + return result; } @@ -310,7 +319,7 @@ internal static IConfiguration GetConfiguration(string settingsFile) return config; } - + /// /// Converts CSDL to OpenAPI /// @@ -329,7 +338,7 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl, stri { settings.SemVerVersion = metadataVersion; } - + config.GetSection("OpenApiConvertSettings").Bind(settings); OpenApiDocument document = edmModel.ConvertToOpenApi(settings); @@ -354,7 +363,7 @@ public static OpenApiDocument FixReferences(OpenApiDocument document) return doc; } - + /// /// Takes in a file stream, parses the stream into a JsonDocument and gets a list of paths and Http methods /// @@ -377,13 +386,13 @@ public static Dictionary> ParseJsonCollectionFile(Stream st private static Dictionary> EnumerateJsonDocument(JsonElement itemElement, Dictionary> paths) { var itemsArray = itemElement.GetProperty("item"); - + foreach (var item in itemsArray.EnumerateArray()) { - if(item.ValueKind == JsonValueKind.Object) + if (item.ValueKind == JsonValueKind.Object) { - if(item.TryGetProperty("request", out var request)) - { + if (item.TryGetProperty("request", out var request)) + { // Fetch list of methods and urls from collection, store them in a dictionary var path = request.GetProperty("url").GetProperty("raw").ToString(); var method = request.GetProperty("method").ToString(); @@ -395,11 +404,11 @@ private static Dictionary> EnumerateJsonDocument(JsonElemen { paths[path].Add(method); } - } - else - { + } + else + { EnumerateJsonDocument(item, paths); - } + } } else { @@ -508,11 +517,11 @@ internal static async Task ShowOpenApiDocument(string openapi, string cs if (output == null) { var tempPath = Path.GetTempPath() + "/hidi/"; - if(!File.Exists(tempPath)) + if (!File.Exists(tempPath)) { Directory.CreateDirectory(tempPath); - } - + } + var fileName = Path.GetRandomFileName(); output = new FileInfo(Path.Combine(tempPath, fileName + ".html")); @@ -528,7 +537,7 @@ internal static async Task ShowOpenApiDocument(string openapi, string cs process.StartInfo.FileName = output.FullName; process.StartInfo.UseShellExecute = true; process.Start(); - + return output.FullName; } else // Write diagram as Markdown document to output file @@ -540,7 +549,7 @@ internal static async Task ShowOpenApiDocument(string openapi, string cs } logger.LogTrace("Created markdown document with diagram "); return output.FullName; - } + } } } catch (TaskCanceledException) @@ -563,7 +572,7 @@ private static void LogErrors(ILogger logger, ReadResult result) { foreach (var error in context.Errors) { - logger.LogError($"Detected error during parsing: {error}",error.ToString()); + logger.LogError($"Detected error during parsing: {error}", error.ToString()); } } } @@ -581,7 +590,7 @@ internal static void WriteTreeDocumentAsMarkdown(string openapiUrl, OpenApiDocum // write a span for each mermaidcolorscheme foreach (var style in OpenApiUrlTreeNode.MermaidNodeStyles) { - writer.WriteLine($"{style.Key.Replace("_"," ")}"); + writer.WriteLine($"{style.Key.Replace("_", " ")}"); } writer.WriteLine("
"); writer.WriteLine(); @@ -609,7 +618,7 @@ internal static void WriteTreeDocumentAsHtml(string sourceUrl, OpenApiDocument d writer.WriteLine("

" + document.Info.Title + "

"); writer.WriteLine(); writer.WriteLine($"

API Description: {sourceUrl}

"); - + writer.WriteLine(@"
"); // write a span for each mermaidcolorscheme foreach (var style in OpenApiUrlTreeNode.MermaidNodeStyles) @@ -622,8 +631,8 @@ internal static void WriteTreeDocumentAsHtml(string sourceUrl, OpenApiDocument d rootNode.WriteMermaid(writer); writer.WriteLine(""); - // Write script tag to include JS library for rendering markdown - writer.WriteLine(@""); - // Write script tag to include JS library for rendering mermaid - writer.WriteLine("("--format", "File format"); formatOption.AddAlias("-f"); - + var terseOutputOption = new Option("--terse-output", "Produce terse json output"); terseOutputOption.AddAlias("--to"); @@ -76,6 +73,9 @@ internal static RootCommand CreateRootCommand() var inlineExternalOption = new Option("--inline-external", "Inline external $ref instances"); inlineExternalOption.AddAlias("--ie"); + // TODO: Move to settings file (--settings-path). + var languageFormatOption = new Option("--language-style", "Language to format the OpenAPI document. e.g. powershell"); + var validateCommand = new Command("validate") { descriptionOption, @@ -105,7 +105,8 @@ internal static RootCommand CreateRootCommand() filterByTagsOption, filterByCollectionOption, inlineLocalOption, - inlineExternalOption + inlineExternalOption, + languageFormatOption }; transformCommand.Handler = new TransformCommandHandler @@ -125,7 +126,8 @@ internal static RootCommand CreateRootCommand() FilterByTagsOption = filterByTagsOption, FilterByCollectionOption = filterByCollectionOption, InlineLocalOption = inlineLocalOption, - InlineExternalOption = inlineExternalOption + InlineExternalOption = inlineExternalOption, + LanguageFormatOption = languageFormatOption }; var showCommand = new Command("show") diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 9081c49f5..50a85fb15 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -3,16 +3,12 @@ using System.CommandLine; using System.CommandLine.Invocation; -using System.Text; -using Castle.Core.Logging; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Hidi; -using Microsoft.OpenApi.Hidi.Handlers; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.OData; using Microsoft.OpenApi.Services; -using Microsoft.VisualStudio.TestPlatform.Utilities; using Xunit; namespace Microsoft.OpenApi.Tests.Services @@ -36,7 +32,7 @@ public async Task ReturnConvertedCSDLFile() Assert.NotEmpty(openApiDoc.Paths); Assert.Equal(expectedPathCount, openApiDoc.Paths.Count); } - + [Theory] [InlineData("Todos.Todo.UpdateTodo", null, 1)] [InlineData("Todos.Todo.ListTodo", null, 1)] @@ -47,7 +43,7 @@ public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocumen var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UtilityFiles\\Todo.xml"); var fileInput = new FileInfo(filePath); var csdlStream = fileInput.OpenRead(); - + // Act var openApiDoc = await OpenApiService.ConvertCsdlToOpenApi(csdlStream); var predicate = OpenApiFilterService.CreatePredicate(operationIds, tags); @@ -58,7 +54,7 @@ public async Task ReturnFilteredOpenApiDocBasedOnOperationIdsAndInputCsdlDocumen Assert.NotEmpty(subsetOpenApiDocument.Paths); Assert.Equal(expectedPathCount, subsetOpenApiDocument.Paths.Count); } - + [Theory] [InlineData("UtilityFiles/appsettingstest.json")] [InlineData(null)] @@ -122,7 +118,7 @@ public void ShowCommandGeneratesMermaidDiagramAsHtml() var output = reader.ReadToEnd(); Assert.Contains("graph LR", output); } - + [Fact] public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() @@ -190,18 +186,18 @@ public async Task TransformCommandConvertsOpenApi() { var fileinfo = new FileInfo("sample.json"); // create a dummy ILogger instance for testing - await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml",null, null, fileinfo, true, null, null, null,false,null,false,false,null,null,null,new Logger(new LoggerFactory()), new CancellationToken()); + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, fileinfo, true, null, null, null, false, null, false, false, null, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText("sample.json"); Assert.NotEmpty(output); } - + [Fact] public async Task TransformCommandConvertsOpenApiWithDefaultOutputname() { // create a dummy ILogger instance for testing - await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, null, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, null, null, null, false, null, false, false, null, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText("output.yml"); Assert.NotEmpty(output); @@ -211,7 +207,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputname() public async Task TransformCommandConvertsCsdlWithDefaultOutputname() { // create a dummy ILogger instance for testing - await OpenApiService.TransformOpenApiDocument(null, "UtilityFiles\\Todo.xml", null, null, true, null, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + await OpenApiService.TransformOpenApiDocument(null, "UtilityFiles\\Todo.xml", null, null, true, null, null, null, false, null, false, false, null, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText("output.yml"); Assert.NotEmpty(output); @@ -221,7 +217,7 @@ public async Task TransformCommandConvertsCsdlWithDefaultOutputname() public async Task TransformCommandConvertsOpenApiWithDefaultOutputnameAndSwitchFormat() { // create a dummy ILogger instance for testing - await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, "3.0", null, OpenApiFormat.Yaml, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); + await OpenApiService.TransformOpenApiDocument("UtilityFiles\\SampleOpenApi.yml", null, null, null, true, "3.0", null, OpenApiFormat.Yaml, false, null, false, false, null, null, null, null, new Logger(new LoggerFactory()), new CancellationToken()); var output = File.ReadAllText("output.yml"); Assert.NotEmpty(output); @@ -231,7 +227,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputnameAndSwitchF public async Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() { await Assert.ThrowsAsync(async () => - await OpenApiService.TransformOpenApiDocument(null, null, null, null, true, null, null, null, false, null, false, false, null, null, null, new Logger(new LoggerFactory()), new CancellationToken())); + await OpenApiService.TransformOpenApiDocument(null, null, null, null, true, null, null, null, false, null, false, false, null, null, null, null, new Logger(new LoggerFactory()), new CancellationToken())); } @@ -239,7 +235,7 @@ await Assert.ThrowsAsync(async () => public void InvokeTransformCommand() { var rootCommand = Program.CreateRootCommand(); - var args = new string[] { "transform", "-d", ".\\UtilityFiles\\SampleOpenApi.yml", "-o", "sample.json","--co" }; + var args = new string[] { "transform", "-d", ".\\UtilityFiles\\SampleOpenApi.yml", "-o", "sample.json", "--co" }; var parseResult = rootCommand.Parse(args); var handler = rootCommand.Subcommands.Where(c => c.Name == "transform").First().Handler; var context = new InvocationContext(parseResult); From faf29de50d861f33c297e1f78229d454b3554bca Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 9 May 2023 15:02:49 +0300 Subject: [PATCH 495/855] Clean up Readme file --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 07f4553c9..60cc5e2f7 100644 --- a/README.md +++ b/README.md @@ -91,15 +91,15 @@ var outputString = openApiDocument.Serialize(OpenApiSpecVersion.OpenApi2_0, Open ``` -# Validating/Testing OpenApi descriptions +# Validating/Testing OpenAPI descriptions In order to test the validity of an OpenApi document, we avail the following tools: - [Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenApi.Hidi) - A commandline tool for validating and transforming OpenApi descriptions. [Installation guidelines and documentation](https://github.com/microsoft/OpenAPI.NET/blob/vnext/src/Microsoft.OpenApi.Hidi/readme.md) + A commandline tool for validating and transforming OpenAPI descriptions. [Installation guidelines and documentation](https://github.com/microsoft/OpenAPI.NET/blob/vnext/src/Microsoft.OpenApi.Hidi/readme.md) - Microsoft.OpenApi.Workbench - A workbench tool consisting of a GUI where you can test and convert OpenApi descriptions in both Json and Yaml from v2-->v3 and vice versa. + A workbench tool consisting of a GUI where you can test and convert OpenAPI descriptions in both JSON and YAML from v2-->v3 and vice versa. #### Installation guidelines: 1. Clone the repo locally by running this command: @@ -111,7 +111,7 @@ In order to test the validity of an OpenApi document, we avail the following too - 5. Copy and paste your OpenApi descriptions in the **Input Content** window or paste the path to the descriptions file in the **Input File** textbox and click on `convert` to render the results. + 5. Copy and paste your OpenAPI descriptions in the **Input Content** window or paste the path to the descriptions file in the **Input File** textbox and click on `Convert` to render the results. # Build Status From f4dee067824b3b8a18c526bf1e09f20fdd2bb548 Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Tue, 9 May 2023 17:01:26 -0700 Subject: [PATCH 496/855] Use strongly typed config and options --- .../Extensions/CommandExtensions.cs | 19 +++ .../Handlers/ShowCommandHandler.cs | 25 ++-- .../Handlers/TransformCommandHandler.cs | 49 ++----- .../Handlers/ValidateCommandHandler.cs | 19 +-- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 88 ++++-------- .../Options/CommandOptions.cs | 93 ++++++++++++ .../Options/FilterOptions.cs | 12 ++ .../Options/HidiOptions.cs | 62 ++++++++ src/Microsoft.OpenApi.Hidi/Program.cs | 134 ++---------------- .../Utilities/SettingsUtilities.cs | 32 +++++ .../Services/OpenApiServiceTests.cs | 58 ++++++-- 11 files changed, 335 insertions(+), 256 deletions(-) create mode 100644 src/Microsoft.OpenApi.Hidi/Extensions/CommandExtensions.cs create mode 100644 src/Microsoft.OpenApi.Hidi/Options/CommandOptions.cs create mode 100644 src/Microsoft.OpenApi.Hidi/Options/FilterOptions.cs create mode 100644 src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs create mode 100644 src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs diff --git a/src/Microsoft.OpenApi.Hidi/Extensions/CommandExtensions.cs b/src/Microsoft.OpenApi.Hidi/Extensions/CommandExtensions.cs new file mode 100644 index 000000000..9d5077432 --- /dev/null +++ b/src/Microsoft.OpenApi.Hidi/Extensions/CommandExtensions.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using System.CommandLine; + +namespace Microsoft.OpenApi.Hidi.Extensions +{ + internal static class CommandExtensions + { + public static void AddOptions(this Command command, IReadOnlyList
"); writer.WriteLine(); @@ -683,7 +681,7 @@ internal static void WriteTreeDocumentAsHtml(string sourceUrl, OpenApiDocument d // write a span for each mermaidcolorscheme foreach (var style in OpenApiUrlTreeNode.MermaidNodeStyles) { - writer.WriteLine($"{style.Key.Replace("_", " ")}"); + writer.WriteLine($"{style.Key.Replace("_", " ", StringComparison.OrdinalIgnoreCase)}"); } writer.WriteLine(""); writer.WriteLine("
"); @@ -708,17 +706,17 @@ internal static void WriteTreeDocumentAsHtml(string sourceUrl, OpenApiDocument d writer.WriteLine(" Main(string[] args) var rootCommand = CreateRootCommand(); // Parse the incoming args and invoke the handler - return await rootCommand.InvokeAsync(args); + return await rootCommand.InvokeAsync(args).ConfigureAwait(false); } internal static RootCommand CreateRootCommand() diff --git a/src/Microsoft.OpenApi.Hidi/StatsVisitor.cs b/src/Microsoft.OpenApi.Hidi/StatsVisitor.cs index b05b0de7c..871f88dca 100644 --- a/src/Microsoft.OpenApi.Hidi/StatsVisitor.cs +++ b/src/Microsoft.OpenApi.Hidi/StatsVisitor.cs @@ -10,63 +10,63 @@ namespace Microsoft.OpenApi.Hidi { internal class StatsVisitor : OpenApiVisitorBase { - public int ParameterCount { get; set; } = 0; + public int ParameterCount { get; set; } public override void Visit(OpenApiParameter parameter) { ParameterCount++; } - public int SchemaCount { get; set; } = 0; + public int SchemaCount { get; set; } public override void Visit(OpenApiSchema schema) { SchemaCount++; } - public int HeaderCount { get; set; } = 0; + public int HeaderCount { get; set; } public override void Visit(IDictionary headers) { HeaderCount++; } - public int PathItemCount { get; set; } = 0; + public int PathItemCount { get; set; } public override void Visit(OpenApiPathItem pathItem) { PathItemCount++; } - public int RequestBodyCount { get; set; } = 0; + public int RequestBodyCount { get; set; } public override void Visit(OpenApiRequestBody requestBody) { RequestBodyCount++; } - public int ResponseCount { get; set; } = 0; + public int ResponseCount { get; set; } public override void Visit(OpenApiResponses response) { ResponseCount++; } - public int OperationCount { get; set; } = 0; + public int OperationCount { get; set; } public override void Visit(OpenApiOperation operation) { OperationCount++; } - public int LinkCount { get; set; } = 0; + public int LinkCount { get; set; } public override void Visit(OpenApiLink operation) { LinkCount++; } - public int CallbackCount { get; set; } = 0; + public int CallbackCount { get; set; } public override void Visit(OpenApiCallback callback) { diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index ebe55934f..4f37314b1 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -6,6 +6,9 @@ enable false + true + All + CA2007 diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 647cac321..b1fcd24d3 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -17,13 +17,14 @@ namespace Microsoft.OpenApi.Hidi.Tests { - public class OpenApiServiceTests + public sealed class OpenApiServiceTests : IDisposable { private readonly ILogger _logger; + private readonly LoggerFactory _loggerFactory = new(); public OpenApiServiceTests() { - _logger = new Logger(new LoggerFactory()); + _logger = new Logger(_loggerFactory); } [Fact] @@ -105,7 +106,7 @@ public void ShowCommandGeneratesMermaidDiagramAsMarkdown() stream.Position = 0; using var reader = new StreamReader(stream); var output = reader.ReadToEnd(); - Assert.Contains("graph LR", output); + Assert.Contains("graph LR", output, StringComparison.Ordinal); } [Fact] @@ -126,7 +127,7 @@ public void ShowCommandGeneratesMermaidDiagramAsHtml() stream.Position = 0; using var reader = new StreamReader(stream); var output = reader.ReadToEnd(); - Assert.Contains("graph LR", output); + Assert.Contains("graph LR", output, StringComparison.Ordinal); } @@ -144,7 +145,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() await OpenApiService.ShowOpenApiDocument(options, _logger, new CancellationToken()); var output = File.ReadAllText(options.Output.FullName); - Assert.Contains("graph LR", output); + Assert.Contains("graph LR", output, StringComparison.Ordinal); } [Fact] @@ -172,7 +173,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileFromCsdlWithMermaidDiag await OpenApiService.ShowOpenApiDocument(options, _logger, new CancellationToken()); var output = File.ReadAllText(options.Output.FullName); - Assert.Contains("graph LR", output); + Assert.Contains("graph LR", output, StringComparison.Ordinal); } [Fact] @@ -341,8 +342,8 @@ public void InvokeTransformCommand() public void InvokeShowCommand() { var rootCommand = Program.CreateRootCommand(); - var openapi = Path.Combine(".", "UtilityFiles", "SampleOpenApi.yml"); - var args = new string[] { "show", "-d", openapi, "-o", "sample.md" }; + var openApi = Path.Combine(".", "UtilityFiles", "SampleOpenApi.yml"); + var args = new string[] { "show", "-d", openApi, "-o", "sample.md" }; var parseResult = rootCommand.Parse(args); var handler = rootCommand.Subcommands.Where(c => c.Name == "show").First().Handler; var context = new InvocationContext(parseResult); @@ -350,7 +351,7 @@ public void InvokeShowCommand() handler!.Invoke(context); var output = File.ReadAllText("sample.md"); - Assert.Contains("graph LR", output); + Assert.Contains("graph LR", output, StringComparison.Ordinal); } [Fact] @@ -383,5 +384,10 @@ public void CreateRootCommand() var rootCommand = Program.CreateRootCommand(); Assert.NotNull(rootCommand); } + + public void Dispose() + { + _loggerFactory.Dispose(); + } } } From c099ebe6fe6014d794858d82d00e3d2eb21a03d7 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Fri, 15 Sep 2023 08:10:48 -0400 Subject: [PATCH 604/855] - fixes hidi release build --- .../Handlers/PluginCommandHandler.cs | 8 ++++++++ .../Handlers/ShowCommandHandler.cs | 8 ++++++++ .../Handlers/TransformCommandHandler.cs | 8 ++++++++ .../Handlers/ValidateCommandHandler.cs | 10 +++++++++- 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs index 0fcb86df2..2c7e921bb 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs @@ -35,16 +35,24 @@ public async Task InvokeAsync(InvocationContext context) return 0; } +#if RELEASE +#pragma warning disable CA1031 // Do not catch general exception types +#endif catch (Exception ex) { #if DEBUG logger.LogCritical(ex, "Command failed"); throw; // so debug tools go straight to the source of the exception when attached #else +#pragma warning disable CA2254 logger.LogCritical(ex.Message); +#pragma warning restore CA2254 return 1; #endif } +#if RELEASE +#pragma warning restore CA1031 // Do not catch general exception types +#endif } } } diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs index a6a161dc2..054912302 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs @@ -35,16 +35,24 @@ public async Task InvokeAsync(InvocationContext context) return 0; } +#if RELEASE +#pragma warning disable CA1031 // Do not catch general exception types +#endif catch (Exception ex) { #if DEBUG logger.LogCritical(ex, "Command failed"); throw; // so debug tools go straight to the source of the exception when attached #else +#pragma warning disable CA2254 logger.LogCritical( ex.Message); +#pragma warning restore CA2254 return 1; #endif } +#if RELEASE +#pragma warning restore CA1031 // Do not catch general exception types +#endif } } } diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index f173024cc..293fefec9 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -35,16 +35,24 @@ public async Task InvokeAsync(InvocationContext context) return 0; } +#if RELEASE +#pragma warning disable CA1031 // Do not catch general exception types +#endif catch (Exception ex) { #if DEBUG logger.LogCritical(ex, "Command failed"); throw; // so debug tools go straight to the source of the exception when attached #else +#pragma warning disable CA2254 logger.LogCritical( ex.Message); +#pragma warning restore CA2254 return 1; #endif } +#if RELEASE +#pragma warning restore CA1031 // Do not catch general exception types +#endif } } } diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs index 153ec707e..4351a04cb 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs @@ -36,16 +36,24 @@ public async Task InvokeAsync(InvocationContext context) await OpenApiService.ValidateOpenApiDocument(hidiOptions.OpenApi, logger, cancellationToken).ConfigureAwait(false); return 0; } +#if RELEASE +#pragma warning disable CA1031 // Do not catch general exception types +#endif catch (Exception ex) { #if DEBUG logger.LogCritical(ex, "Command failed"); throw; // so debug tools go straight to the source of the exception when attached #else - logger.LogCritical( ex.Message); +#pragma warning disable CA2254 + logger.LogCritical(ex.Message); +#pragma warning restore CA2254 return 1; #endif } +#if RELEASE +#pragma warning restore CA1031 // Do not catch general exception types +#endif } } } From fa032dd7e74211417b23e47176d59b069e7314d2 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 18 Sep 2023 09:50:12 -0400 Subject: [PATCH 605/855] - removes publish trimmed since it'd break functionality Signed-off-by: Vincent Biret --- .azure-pipelines/ci-build.yml | 2 +- src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 4ce92b8e9..43612060c 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -216,7 +216,7 @@ stages: displayName: publish Hidi as executable inputs: command: 'publish' - arguments: -c Release --runtime win-x64 /p:PublishSingleFile=true --self-contained --output $(Build.ArtifactStagingDirectory)/Microsoft.OpenApi.Hidi-v$(hidiversion) -p:PublishTrimmed=true + arguments: -c Release --runtime win-x64 /p:PublishSingleFile=true --self-contained --output $(Build.ArtifactStagingDirectory)/Microsoft.OpenApi.Hidi-v$(hidiversion) projects: 'src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj' publishWebProjects: False zipAfterPublish: false diff --git a/src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs b/src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs index 1d261e5f3..6264270a6 100644 --- a/src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs +++ b/src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs @@ -20,7 +20,7 @@ internal static IConfiguration GetConfiguration(string? settingsFile = null) return config; } - internal static OpenApiConvertSettings GetOpenApiConvertSettings(IConfiguration config, string? metadataVersion = null) + internal static OpenApiConvertSettings GetOpenApiConvertSettings(IConfiguration config, string? metadataVersion) { if (config == null) { throw new System.ArgumentNullException(nameof(config)); } var settings = new OpenApiConvertSettings(); From 4c558a886605f6f3b6f8db53e5594a61d4619998 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Sep 2023 21:01:18 +0000 Subject: [PATCH 606/855] Bump xunit.runner.visualstudio from 2.5.0 to 2.5.1 Bumps [xunit.runner.visualstudio](https://github.com/xunit/xunit) from 2.5.0 to 2.5.1. - [Commits](https://github.com/xunit/xunit/compare/2.5.0...2.5.1) --- updated-dependencies: - dependency-name: xunit.runner.visualstudio dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 4 ++-- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index ebe55934f..8c6bdd9c0 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -16,7 +16,7 @@ - + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 98ac3a206..c173d2ad2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -1,4 +1,4 @@ - + net7.0 false @@ -281,7 +281,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index c1355fec4..89dc9d666 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -19,7 +19,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index a028227ef..8461b3ee6 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -30,7 +30,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive From da91427a0dc62b298960d95bec4263b2667ceedd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Sep 2023 21:05:44 +0000 Subject: [PATCH 607/855] Bump xunit from 2.5.0 to 2.5.1 Bumps [xunit](https://github.com/xunit/xunit) from 2.5.0 to 2.5.1. - [Commits](https://github.com/xunit/xunit/compare/2.5.0...2.5.1) --- updated-dependencies: - dependency-name: xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 8c6bdd9c0..706e899f1 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -15,7 +15,7 @@ - + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index c173d2ad2..7669e2fcf 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -279,7 +279,7 @@ - + all diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 89dc9d666..2d72104ad 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -18,7 +18,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 8461b3ee6..7c0411500 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -29,7 +29,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive From e4acf0951784c566695539ffc15f41950092632f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Sep 2023 21:27:58 +0000 Subject: [PATCH 608/855] Bump docker/build-push-action from 4.2.1 to 5.0.0 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 4.2.1 to 5.0.0. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v4.2.1...v5.0.0) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index daee21546..103e77df0 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -30,13 +30,13 @@ jobs: id: getversion - name: Push to GitHub Packages - Nightly if: ${{ github.ref == 'refs/heads/vnext' }} - uses: docker/build-push-action@v4.2.1 + uses: docker/build-push-action@v5.0.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly - name: Push to GitHub Packages - Release if: ${{ github.ref == 'refs/heads/master' }} - uses: docker/build-push-action@v4.2.1 + uses: docker/build-push-action@v5.0.0 with: push: true tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest,${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.getversion.outputs.version }} From adbbe34f46da91ea7ed9aae150a6d3cbe84a56d0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Sep 2023 21:28:03 +0000 Subject: [PATCH 609/855] Bump docker/login-action from 2.2.0 to 3.0.0 Bumps [docker/login-action](https://github.com/docker/login-action) from 2.2.0 to 3.0.0. - [Release notes](https://github.com/docker/login-action/releases) - [Commits](https://github.com/docker/login-action/compare/v2.2.0...v3.0.0) --- updated-dependencies: - dependency-name: docker/login-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index daee21546..c6c3eb95f 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -17,7 +17,7 @@ jobs: - name: Check out the repo uses: actions/checkout@v4 - name: Login to GitHub package feed - uses: docker/login-action@v2.2.0 + uses: docker/login-action@v3.0.0 with: username: ${{ secrets.ACR_USERNAME }} password: ${{ secrets.ACR_PASSWORD }} From cca1bb917ebf01373045832676f168cb9620354c Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 19 Sep 2023 07:56:02 -0400 Subject: [PATCH 610/855] - fixes readme path to the correct hidi readme --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index b02f89003..3d20c3d9f 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -69,7 +69,7 @@ - + From 5c3230192140c8b4e078c5721f039891de59969d Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 19 Sep 2023 08:03:48 -0400 Subject: [PATCH 611/855] - adds auto merge dependabot workflow --- .github/workflows/auto-merge-dependabot.yml | 32 +++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .github/workflows/auto-merge-dependabot.yml diff --git a/.github/workflows/auto-merge-dependabot.yml b/.github/workflows/auto-merge-dependabot.yml new file mode 100644 index 000000000..6e5953f56 --- /dev/null +++ b/.github/workflows/auto-merge-dependabot.yml @@ -0,0 +1,32 @@ +name: Auto-merge dependabot updates + +on: + pull_request: + branches: [ main ] + +permissions: + pull-requests: write + contents: write + +jobs: + + dependabot-merge: + + runs-on: ubuntu-latest + + if: ${{ github.actor == 'dependabot[bot]' }} + + steps: + - name: Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@v1.6.0 + with: + github-token: "${{ secrets.GITHUB_TOKEN }}" + + - name: Enable auto-merge for Dependabot PRs + # Only if version bump is not a major version change + if: ${{steps.metadata.outputs.update-type != 'version-update:semver-major'}} + run: gh pr merge --auto --merge "$PR_URL" + env: + PR_URL: ${{github.event.pull_request.html_url}} + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} From 65b7e7eb0d8376148e802e0d187f59fab3e99e83 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 19 Sep 2023 09:29:44 -0400 Subject: [PATCH 612/855] - fixes an issue where executable release would fail because of warn as error --- .azure-pipelines/ci-build.yml | 2 +- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 43612060c..244797588 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -216,7 +216,7 @@ stages: displayName: publish Hidi as executable inputs: command: 'publish' - arguments: -c Release --runtime win-x64 /p:PublishSingleFile=true --self-contained --output $(Build.ArtifactStagingDirectory)/Microsoft.OpenApi.Hidi-v$(hidiversion) + arguments: -c Release --runtime win-x64 /p:PublishSingleFile=true /p:PackAsTool=false --self-contained --output $(Build.ArtifactStagingDirectory)/Microsoft.OpenApi.Hidi-v$(hidiversion) projects: 'src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj' publishWebProjects: False zipAfterPublish: false diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 3d20c3d9f..f1ac21781 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -28,7 +28,7 @@ true true - NU5048;CA1848; + $(NoWarn);NU5048;NU5104;CA1848; true readme.md All From e07a980b14543a07dbdaa912262cf1ef53845ac1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 19 Sep 2023 21:17:31 +0000 Subject: [PATCH 613/855] Bump Verify.Xunit from 21.1.3 to 21.1.4 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 21.1.3 to 21.1.4. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/21.1.3...21.1.4) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 7c0411500..d9f34b2bc 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 0bb8a93525379479d209e279729b0515a9161c70 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 21 Sep 2023 21:46:23 +0000 Subject: [PATCH 614/855] Bump Verify.Xunit from 21.1.4 to 21.1.5 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 21.1.4 to 21.1.5. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/21.1.4...21.1.5) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index d9f34b2bc..55e99d880 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 33ff05480f754eda46e393bddecef3b7cc642d72 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Sep 2023 21:01:48 +0000 Subject: [PATCH 615/855] Bump Verify.Xunit from 21.1.5 to 21.2.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 21.1.5 to 21.2.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 55e99d880..214b2f017 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 73c11c53e81adfd7c7878b349c871a1d36e69744 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 26 Sep 2023 10:41:45 +0300 Subject: [PATCH 616/855] Add a DefaultContentType setting to OpenApiReaderSettings --- src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs | 5 +++++ src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs | 3 ++- src/Microsoft.OpenApi.Readers/ParsingContext.cs | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs index 56001e295..25bcbca6f 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs @@ -62,6 +62,11 @@ public class OpenApiReaderSettings /// public Uri BaseUrl { get; set; } + /// + /// Allows clients to define a custom DefaultContentType if produces array is empty + /// + public List DefaultContentType { get; set; } + /// /// Function used to provide an alternative loader for accessing external references. /// diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 5b87ab7ae..4a120cbbf 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -47,7 +47,8 @@ public OpenApiDocument Read(YamlDocument input, out OpenApiDiagnostic diagnostic var context = new ParsingContext(diagnostic) { ExtensionParsers = _settings.ExtensionParsers, - BaseUrl = _settings.BaseUrl + BaseUrl = _settings.BaseUrl, + DefaultContentType = _settings.DefaultContentType }; OpenApiDocument document = null; diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index 6c4dece2f..0cd98c67e 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -29,6 +29,7 @@ public class ParsingContext internal RootNode RootNode { get; set; } internal List Tags { get; private set; } = new List(); internal Uri BaseUrl { get; set; } + internal List DefaultContentType { get; set; } /// /// Diagnostic object that returns metadata about the parsing process. From 07202317c7cdee148941ac1ea0fd5d83faf529eb Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 26 Sep 2023 10:42:35 +0300 Subject: [PATCH 617/855] Use the setting passed as the default content type if global and local produces are missing --- src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs index 5734ff19d..182def419 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs @@ -74,7 +74,7 @@ private static void ProcessProduces(MapNode mapNode, OpenApiResponse response, P var produces = context.GetFromTempStorage>(TempStorageKeys.OperationProduces) ?? context.GetFromTempStorage>(TempStorageKeys.GlobalProduces) - ?? new List { "application/octet-stream" }; + ?? context.DefaultContentType ?? new List { "application/octet-stream" }; var schema = context.GetFromTempStorage(TempStorageKeys.ResponseSchema, response); From f359565dfcba4ddbe97901b3939bdce4a8cf255c Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 26 Sep 2023 10:43:03 +0300 Subject: [PATCH 618/855] Add test to validate --- .../Microsoft.OpenApi.Readers.Tests.csproj | 5 +++- .../V2Tests/OpenApiDocumentTests.cs | 30 ++++++++++++------- .../V2Tests/Samples/docWithEmptyProduces.yaml | 20 +++++++++++++ 3 files changed, 43 insertions(+), 12 deletions(-) create mode 100644 test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/docWithEmptyProduces.yaml diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 7669e2fcf..ee9240603 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -36,7 +36,10 @@ Never - + + Never + + PreserveNewest diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index 0b35d43e8..ac5f99a86 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -409,19 +409,27 @@ public void ShouldAssignSchemaToAllResponses() [Fact] public void ShouldAllowComponentsThatJustContainAReference() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "ComponentRootReference.json"))) + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "ComponentRootReference.json")); + OpenApiStreamReader reader = new OpenApiStreamReader(); + OpenApiDocument doc = reader.Read(stream, out OpenApiDiagnostic diags); + OpenApiSchema schema1 = doc.Components.Schemas["AllPets"]; + Assert.False(schema1.UnresolvedReference); + OpenApiSchema schema2 = doc.ResolveReferenceTo(schema1.Reference); + if (schema2.UnresolvedReference && schema1.Reference.Id == schema2.Reference.Id) { - OpenApiStreamReader reader = new OpenApiStreamReader(); - OpenApiDocument doc = reader.Read(stream, out OpenApiDiagnostic diags); - OpenApiSchema schema1 = doc.Components.Schemas["AllPets"]; - Assert.False(schema1.UnresolvedReference); - OpenApiSchema schema2 = doc.ResolveReferenceTo(schema1.Reference); - if (schema2.UnresolvedReference && schema1.Reference.Id == schema2.Reference.Id) - { - // detected a cycle - this code gets triggered - Assert.Fail("A cycle should not be detected"); - } + // detected a cycle - this code gets triggered + Assert.Fail("A cycle should not be detected"); } } + + [Fact] + public void ParseDocumentWithDefaultContentTypeSettingShouldSucceed() + { + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "docWithEmptyProduces.yaml")); + var doc = new OpenApiStreamReader(new OpenApiReaderSettings { DefaultContentType = new List { "application/json" } }) + .Read(stream, out OpenApiDiagnostic diags); + var mediaType = doc.Paths["/example"].Operations[OperationType.Get].Responses["200"].Content; + Assert.Contains("application/json", mediaType); + } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/docWithEmptyProduces.yaml b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/docWithEmptyProduces.yaml new file mode 100644 index 000000000..ba9213c08 --- /dev/null +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/Samples/docWithEmptyProduces.yaml @@ -0,0 +1,20 @@ +swagger: '2.0' +info: + title: Sample API + version: 1.0.0 +paths: + /example: + get: + summary: Get Example + description: Retrieves an example resource. + produces: [] + responses: + 200: + description: Successful response + schema: + format: binary, + description: The content of the file., + type: string, + x-ms-summary: File Content +components: {} + \ No newline at end of file From 3d6c85e9f0d95335de58194c325f6bdaa74bbcdb Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 26 Sep 2023 16:43:26 +0300 Subject: [PATCH 619/855] Bump lib versions --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index f1ac21781..ced9d9c3c 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -17,7 +17,7 @@ Microsoft.OpenApi.Hidi hidi ./../../artifacts - 1.2.9 + 1.3.0 OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 609b16a09..49dde408e 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi.Readers Microsoft.OpenApi.Readers - 1.6.8 + 1.6.9 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 739d34354..7372332c1 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -11,7 +11,7 @@ Microsoft Microsoft.OpenApi Microsoft.OpenApi - 1.6.8 + 1.6.9 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET From b2544025fe63cf1e5c9bad7ced2d1aa86b75e2f2 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 26 Sep 2023 17:06:15 +0300 Subject: [PATCH 620/855] Fix grammatical error in ReadMe --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 60cc5e2f7..358d0a686 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ var document = new OpenApiDocument }; ``` -Reading and writing a OpenAPI description +Reading and writing an OpenAPI description ```C# var httpClient = new HttpClient From 6e0f84a6f783d96119a80fef710aece7cd4d08b9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 28 Sep 2023 21:55:15 +0000 Subject: [PATCH 621/855] Bump Verify.Xunit from 21.2.0 to 21.3.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 21.2.0 to 21.3.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits/21.3.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 214b2f017..56c833d45 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -28,7 +28,7 @@ - + all From 7fe922db323c32a16e1a97d861b6f4c7bfa6c0fd Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:29:02 +1000 Subject: [PATCH 622/855] fix some warnings --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 13 +++++++------ .../Services/OpenApiServiceTests.cs | 14 +++++++------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 809e3ecf9..b3e66cfe2 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -81,7 +81,7 @@ public static async Task TransformOpenApiDocument(HidiOptions options, ILogger l if (!string.IsNullOrEmpty(options.FilterOptions?.FilterByCollection)) { using var collectionStream = await GetStream(options.FilterOptions.FilterByCollection, logger, cancellationToken).ConfigureAwait(false); - postmanCollection = JsonDocument.Parse(collectionStream); + postmanCollection = await JsonDocument.ParseAsync(collectionStream, cancellationToken: cancellationToken).ConfigureAwait(false); } // Load OpenAPI document @@ -132,7 +132,8 @@ public static async Task TransformOpenApiDocument(HidiOptions options, ILogger l } using (var fileStream = await GetStream(apiManifestRef[0], logger, cancellationToken).ConfigureAwait(false)) { - apiManifest = ApiManifestDocument.Load(JsonDocument.Parse(fileStream).RootElement); + var document = await JsonDocument.ParseAsync(fileStream, cancellationToken: cancellationToken).ConfigureAwait(false); + apiManifest = ApiManifestDocument.Load(document.RootElement); } apiDependency = !string.IsNullOrEmpty(apiDependencyName) && apiManifest.ApiDependencies.TryGetValue(apiDependencyName, out var dependency) ? dependency : apiManifest.ApiDependencies.First().Value; @@ -453,13 +454,13 @@ private static Dictionary> EnumerateJsonDocument(JsonElemen // Fetch list of methods and urls from collection, store them in a dictionary var path = request.GetProperty("url").GetProperty("raw").ToString(); var method = request.GetProperty("method").ToString(); - if (!paths.ContainsKey(path)) + if (paths.TryGetValue(path, out var value)) { - paths.Add(path, new List { method }); + value.Add(method); } else { - paths[path].Add(method); + paths.Add(path, new List {method}); } } else @@ -755,7 +756,7 @@ internal static async Task PluginManifest(HidiOptions options, ILogger logger, C using var file = new FileStream(manifestFile.FullName, FileMode.Create); using var jsonWriter = new Utf8JsonWriter(file, new JsonWriterOptions { Indented = true }); manifest.Write(jsonWriter); - jsonWriter.Flush(); + await jsonWriter.FlushAsync(cancellationToken).ConfigureAwait(false); } } } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index b1fcd24d3..9d73c8db6 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -144,7 +144,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() await OpenApiService.ShowOpenApiDocument(options, _logger, new CancellationToken()); - var output = File.ReadAllText(options.Output.FullName); + var output = await File.ReadAllTextAsync(options.Output.FullName); Assert.Contains("graph LR", output, StringComparison.Ordinal); } @@ -172,7 +172,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileFromCsdlWithMermaidDiag // create a dummy ILogger instance for testing await OpenApiService.ShowOpenApiDocument(options, _logger, new CancellationToken()); - var output = File.ReadAllText(options.Output.FullName); + var output = await File.ReadAllTextAsync(options.Output.FullName); Assert.Contains("graph LR", output, StringComparison.Ordinal); } @@ -223,7 +223,7 @@ public async Task TransformCommandConvertsOpenApi() // create a dummy ILogger instance for testing await OpenApiService.TransformOpenApiDocument(options, _logger, new CancellationToken()); - var output = File.ReadAllText("sample.json"); + var output = await File.ReadAllTextAsync("sample.json"); Assert.NotEmpty(output); } @@ -242,7 +242,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputName() // create a dummy ILogger instance for testing await OpenApiService.TransformOpenApiDocument(options, _logger, new CancellationToken()); - var output = File.ReadAllText("output.yml"); + var output = await File.ReadAllTextAsync("output.yml"); Assert.NotEmpty(output); } @@ -260,7 +260,7 @@ public async Task TransformCommandConvertsCsdlWithDefaultOutputName() // create a dummy ILogger instance for testing await OpenApiService.TransformOpenApiDocument(options, _logger, new CancellationToken()); - var output = File.ReadAllText("output.yml"); + var output = await File.ReadAllTextAsync("output.yml"); Assert.NotEmpty(output); } @@ -280,7 +280,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputNameAndSwitchF // create a dummy ILogger instance for testing await OpenApiService.TransformOpenApiDocument(options, _logger, new CancellationToken()); - var output = File.ReadAllText("output.yml"); + var output = await File.ReadAllTextAsync("output.yml"); Assert.NotEmpty(output); } @@ -317,7 +317,7 @@ public async Task TransformToPowerShellCompliantOpenApi() // create a dummy ILogger instance for testing await OpenApiService.TransformOpenApiDocument(options, _logger, new CancellationToken()); - var output = File.ReadAllText("output.yml"); + var output = await File.ReadAllTextAsync("output.yml"); Assert.NotEmpty(output); } From c1a6ebaf5a768cb97877b4d0a63218f2d264366f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:44:25 +1000 Subject: [PATCH 623/855] move dir props up --- src/Directory.Build.props => Directory.Build.props | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename src/Directory.Build.props => Directory.Build.props (61%) diff --git a/src/Directory.Build.props b/Directory.Build.props similarity index 61% rename from src/Directory.Build.props rename to Directory.Build.props index bfc937cba..c1064f1a0 100644 --- a/src/Directory.Build.props +++ b/Directory.Build.props @@ -3,6 +3,8 @@ $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb - + \ No newline at end of file From 63aa7330355e42acc73b3daf30bddbdf57687ce5 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:45:54 +1000 Subject: [PATCH 624/855] remove csproj settings that are convention based on project name --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 4 ---- .../Microsoft.OpenApi.Readers.csproj | 4 ---- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 4 ---- .../Microsoft.OpenApi.Readers.Tests.csproj | 5 ----- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 5 ----- 5 files changed, 22 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index ced9d9c3c..ae373f6c8 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -13,8 +13,6 @@ true Microsoft Microsoft - Microsoft.OpenApi.Hidi - Microsoft.OpenApi.Hidi hidi ./../../artifacts 1.3.0 @@ -23,8 +21,6 @@ OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET https://github.com/microsoft/OpenAPI.NET/releases - Microsoft.OpenApi.Hidi - Microsoft.OpenApi.Hidi true true diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 49dde408e..f7faa1d9b 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -9,16 +9,12 @@ true Microsoft Microsoft - Microsoft.OpenApi.Readers - Microsoft.OpenApi.Readers 1.6.9 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET https://github.com/microsoft/OpenAPI.NET/releases - Microsoft.OpenApi.Readers - Microsoft.OpenApi.Readers true true diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 7372332c1..e876a57d2 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -9,16 +9,12 @@ true Microsoft Microsoft - Microsoft.OpenApi - Microsoft.OpenApi 1.6.9 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET https://github.com/Microsoft/OpenAPI.NET https://github.com/microsoft/OpenAPI.NET/releases - Microsoft.OpenApi - Microsoft.OpenApi true true diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index ee9240603..bbea8fe69 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -4,11 +4,6 @@ false Microsoft - Microsoft.OpenApi.Readers.Tests - Microsoft.OpenApi.Readers.Tests - Tests for Microsoft.OpenApi.Readers - Microsoft.OpenApi.Readers.Tests - Microsoft.OpenApi.Readers.Tests true ..\..\src\Microsoft.OpenApi.snk diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 56c833d45..25f915704 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -4,11 +4,6 @@ false Microsoft - Microsoft.OpenApi.Tests - Microsoft.OpenApi.Tests - Tests for Microsoft.OpenApi - Microsoft.OpenApi.Tests - Microsoft.OpenApi.Tests true Library ..\..\src\Microsoft.OpenApi.snk From 6356fc2ae91ba44173929e37d9e0f30009ab924f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:47:29 +1000 Subject: [PATCH 625/855] move Authors and company to props --- Directory.Build.props | 2 ++ src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 -- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 -- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 -- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 -- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 -- 6 files changed, 2 insertions(+), 10 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index c1064f1a0..861236ce2 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,8 @@ $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + Microsoft + Microsoft https://github.com/Microsoft/OpenAPI.NET MIT true - Microsoft - Microsoft hidi ./../../artifacts 1.3.0 diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index f7faa1d9b..026d2d47a 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -7,8 +7,6 @@ https://github.com/Microsoft/OpenAPI.NET MIT true - Microsoft - Microsoft 1.6.9 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index e876a57d2..c5266741f 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -7,8 +7,6 @@ https://github.com/Microsoft/OpenAPI.NET MIT true - Microsoft - Microsoft 1.6.9 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index bbea8fe69..e9eadcd38 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -2,8 +2,6 @@ net7.0 false - - Microsoft true ..\..\src\Microsoft.OpenApi.snk diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 25f915704..25d764817 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -2,8 +2,6 @@ net7.0 false - - Microsoft true Library ..\..\src\Microsoft.OpenApi.snk From 6149e55defabdf62713acb9c174cc554ac2e36c7 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:48:20 +1000 Subject: [PATCH 626/855] move license to props --- Directory.Build.props | 1 + src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 1 - src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 1 - src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 1 - 4 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 861236ce2..b6c70f6cc 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -3,6 +3,7 @@ $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb Microsoft Microsoft + MIT enable http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/Microsoft/OpenAPI.NET - MIT true hidi ./../../artifacts diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 026d2d47a..7b80c66fa 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -5,7 +5,6 @@ true http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/Microsoft/OpenAPI.NET - MIT true 1.6.9 OpenAPI.NET Readers for JSON and YAML documents diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index c5266741f..80e76f089 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -5,7 +5,6 @@ true http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/Microsoft/OpenAPI.NET - MIT true 1.6.9 .NET models with JSON and YAML writers for OpenAPI specification From 7e60f937e36a75b1a9ce5ed2abaec15febbb77be Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:48:57 +1000 Subject: [PATCH 627/855] move PackageRequireLicenseAcceptance to props --- Directory.Build.props | 1 + src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 1 - src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 1 - src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 1 - 4 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index b6c70f6cc..00158e414 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,6 +4,7 @@ Microsoft Microsoft MIT + true enable http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/Microsoft/OpenAPI.NET - true hidi ./../../artifacts 1.3.0 diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 7b80c66fa..a090f4aef 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -5,7 +5,6 @@ true http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/Microsoft/OpenAPI.NET - true 1.6.9 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 80e76f089..9f76741a1 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -5,7 +5,6 @@ true http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/Microsoft/OpenAPI.NET - true 1.6.9 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. From 6e6a2b8e438500e3549a841945e809bd0d02f25f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:49:52 +1000 Subject: [PATCH 628/855] move RepositoryUrl to props --- Directory.Build.props | 1 + src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 1 - src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 1 - src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 1 - 4 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 00158e414..cb89aecf0 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,6 +5,7 @@ Microsoft MIT true + https://github.com/Microsoft/OpenAPI.NET OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET - https://github.com/Microsoft/OpenAPI.NET https://github.com/microsoft/OpenAPI.NET/releases true diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index a090f4aef..7ea9c4655 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -9,7 +9,6 @@ OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET - https://github.com/Microsoft/OpenAPI.NET https://github.com/microsoft/OpenAPI.NET/releases true diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 9f76741a1..71fcdf361 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -9,7 +9,6 @@ .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET - https://github.com/Microsoft/OpenAPI.NET https://github.com/microsoft/OpenAPI.NET/releases true From 4f1513e24e7a73365d90cd814e0cb867aadd40d9 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:50:26 +1000 Subject: [PATCH 629/855] move PackageReleaseNotes to props --- Directory.Build.props | 1 + src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 1 - src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 1 - src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 1 - 4 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index cb89aecf0..671fcd507 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,6 +6,7 @@ MIT true https://github.com/Microsoft/OpenAPI.NET + https://github.com/microsoft/OpenAPI.NET/releases OpenAPI.NET CLI tool for slicing OpenAPI documents © Microsoft Corporation. All rights reserved. OpenAPI .NET - https://github.com/microsoft/OpenAPI.NET/releases true true diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 7ea9c4655..120ad9215 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -9,7 +9,6 @@ OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. OpenAPI .NET - https://github.com/microsoft/OpenAPI.NET/releases true true diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 71fcdf361..720995f9b 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -9,7 +9,6 @@ .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. OpenAPI .NET - https://github.com/microsoft/OpenAPI.NET/releases true true From 838ac24ed6aaf6dc1a5df1f808693284b9e368c3 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:51:20 +1000 Subject: [PATCH 630/855] move TreatWarningsAsErrors to props --- Directory.Build.props | 1 + src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 1 - src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 1 - src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 1 - .../Microsoft.OpenApi.Hidi.Tests.csproj | 1 - 5 files changed, 1 insertion(+), 4 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 671fcd507..37fb23a82 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,6 +7,7 @@ true https://github.com/Microsoft/OpenAPI.NET https://github.com/microsoft/OpenAPI.NET/releases + true true $(NoWarn);NU5048;NU5104;CA1848; - true readme.md All diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 120ad9215..41504d442 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -13,7 +13,6 @@ true NU5048 - true README.md diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 720995f9b..b54feb2cf 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -13,7 +13,6 @@ true NU5048 - true README.md diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 3f719eda8..89789bbb9 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -6,7 +6,6 @@ enable false - true All CA2007 From b813e518985cddf7faadde60aea81aa1a68194fe Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:52:02 +1000 Subject: [PATCH 631/855] move ContinuousIntegrationBuild to props --- Directory.Build.props | 4 ++++ .../Microsoft.OpenApi.Readers.csproj | 5 ----- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 5 ----- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 37fb23a82..95d10054c 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -9,6 +9,10 @@ https://github.com/microsoft/OpenAPI.NET/releases true + + + true + ..\Microsoft.OpenApi.snk - - - true - - diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index b54feb2cf..6419da7a6 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -21,11 +21,6 @@ ..\Microsoft.OpenApi.snk - - - true - - True From 37afc804893216dda1f9831a34265432e70e5cc7 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:52:51 +1000 Subject: [PATCH 632/855] move PackageIconUrl and PackageProjectUrl to props --- Directory.Build.props | 2 ++ src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 -- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 -- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 -- 4 files changed, 2 insertions(+), 6 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 95d10054c..d2685c137 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -8,6 +8,8 @@ https://github.com/Microsoft/OpenAPI.NET https://github.com/microsoft/OpenAPI.NET/releases true + http://go.microsoft.com/fwlink/?LinkID=288890 + https://github.com/Microsoft/OpenAPI.NET diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 6435a5256..7806fbd3d 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -7,8 +7,6 @@ true true enable - http://go.microsoft.com/fwlink/?LinkID=288890 - https://github.com/Microsoft/OpenAPI.NET hidi ./../../artifacts 1.3.0 diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 1c95ae7aa..df29cfc1f 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -3,8 +3,6 @@ netstandard2.0 latest true - http://go.microsoft.com/fwlink/?LinkID=288890 - https://github.com/Microsoft/OpenAPI.NET 1.6.9 OpenAPI.NET Readers for JSON and YAML documents © Microsoft Corporation. All rights reserved. diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 6419da7a6..404afc36b 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -3,8 +3,6 @@ netstandard2.0 Latest true - http://go.microsoft.com/fwlink/?LinkID=288890 - https://github.com/Microsoft/OpenAPI.NET 1.6.9 .NET models with JSON and YAML writers for OpenAPI specification © Microsoft Corporation. All rights reserved. From 0ac9a52fc1be2062c73c1ad6387e79162db1602c Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:53:36 +1000 Subject: [PATCH 633/855] move Copyright to props --- Directory.Build.props | 1 + src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 1 - src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 1 - src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 1 - 4 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index d2685c137..70ab6850a 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -10,6 +10,7 @@ true http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/Microsoft/OpenAPI.NET + © Microsoft Corporation. All rights reserved. diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 7806fbd3d..14d5125ae 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -11,7 +11,6 @@ ./../../artifacts 1.3.0 OpenAPI.NET CLI tool for slicing OpenAPI documents - © Microsoft Corporation. All rights reserved. OpenAPI .NET true diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index df29cfc1f..edb08e140 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -5,7 +5,6 @@ true 1.6.9 OpenAPI.NET Readers for JSON and YAML documents - © Microsoft Corporation. All rights reserved. OpenAPI .NET true diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 404afc36b..2b891ffdc 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -5,7 +5,6 @@ true 1.6.9 .NET models with JSON and YAML writers for OpenAPI specification - © Microsoft Corporation. All rights reserved. OpenAPI .NET true From cde8923c853393ed48a6bca24dcea69635fe1b2f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:54:10 +1000 Subject: [PATCH 634/855] move PackageTags to props --- Directory.Build.props | 1 + src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 1 - src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 1 - src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 1 - 4 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 70ab6850a..f65c81703 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -11,6 +11,7 @@ http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/Microsoft/OpenAPI.NET © Microsoft Corporation. All rights reserved. + OpenAPI .NET diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 14d5125ae..fd1520481 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -11,7 +11,6 @@ ./../../artifacts 1.3.0 OpenAPI.NET CLI tool for slicing OpenAPI documents - OpenAPI .NET true true diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index edb08e140..e08a54fca 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -5,7 +5,6 @@ true 1.6.9 OpenAPI.NET Readers for JSON and YAML documents - OpenAPI .NET true true diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index 2b891ffdc..e0afd008d 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -5,7 +5,6 @@ true 1.6.9 .NET models with JSON and YAML writers for OpenAPI specification - OpenAPI .NET true true From 4df30254f6c41aa34f9072ece2152d4a62ffbe5c Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:55:19 +1000 Subject: [PATCH 635/855] TargetFrameworks to TargetFramework --- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index e08a54fca..33788cebd 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -1,6 +1,6 @@  - netstandard2.0 + netstandard2.0 latest true 1.6.9 diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index e0afd008d..dc1e97a64 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -1,6 +1,6 @@  - netstandard2.0 + netstandard2.0 Latest true 1.6.9 diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index e9eadcd38..cf6a7a470 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -1,6 +1,6 @@ - net7.0 + net7.0 false true ..\..\src\Microsoft.OpenApi.snk diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 2d72104ad..db323e1c6 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -1,7 +1,7 @@ - net7.0 + net7.0 diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 25d764817..1e29addc4 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -1,6 +1,6 @@ - net7.0 + net7.0 false true Library From 2b304a73d4c4194336e8b1f6be7555898a8065ad Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:57:08 +1000 Subject: [PATCH 636/855] simplify PrivateAssets all --- .../Microsoft.OpenApi.Workbench.csproj | 4 +--- .../Microsoft.OpenApi.Hidi.Tests.csproj | 15 +++------------ .../Microsoft.OpenApi.Readers.Tests.csproj | 15 +++------------ .../Microsoft.OpenApi.SmokeTests.csproj | 15 +++------------ .../Microsoft.OpenApi.Tests.csproj | 15 +++------------ 5 files changed, 13 insertions(+), 51 deletions(-) diff --git a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj index e2d75c96a..36a1d979b 100644 --- a/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj +++ b/src/Microsoft.OpenApi.Workbench/Microsoft.OpenApi.Workbench.csproj @@ -8,9 +8,7 @@ true - - all - + diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 89789bbb9..1f2ec91e3 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -11,21 +11,12 @@ - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - + - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - + + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index cf6a7a470..1b3cec73a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -260,14 +260,8 @@ - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - + + @@ -277,10 +271,7 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index db323e1c6..637e25583 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -8,21 +8,12 @@ - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - + + - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 1e29addc4..b073d6b8d 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -8,14 +8,8 @@ - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - + + @@ -23,10 +17,7 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + From 32b2525ab7c472131d05b891b292c0023d870315 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 30 Sep 2023 22:57:41 +1000 Subject: [PATCH 637/855] remove redundant PackageReference closing tags --- .../Microsoft.OpenApi.Readers.Tests.csproj | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 1b3cec73a..5ba3103fe 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -263,14 +263,10 @@ - - - - - - - - + + + + From cf89b4f756bcfb7775d4b8987a553fbf11ac29ab Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:09:30 +1100 Subject: [PATCH 638/855] use some pattern matiching --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 16 +++++++++------- .../ParseNodes/OpenApiAnyConverter.cs | 2 +- .../ParseNodes/ValueNode.cs | 2 +- src/Microsoft.OpenApi.Readers/ParsingContext.cs | 2 +- .../V2/OpenApiV2VersionService.cs | 2 +- .../V3/OpenApiV3VersionService.cs | 2 +- .../OpenApiEnumValuesDescriptionExtension.cs | 2 +- .../Writers/OpenApiWriterAnyExtensionsTests.cs | 2 +- 8 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index b3e66cfe2..8d6471e88 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -510,13 +510,15 @@ private static async Task GetStream(string input, ILogger logger, Cancel var fileInput = new FileInfo(input); stream = fileInput.OpenRead(); } - catch (Exception ex) when (ex is FileNotFoundException || - ex is PathTooLongException || - ex is DirectoryNotFoundException || - ex is IOException || - ex is UnauthorizedAccessException || - ex is SecurityException || - ex is NotSupportedException) + catch (Exception ex) when ( + ex is + FileNotFoundException or + PathTooLongException or + DirectoryNotFoundException or + IOException or + UnauthorizedAccessException or + SecurityException or + NotSupportedException) { throw new InvalidOperationException($"Could not open the file at {input}", ex); } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs index ae9254fe8..01aef7652 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs @@ -116,7 +116,7 @@ public static IOpenApiAny GetSpecificOpenApiAny(IOpenApiAny openApiAny, OpenApiS return openApiAny; } - if (value == null || value == "null") + if (value is null or "null") { return new OpenApiNull(); } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs index 68f4bd7ea..bbce7a7d3 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs @@ -34,7 +34,7 @@ public override string GetScalarValue() public override IOpenApiAny CreateAny() { var value = GetScalarValue(); - return new OpenApiString(value, this._node.Style == ScalarStyle.SingleQuoted || this._node.Style == ScalarStyle.DoubleQuoted || this._node.Style == ScalarStyle.Literal || this._node.Style == ScalarStyle.Folded); + return new OpenApiString(value, this._node.Style is ScalarStyle.SingleQuoted or ScalarStyle.DoubleQuoted or ScalarStyle.Literal or ScalarStyle.Folded); } } } diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index 0cd98c67e..afc76bcf5 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -60,7 +60,7 @@ internal OpenApiDocument Parse(YamlDocument yamlDocument) switch (inputVersion) { - case string version when version == "2.0": + case string and "2.0": VersionService = new OpenApiV2VersionService(Diagnostic); doc = VersionService.LoadDocument(RootNode); this.Diagnostic.SpecificationVersion = OpenApiSpecVersion.OpenApi2_0; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index 33c9d7c6f..54b0a3776 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -152,7 +152,7 @@ public OpenApiReference ConvertToOpenApiReference(string reference, ReferenceTyp }; } - if (type == ReferenceType.Tag || type == ReferenceType.SecurityScheme) + if (type is ReferenceType.Tag or ReferenceType.SecurityScheme) { return new OpenApiReference { diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 889ce4cb8..60ce71c8a 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -78,7 +78,7 @@ public OpenApiReference ConvertToOpenApiReference( var segments = reference.Split('#'); if (segments.Length == 1) { - if (type == ReferenceType.Tag || type == ReferenceType.SecurityScheme) + if (type is ReferenceType.Tag or ReferenceType.SecurityScheme) { return new OpenApiReference { diff --git a/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtension.cs b/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtension.cs index b3db2b437..c98a87af1 100644 --- a/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtension.cs +++ b/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtension.cs @@ -38,7 +38,7 @@ public class OpenApiEnumValuesDescriptionExtension : IOpenApiExtension public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { if (writer is null) throw new ArgumentNullException(nameof(writer)); - if ((specVersion == OpenApiSpecVersion.OpenApi2_0 || specVersion == OpenApiSpecVersion.OpenApi3_0) && + if (specVersion is OpenApiSpecVersion.OpenApi2_0 or OpenApiSpecVersion.OpenApi3_0 && !string.IsNullOrEmpty(EnumName) && ValuesDescriptions.Any()) { // when we upgrade to 3.1, we don't need to write this extension as JSON schema will support writing enum values diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs index c9ef96efd..d1839015d 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs @@ -274,7 +274,7 @@ private static string WriteAsJson(IOpenApiAny any, bool produceTerseOutput = fal // Act var value = new StreamReader(stream).ReadToEnd(); - if (any.AnyType == AnyType.Primitive || any.AnyType == AnyType.Null) + if (any.AnyType is AnyType.Primitive or AnyType.Null) { return value; } From fc431205206514a95415fef4410c99f4cfa86561 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:14:05 +1100 Subject: [PATCH 639/855] elide some asyncs --- src/Microsoft.OpenApi.Hidi/Program.cs | 4 ++-- .../OpenApiYamlDocumentReader.cs | 4 ++-- .../Services/OpenApiServiceTests.cs | 24 +++++++++---------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index b8508ab5f..9fe8a3014 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -12,12 +12,12 @@ namespace Microsoft.OpenApi.Hidi { static class Program { - static async Task Main(string[] args) + static Task Main(string[] args) { var rootCommand = CreateRootCommand(); // Parse the incoming args and invoke the handler - return await rootCommand.InvokeAsync(args).ConfigureAwait(false); + return rootCommand.InvokeAsync(args); } internal static RootCommand CreateRootCommand() diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 4a120cbbf..de7f810ad 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -140,7 +140,7 @@ public async Task ReadAsync(YamlDocument input, CancellationToken ca }; } - private async Task LoadExternalRefs(OpenApiDocument document, CancellationToken cancellationToken) + private Task LoadExternalRefs(OpenApiDocument document, CancellationToken cancellationToken) { // Create workspace for all documents to live in. var openApiWorkSpace = new OpenApiWorkspace(); @@ -148,7 +148,7 @@ private async Task LoadExternalRefs(OpenApiDocument document, // Load this root document into the workspace var streamLoader = new DefaultStreamLoader(_settings.BaseUrl); var workspaceLoader = new OpenApiWorkspaceLoader(openApiWorkSpace, _settings.CustomExternalLoader ?? streamLoader, _settings); - return await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document, cancellationToken); + return workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document, cancellationToken); } private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument document) diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 9d73c8db6..24169045f 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -177,25 +177,25 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileFromCsdlWithMermaidDiag } [Fact] - public async Task ThrowIfOpenApiUrlIsNotProvidedWhenValidating() + public Task ThrowIfOpenApiUrlIsNotProvidedWhenValidating() { - await Assert.ThrowsAsync(async () => - await OpenApiService.ValidateOpenApiDocument("", _logger, new CancellationToken())); + return Assert.ThrowsAsync(() => + OpenApiService.ValidateOpenApiDocument("", _logger, new CancellationToken())); } [Fact] - public async Task ThrowIfURLIsNotResolvableWhenValidating() + public Task ThrowIfURLIsNotResolvableWhenValidating() { - await Assert.ThrowsAsync(async () => - await OpenApiService.ValidateOpenApiDocument("https://example.org/itdoesnmatter", _logger, new CancellationToken())); + return Assert.ThrowsAsync(() => + OpenApiService.ValidateOpenApiDocument("https://example.org/itdoesnmatter", _logger, new CancellationToken())); } [Fact] - public async Task ThrowIfFileDoesNotExistWhenValidating() + public Task ThrowIfFileDoesNotExistWhenValidating() { - await Assert.ThrowsAsync(async () => - await OpenApiService.ValidateOpenApiDocument("aFileThatBetterNotExist.fake", _logger, new CancellationToken())); + return Assert.ThrowsAsync(() => + OpenApiService.ValidateOpenApiDocument("aFileThatBetterNotExist.fake", _logger, new CancellationToken())); } [Fact] @@ -285,7 +285,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputNameAndSwitchF } [Fact] - public async Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() + public Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() { HidiOptions options = new HidiOptions { @@ -294,8 +294,8 @@ public async Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() InlineLocal = false, InlineExternal = false, }; - await Assert.ThrowsAsync(async () => - await OpenApiService.TransformOpenApiDocument(options, _logger, new CancellationToken())); + return Assert.ThrowsAsync(() => + OpenApiService.TransformOpenApiDocument(options, _logger, new CancellationToken())); } From 86c72b561a4b8b06dcb198b9174d9f0c60751e16 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:17:02 +1100 Subject: [PATCH 640/855] using declarations --- .../OpenApiStreamReader.cs | 12 +- .../OpenApiStringReader.cs | 12 +- .../OpenApiSerializableExtensions.cs | 14 +- .../OpenApiDiagnosticTests.cs | 20 +- .../OpenApiStreamReaderTests.cs | 20 +- .../UnsupportedSpecVersionTests.cs | 16 +- .../Resources.cs | 8 +- .../V2Tests/ComparisonTests.cs | 14 +- .../V2Tests/OpenApiDocumentTests.cs | 256 ++++--- .../V2Tests/OpenApiSecuritySchemeTests.cs | 264 +++---- .../V3Tests/OpenApiCallbackTests.cs | 320 ++++---- .../V3Tests/OpenApiDiscriminatorTests.cs | 40 +- .../V3Tests/OpenApiDocumentTests.cs | 300 ++++---- .../V3Tests/OpenApiEncodingTests.cs | 70 +- .../V3Tests/OpenApiExampleTests.cs | 76 +- .../V3Tests/OpenApiInfoTests.cs | 202 +++-- .../V3Tests/OpenApiOperationTests.cs | 10 +- .../V3Tests/OpenApiResponseTests.cs | 10 +- .../V3Tests/OpenApiSchemaTests.cs | 710 +++++++++--------- .../V3Tests/OpenApiSecuritySchemeTests.cs | 220 +++--- .../V3Tests/OpenApiXmlTests.cs | 38 +- 21 files changed, 1259 insertions(+), 1373 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index 8922be4ce..7debb3723 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -73,10 +73,8 @@ public async Task ReadAsync(Stream input, CancellationToken cancella bufferedStream.Position = 0; } - using (var reader = new StreamReader(bufferedStream)) - { - return await new OpenApiTextReaderReader(_settings).ReadAsync(reader, cancellationToken); - } + using var reader = new StreamReader(bufferedStream); + return await new OpenApiTextReaderReader(_settings).ReadAsync(reader, cancellationToken); } /// @@ -88,10 +86,8 @@ public async Task ReadAsync(Stream input, CancellationToken cancella /// Instance of newly created OpenApiDocument public T ReadFragment(Stream input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic) where T : IOpenApiReferenceable { - using (var reader = new StreamReader(input)) - { - return new OpenApiTextReaderReader(_settings).ReadFragment(reader, version, out diagnostic); - } + using var reader = new StreamReader(input); + return new OpenApiTextReaderReader(_settings).ReadFragment(reader, version, out diagnostic); } } } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs index 0cb9605dd..92e5307c4 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs @@ -29,10 +29,8 @@ public OpenApiStringReader(OpenApiReaderSettings settings = null) /// public OpenApiDocument Read(string input, out OpenApiDiagnostic diagnostic) { - using (var reader = new StringReader(input)) - { - return new OpenApiTextReaderReader(_settings).Read(reader, out diagnostic); - } + using var reader = new StringReader(input); + return new OpenApiTextReaderReader(_settings).Read(reader, out diagnostic); } /// @@ -40,10 +38,8 @@ public OpenApiDocument Read(string input, out OpenApiDiagnostic diagnostic) /// public T ReadFragment(string input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic) where T : IOpenApiElement { - using (var reader = new StringReader(input)) - { - return new OpenApiTextReaderReader(_settings).ReadFragment(reader, version, out diagnostic); - } + using var reader = new StringReader(input); + return new OpenApiTextReaderReader(_settings).ReadFragment(reader, version, out diagnostic); } } } diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs index f60c5483b..92ede5634 100755 --- a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs @@ -179,16 +179,12 @@ public static string Serialize( throw Error.ArgumentNull(nameof(element)); } - using (var stream = new MemoryStream()) - { - element.Serialize(stream, specVersion, format); - stream.Position = 0; + using var stream = new MemoryStream(); + element.Serialize(stream, specVersion, format); + stream.Position = 0; - using (var streamReader = new StreamReader(stream)) - { - return streamReader.ReadToEnd(); - } - } + using var streamReader = new StreamReader(stream); + return streamReader.ReadToEnd(); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs index 23c23b4d6..e9109c061 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs @@ -20,25 +20,21 @@ public class OpenApiDiagnosticTests [Fact] public void DetectedSpecificationVersionShouldBeV2_0() { - using (var stream = Resources.GetStream("V2Tests/Samples/basic.v2.yaml")) - { - new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream("V2Tests/Samples/basic.v2.yaml"); + new OpenApiStreamReader().Read(stream, out var diagnostic); - diagnostic.Should().NotBeNull(); - diagnostic.SpecificationVersion.Should().Be(OpenApiSpecVersion.OpenApi2_0); - } + diagnostic.Should().NotBeNull(); + diagnostic.SpecificationVersion.Should().Be(OpenApiSpecVersion.OpenApi2_0); } [Fact] public void DetectedSpecificationVersionShouldBeV3_0() { - using (var stream = Resources.GetStream("V3Tests/Samples/OpenApiDocument/minimalDocument.yaml")) - { - new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream("V3Tests/Samples/OpenApiDocument/minimalDocument.yaml"); + new OpenApiStreamReader().Read(stream, out var diagnostic); - diagnostic.Should().NotBeNull(); - diagnostic.SpecificationVersion.Should().Be(OpenApiSpecVersion.OpenApi3_0); - } + diagnostic.Should().NotBeNull(); + diagnostic.SpecificationVersion.Should().Be(OpenApiSpecVersion.OpenApi3_0); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs index 7567e0b7d..0f6bbce15 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs @@ -13,23 +13,19 @@ public class OpenApiStreamReaderTests [Fact] public void StreamShouldCloseIfLeaveStreamOpenSettingEqualsFalse() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml"))) - { - var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LeaveStreamOpen = false }); - reader.Read(stream, out _); - Assert.False(stream.CanRead); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml")); + var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LeaveStreamOpen = false }); + reader.Read(stream, out _); + Assert.False(stream.CanRead); } [Fact] public void StreamShouldNotCloseIfLeaveStreamOpenSettingEqualsTrue() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml"))) - { - var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LeaveStreamOpen = true}); - reader.Read(stream, out _); - Assert.True(stream.CanRead); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml")); + var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LeaveStreamOpen = true}); + reader.Read(stream, out _); + Assert.True(stream.CanRead); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs index cd60aa630..753f60e6a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs @@ -13,16 +13,14 @@ public class UnsupportedSpecVersionTests [Fact] public void ThrowOpenApiUnsupportedSpecVersionException() { - using (var stream = Resources.GetStream("OpenApiReaderTests/Samples/unsupported.v1.yaml")) + using var stream = Resources.GetStream("OpenApiReaderTests/Samples/unsupported.v1.yaml"); + try { - try - { - new OpenApiStreamReader().Read(stream, out var diagnostic); - } - catch (OpenApiUnsupportedSpecVersionException exception) - { - exception.SpecificationVersion.Should().Be("1.0.0"); - } + new OpenApiStreamReader().Read(stream, out var diagnostic); + } + catch (OpenApiUnsupportedSpecVersionException exception) + { + exception.SpecificationVersion.Should().Be("1.0.0"); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/Resources.cs b/test/Microsoft.OpenApi.Readers.Tests/Resources.cs index 895e1ed3f..a817dc203 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Resources.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/Resources.cs @@ -14,11 +14,9 @@ internal static class Resources /// The file contents. public static string GetString(string fileName) { - using (Stream stream = GetStream(fileName)) - using (TextReader reader = new StreamReader(stream)) - { - return reader.ReadToEnd(); - } + using Stream stream = GetStream(fileName); + using TextReader reader = new StreamReader(stream); + return reader.ReadToEnd(); } /// diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs index 1ae3678d6..7d4f607f0 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs @@ -18,16 +18,14 @@ public class ComparisonTests //[InlineData("definitions")] //Currently broken due to V3 references not behaving the same as V2 public void EquivalentV2AndV3DocumentsShouldProductEquivalentObjects(string fileName) { - using (var streamV2 = Resources.GetStream(Path.Combine(SampleFolderPath, $"{fileName}.v2.yaml"))) - using (var streamV3 = Resources.GetStream(Path.Combine(SampleFolderPath, $"{fileName}.v3.yaml"))) - { - var openApiDocV2 = new OpenApiStreamReader().Read(streamV2, out var diagnosticV2); - var openApiDocV3 = new OpenApiStreamReader().Read(streamV3, out var diagnosticV3); + using var streamV2 = Resources.GetStream(Path.Combine(SampleFolderPath, $"{fileName}.v2.yaml")); + using var streamV3 = Resources.GetStream(Path.Combine(SampleFolderPath, $"{fileName}.v3.yaml")); + var openApiDocV2 = new OpenApiStreamReader().Read(streamV2, out var diagnosticV2); + var openApiDocV3 = new OpenApiStreamReader().Read(streamV3, out var diagnosticV3); - openApiDocV3.Should().BeEquivalentTo(openApiDocV2); + openApiDocV3.Should().BeEquivalentTo(openApiDocV2); - diagnosticV2.Errors.Should().BeEquivalentTo(diagnosticV3.Errors); - } + diagnosticV2.Errors.Should().BeEquivalentTo(diagnosticV3.Errors); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index ac5f99a86..9a6ec6a63 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -158,176 +158,174 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) [Fact] public void ShouldParseProducesInAnyOrder() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "twoResponses.json"))) - { - var reader = new OpenApiStreamReader(); - var doc = reader.Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "twoResponses.json")); + var reader = new OpenApiStreamReader(); + var doc = reader.Read(stream, out var diagnostic); - var okSchema = new OpenApiSchema() + var okSchema = new OpenApiSchema() + { + Reference = new OpenApiReference { - Reference = new OpenApiReference - { - Type = ReferenceType.Schema, - Id = "Item", - HostDocument = doc - }, - Properties = new Dictionary() - { - { "id", new OpenApiSchema() - { - Type = "string", - Description = "Item identifier." - } + Type = ReferenceType.Schema, + Id = "Item", + HostDocument = doc + }, + Properties = new Dictionary() + { + { "id", new OpenApiSchema() + { + Type = "string", + Description = "Item identifier." } } - }; + } + }; - var errorSchema = new OpenApiSchema() + var errorSchema = new OpenApiSchema() + { + Reference = new OpenApiReference { - Reference = new OpenApiReference - { - Type = ReferenceType.Schema, - Id = "Error", - HostDocument = doc + Type = ReferenceType.Schema, + Id = "Error", + HostDocument = doc + }, + Properties = new Dictionary() + { + { "code", new OpenApiSchema() + { + Type = "integer", + Format = "int32" + } }, - Properties = new Dictionary() - { - { "code", new OpenApiSchema() - { - Type = "integer", - Format = "int32" - } - }, - { "message", new OpenApiSchema() - { - Type = "string" - } - }, - { "fields", new OpenApiSchema() - { - Type = "string" - } + { "message", new OpenApiSchema() + { + Type = "string" + } + }, + { "fields", new OpenApiSchema() + { + Type = "string" } } - }; + } + }; - var okMediaType = new OpenApiMediaType + var okMediaType = new OpenApiMediaType + { + Schema = new OpenApiSchema { - Schema = new OpenApiSchema - { - Type = "array", - Items = okSchema - } - }; + Type = "array", + Items = okSchema + } + }; - var errorMediaType = new OpenApiMediaType - { - Schema = errorSchema - }; + var errorMediaType = new OpenApiMediaType + { + Schema = errorSchema + }; - doc.Should().BeEquivalentTo(new OpenApiDocument + doc.Should().BeEquivalentTo(new OpenApiDocument + { + Info = new OpenApiInfo { - Info = new OpenApiInfo - { - Title = "Two responses", - Version = "1.0.0" - }, - Servers = + Title = "Two responses", + Version = "1.0.0" + }, + Servers = + { + new OpenApiServer { - new OpenApiServer - { - Url = "https://" - } - }, - Paths = new OpenApiPaths + Url = "https://" + } + }, + Paths = new OpenApiPaths + { + ["/items"] = new OpenApiPathItem { - ["/items"] = new OpenApiPathItem + Operations = { - Operations = + [OperationType.Get] = new OpenApiOperation { - [OperationType.Get] = new OpenApiOperation + Responses = { - Responses = + ["200"] = new OpenApiResponse { - ["200"] = new OpenApiResponse + Description = "An OK response", + Content = { - Description = "An OK response", - Content = - { - ["application/json"] = okMediaType, - ["application/xml"] = okMediaType, - } - }, - ["default"] = new OpenApiResponse + ["application/json"] = okMediaType, + ["application/xml"] = okMediaType, + } + }, + ["default"] = new OpenApiResponse + { + Description = "An error response", + Content = { - Description = "An error response", - Content = - { - ["application/json"] = errorMediaType, - ["application/xml"] = errorMediaType - } + ["application/json"] = errorMediaType, + ["application/xml"] = errorMediaType } } - }, - [OperationType.Post] = new OpenApiOperation + } + }, + [OperationType.Post] = new OpenApiOperation + { + Responses = { - Responses = + ["200"] = new OpenApiResponse { - ["200"] = new OpenApiResponse + Description = "An OK response", + Content = { - Description = "An OK response", - Content = - { - ["html/text"] = okMediaType - } - }, - ["default"] = new OpenApiResponse + ["html/text"] = okMediaType + } + }, + ["default"] = new OpenApiResponse + { + Description = "An error response", + Content = { - Description = "An error response", - Content = - { - ["html/text"] = errorMediaType - } + ["html/text"] = errorMediaType } } - }, - [OperationType.Patch] = new OpenApiOperation + } + }, + [OperationType.Patch] = new OpenApiOperation + { + Responses = { - Responses = + ["200"] = new OpenApiResponse { - ["200"] = new OpenApiResponse + Description = "An OK response", + Content = { - Description = "An OK response", - Content = - { - ["application/json"] = okMediaType, - ["application/xml"] = okMediaType, - } - }, - ["default"] = new OpenApiResponse + ["application/json"] = okMediaType, + ["application/xml"] = okMediaType, + } + }, + ["default"] = new OpenApiResponse + { + Description = "An error response", + Content = { - Description = "An error response", - Content = - { - ["application/json"] = errorMediaType, - ["application/xml"] = errorMediaType - } + ["application/json"] = errorMediaType, + ["application/xml"] = errorMediaType } } } } } - }, - Components = new OpenApiComponents + } + }, + Components = new OpenApiComponents + { + Schemas = { - Schemas = - { - ["Item"] = okSchema, - ["Error"] = errorSchema - } + ["Item"] = okSchema, + ["Error"] = errorSchema } - }); - } + } + }); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs index 22f7d1633..2745385af 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs @@ -21,202 +21,188 @@ public class OpenApiSecuritySchemeTests [Fact] public void ParseHttpSecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicSecurityScheme.yaml"))) - { - var document = LoadYamlDocument(stream); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicSecurityScheme.yaml")); + var document = LoadYamlDocument(stream); - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)document.RootNode); + var node = new MapNode(context, (YamlMappingNode)document.RootNode); - // Act - var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); + // Act + var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme - { - Type = SecuritySchemeType.Http, - Scheme = OpenApiConstants.Basic - }); - } + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.Http, + Scheme = OpenApiConstants.Basic + }); } [Fact] public void ParseApiKeySecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "apiKeySecurityScheme.yaml"))) - { - var document = LoadYamlDocument(stream); - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)document.RootNode); - - // Act - var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); - - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme - { - Type = SecuritySchemeType.ApiKey, - Name = "api_key", - In = ParameterLocation.Header - }); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "apiKeySecurityScheme.yaml")); + var document = LoadYamlDocument(stream); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)document.RootNode); + + // Act + var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); + + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.ApiKey, + Name = "api_key", + In = ParameterLocation.Header + }); } [Fact] public void ParseOAuth2ImplicitSecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2ImplicitSecurityScheme.yaml"))) - { - var document = LoadYamlDocument(stream); - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)document.RootNode); - - // Act - var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); - - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2ImplicitSecurityScheme.yaml")); + var document = LoadYamlDocument(stream); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)document.RootNode); + + // Act + var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); + + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Implicit = new OpenApiOAuthFlow { - Implicit = new OpenApiOAuthFlow + AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), + Scopes = { - AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), - Scopes = - { - ["write:pets"] = "modify pets in your account", - ["read:pets"] = "read your pets" - } + ["write:pets"] = "modify pets in your account", + ["read:pets"] = "read your pets" } } - }); - } + } + }); } [Fact] public void ParseOAuth2PasswordSecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2PasswordSecurityScheme.yaml"))) - { - var document = LoadYamlDocument(stream); - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)document.RootNode); - - // Act - var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); - - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2PasswordSecurityScheme.yaml")); + var document = LoadYamlDocument(stream); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)document.RootNode); + + // Act + var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); + + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Password = new OpenApiOAuthFlow { - Password = new OpenApiOAuthFlow + AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), + Scopes = { - AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), - Scopes = - { - ["write:pets"] = "modify pets in your account", - ["read:pets"] = "read your pets" - } + ["write:pets"] = "modify pets in your account", + ["read:pets"] = "read your pets" } } - }); - } + } + }); } [Fact] public void ParseOAuth2ApplicationSecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2ApplicationSecurityScheme.yaml"))) - { - var document = LoadYamlDocument(stream); - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)document.RootNode); - - // Act - var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); - - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2ApplicationSecurityScheme.yaml")); + var document = LoadYamlDocument(stream); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)document.RootNode); + + // Act + var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); + + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + ClientCredentials = new OpenApiOAuthFlow { - ClientCredentials = new OpenApiOAuthFlow + AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), + Scopes = { - AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), - Scopes = - { - ["write:pets"] = "modify pets in your account", - ["read:pets"] = "read your pets" - } + ["write:pets"] = "modify pets in your account", + ["read:pets"] = "read your pets" } } - }); - } + } + }); } [Fact] public void ParseOAuth2AccessCodeSecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2AccessCodeSecurityScheme.yaml"))) - { - var document = LoadYamlDocument(stream); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2AccessCodeSecurityScheme.yaml")); + var document = LoadYamlDocument(stream); - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)document.RootNode); + var node = new MapNode(context, (YamlMappingNode)document.RootNode); - // Act - var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); + // Act + var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + AuthorizationCode = new OpenApiOAuthFlow { - AuthorizationCode = new OpenApiOAuthFlow + AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), + Scopes = { - AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), - Scopes = - { - ["write:pets"] = "modify pets in your account", - ["read:pets"] = "read your pets" - } + ["write:pets"] = "modify pets in your account", + ["read:pets"] = "read your pets" } } - }); - } + } + }); } static YamlDocument LoadYamlDocument(Stream input) { - using (var reader = new StreamReader(input)) - { - var yamlStream = new YamlStream(); - yamlStream.Load(reader); - return yamlStream.Documents.First(); - } + using var reader = new StreamReader(input); + var yamlStream = new YamlStream(); + yamlStream.Load(reader); + return yamlStream.Documents.First(); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs index 320f01fae..fde8a9b63 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs @@ -21,254 +21,248 @@ public class OpenApiCallbackTests [Fact] public void ParseBasicCallbackShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicCallback.yaml"))) - { - // Arrange - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicCallback.yaml")); + // Arrange + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var callback = OpenApiV3Deserializer.LoadCallback(node); + // Act + var callback = OpenApiV3Deserializer.LoadCallback(node); - // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - callback.Should().BeEquivalentTo( - new OpenApiCallback + callback.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { - [RuntimeExpression.Build("$request.body#/url")] + [RuntimeExpression.Build("$request.body#/url")] = new OpenApiPathItem { Operations = { [OperationType.Post] = - new OpenApiOperation - { - RequestBody = new OpenApiRequestBody + new OpenApiOperation { - Content = + RequestBody = new OpenApiRequestBody { - ["application/json"] = null - } - }, - Responses = new OpenApiResponses - { - ["200"] = new OpenApiResponse + Content = + { + ["application/json"] = null + } + }, + Responses = new OpenApiResponses { - Description = "Success" + ["200"] = new OpenApiResponse + { + Description = "Success" + } } } - } } } - } - }); - } + } + }); } [Fact] public void ParseCallbackWithReferenceShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "callbackWithReference.yaml"))) - { - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "callbackWithReference.yaml")); + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - // Assert - var path = openApiDoc.Paths.First().Value; - var subscribeOperation = path.Operations[OperationType.Post]; + // Assert + var path = openApiDoc.Paths.First().Value; + var subscribeOperation = path.Operations[OperationType.Post]; - var callback = subscribeOperation.Callbacks["simpleHook"]; + var callback = subscribeOperation.Callbacks["simpleHook"]; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - callback.Should().BeEquivalentTo( - new OpenApiCallback + callback.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { - [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { - Operations = { - [OperationType.Post] = new OpenApiOperation() + [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { + Operations = { + [OperationType.Post] = new OpenApiOperation() + { + RequestBody = new OpenApiRequestBody { - RequestBody = new OpenApiRequestBody + Content = { - Content = + ["application/json"] = new OpenApiMediaType { - ["application/json"] = new OpenApiMediaType + Schema = new OpenApiSchema() { - Schema = new OpenApiSchema() - { - Type = "object" - } + Type = "object" } } - }, - Responses = { - ["200"]= new OpenApiResponse - { - Description = "Success" - } + } + }, + Responses = { + ["200"]= new OpenApiResponse + { + Description = "Success" } } } } - }, - Reference = new OpenApiReference - { - Type = ReferenceType.Callback, - Id = "simpleHook", - HostDocument = openApiDoc } - }); - } + }, + Reference = new OpenApiReference + { + Type = ReferenceType.Callback, + Id = "simpleHook", + HostDocument = openApiDoc + } + }); } [Fact] public void ParseMultipleCallbacksWithReferenceShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleCallbacksWithReference.yaml"))) - { - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleCallbacksWithReference.yaml")); + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - // Assert - var path = openApiDoc.Paths.First().Value; - var subscribeOperation = path.Operations[OperationType.Post]; + // Assert + var path = openApiDoc.Paths.First().Value; + var subscribeOperation = path.Operations[OperationType.Post]; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - var callback1 = subscribeOperation.Callbacks["simpleHook"]; + var callback1 = subscribeOperation.Callbacks["simpleHook"]; - callback1.Should().BeEquivalentTo( - new OpenApiCallback + callback1.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { - [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { - Operations = { - [OperationType.Post] = new OpenApiOperation() + [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { + Operations = { + [OperationType.Post] = new OpenApiOperation() + { + RequestBody = new OpenApiRequestBody { - RequestBody = new OpenApiRequestBody + Content = { - Content = + ["application/json"] = new OpenApiMediaType { - ["application/json"] = new OpenApiMediaType + Schema = new OpenApiSchema() { - Schema = new OpenApiSchema() - { - Type = "object" - } + Type = "object" } } - }, - Responses = { - ["200"]= new OpenApiResponse - { - Description = "Success" - } + } + }, + Responses = { + ["200"]= new OpenApiResponse + { + Description = "Success" } } } } - }, - Reference = new OpenApiReference - { - Type = ReferenceType.Callback, - Id = "simpleHook", - HostDocument = openApiDoc } - }); + }, + Reference = new OpenApiReference + { + Type = ReferenceType.Callback, + Id = "simpleHook", + HostDocument = openApiDoc + } + }); - var callback2 = subscribeOperation.Callbacks["callback2"]; - callback2.Should().BeEquivalentTo( - new OpenApiCallback + var callback2 = subscribeOperation.Callbacks["callback2"]; + callback2.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { - [RuntimeExpression.Build("/simplePath")]= new OpenApiPathItem { - Operations = { - [OperationType.Post] = new OpenApiOperation() + [RuntimeExpression.Build("/simplePath")]= new OpenApiPathItem { + Operations = { + [OperationType.Post] = new OpenApiOperation() + { + RequestBody = new OpenApiRequestBody { - RequestBody = new OpenApiRequestBody + Description = "Callback 2", + Content = { - Description = "Callback 2", - Content = + ["application/json"] = new OpenApiMediaType { - ["application/json"] = new OpenApiMediaType + Schema = new OpenApiSchema() { - Schema = new OpenApiSchema() - { - Type = "string" - } + Type = "string" } } - }, - Responses = { - ["400"]= new OpenApiResponse - { - Description = "Callback Response" - } + } + }, + Responses = { + ["400"]= new OpenApiResponse + { + Description = "Callback Response" } } - }, - } + } + }, } - }); + } + }); - var callback3 = subscribeOperation.Callbacks["callback3"]; - callback3.Should().BeEquivalentTo( - new OpenApiCallback + var callback3 = subscribeOperation.Callbacks["callback3"]; + callback3.Should().BeEquivalentTo( + new OpenApiCallback + { + PathItems = { - PathItems = - { - [RuntimeExpression.Build(@"http://example.com?transactionId={$request.body#/id}&email={$request.body#/email}")] = new OpenApiPathItem { - Operations = { - [OperationType.Post] = new OpenApiOperation() + [RuntimeExpression.Build(@"http://example.com?transactionId={$request.body#/id}&email={$request.body#/email}")] = new OpenApiPathItem { + Operations = { + [OperationType.Post] = new OpenApiOperation() + { + RequestBody = new OpenApiRequestBody { - RequestBody = new OpenApiRequestBody + Content = { - Content = + ["application/xml"] = new OpenApiMediaType { - ["application/xml"] = new OpenApiMediaType + Schema = new OpenApiSchema() { - Schema = new OpenApiSchema() - { - Type = "object" - } + Type = "object" } } + } + }, + Responses = { + ["200"]= new OpenApiResponse + { + Description = "Success" }, - Responses = { - ["200"]= new OpenApiResponse - { - Description = "Success" - }, - ["401"]= new OpenApiResponse - { - Description = "Unauthorized" - }, - ["404"]= new OpenApiResponse - { - Description = "Not Found" - } + ["401"]= new OpenApiResponse + { + Description = "Unauthorized" + }, + ["404"]= new OpenApiResponse + { + Description = "Not Found" } } } } } - }); - } + } + }); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs index 0768592b3..6496a48b8 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs @@ -20,32 +20,30 @@ public class OpenApiDiscriminatorTests [Fact] public void ParseBasicDiscriminatorShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDiscriminator.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDiscriminator.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var discriminator = OpenApiV3Deserializer.LoadDiscriminator(node); + // Act + var discriminator = OpenApiV3Deserializer.LoadDiscriminator(node); - // Assert - discriminator.Should().BeEquivalentTo( - new OpenApiDiscriminator + // Assert + discriminator.Should().BeEquivalentTo( + new OpenApiDiscriminator + { + PropertyName = "pet_type", + Mapping = { - PropertyName = "pet_type", - Mapping = - { - ["puppy"] = "#/components/schemas/Dog", - ["kitten"] = "Cat" - } - }); - } + ["puppy"] = "#/components/schemas/Dog", + ["kitten"] = "Cat" + } + }); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 8a0da3481..a112824be 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -32,46 +32,38 @@ public class OpenApiDocumentTests public T Clone(T element) where T : IOpenApiSerializable { - using (var stream = new MemoryStream()) + using var stream = new MemoryStream(); + IOpenApiWriter writer; + var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); + writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() { - IOpenApiWriter writer; - var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); - writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() - { - InlineLocalReferences = true - }); - element.SerializeAsV3(writer); - writer.Flush(); - stream.Position = 0; - - using (var streamReader = new StreamReader(stream)) - { - var result = streamReader.ReadToEnd(); - return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); - } - } + InlineLocalReferences = true + }); + element.SerializeAsV3(writer); + writer.Flush(); + stream.Position = 0; + + using var streamReader = new StreamReader(stream); + var result = streamReader.ReadToEnd(); + return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); } public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) { - using (var stream = new MemoryStream()) + using var stream = new MemoryStream(); + IOpenApiWriter writer; + var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); + writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() { - IOpenApiWriter writer; - var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); - writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() - { - InlineLocalReferences = true - }); - element.SerializeAsV3WithoutReference(writer); - writer.Flush(); - stream.Position = 0; - - using (var streamReader = new StreamReader(stream)) - { - var result = streamReader.ReadToEnd(); - return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); - } - } + InlineLocalReferences = true + }); + element.SerializeAsV3WithoutReference(writer); + writer.Flush(); + stream.Position = 0; + + using var streamReader = new StreamReader(stream); + var result = streamReader.ReadToEnd(); + return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); } @@ -182,89 +174,83 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) [Fact] public void ParseBasicDocumentWithMultipleServersShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDocumentWithMultipleServers.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDocumentWithMultipleServers.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument + { + Info = new OpenApiInfo + { + Title = "The API", + Version = "0.9.1", + }, + Servers = { - Info = new OpenApiInfo + new OpenApiServer { - Title = "The API", - Version = "0.9.1", + Url = new Uri("http://www.example.org/api").ToString(), + Description = "The http endpoint" }, - Servers = + new OpenApiServer { - new OpenApiServer - { - Url = new Uri("http://www.example.org/api").ToString(), - Description = "The http endpoint" - }, - new OpenApiServer - { - Url = new Uri("https://www.example.org/api").ToString(), - Description = "The https endpoint" - } - }, - Paths = new OpenApiPaths() - }); - } + Url = new Uri("https://www.example.org/api").ToString(), + Description = "The https endpoint" + } + }, + Paths = new OpenApiPaths() + }); } [Fact] public void ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "brokenMinimalDocument.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "brokenMinimalDocument.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument + { + Info = new OpenApiInfo { - Info = new OpenApiInfo - { - Version = "0.9" - }, - Paths = new OpenApiPaths() - }); + Version = "0.9" + }, + Paths = new OpenApiPaths() + }); - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic + { + Errors = { - Errors = - { - new OpenApiValidatorError(nameof(OpenApiInfoRules.InfoRequiredFields),"#/info/title", "The field 'title' in 'info' object is REQUIRED.") - }, - SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 - }); - } + new OpenApiValidatorError(nameof(OpenApiInfoRules.InfoRequiredFields),"#/info/title", "The field 'title' in 'info' object is REQUIRED.") + }, + SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 + }); } [Fact] public void ParseMinimalDocumentShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalDocument.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - openApiDoc.Should().BeEquivalentTo( - new OpenApiDocument + openApiDoc.Should().BeEquivalentTo( + new OpenApiDocument + { + Info = new OpenApiInfo { - Info = new OpenApiInfo - { - Title = "Simple Document", - Version = "0.9.1" - }, - Paths = new OpenApiPaths() - }); + Title = "Simple Document", + Version = "0.9.1" + }, + Paths = new OpenApiPaths() + }); - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - } + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] @@ -1249,85 +1235,81 @@ public void ParsePetStoreExpandedShouldSucceed() [Fact] public void GlobalSecurityRequirementShouldReferenceSecurityScheme() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "securedApi.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "securedApi.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - var securityRequirement = openApiDoc.SecurityRequirements.First(); + var securityRequirement = openApiDoc.SecurityRequirements.First(); - Assert.Same(securityRequirement.Keys.First(), openApiDoc.Components.SecuritySchemes.First().Value); - } + Assert.Same(securityRequirement.Keys.First(), openApiDoc.Components.SecuritySchemes.First().Value); } [Fact] public void HeaderParameterShouldAllowExample() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "apiWithFullHeaderComponent.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "apiWithFullHeaderComponent.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - var exampleHeader = openApiDoc.Components?.Headers?["example-header"]; - Assert.NotNull(exampleHeader); - exampleHeader.Should().BeEquivalentTo( - new OpenApiHeader() + var exampleHeader = openApiDoc.Components?.Headers?["example-header"]; + Assert.NotNull(exampleHeader); + exampleHeader.Should().BeEquivalentTo( + new OpenApiHeader() + { + Description = "Test header with example", + Required = true, + Deprecated = true, + AllowEmptyValue = true, + AllowReserved = true, + Style = ParameterStyle.Simple, + Explode = true, + Example = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721"), + Schema = new OpenApiSchema() { - Description = "Test header with example", - Required = true, - Deprecated = true, - AllowEmptyValue = true, - AllowReserved = true, - Style = ParameterStyle.Simple, - Explode = true, - Example = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721"), - Schema = new OpenApiSchema() - { - Type = "string", - Format = "uuid" - }, - Reference = new OpenApiReference() - { - Type = ReferenceType.Header, - Id = "example-header" - } - }); + Type = "string", + Format = "uuid" + }, + Reference = new OpenApiReference() + { + Type = ReferenceType.Header, + Id = "example-header" + } + }); - var examplesHeader = openApiDoc.Components?.Headers?["examples-header"]; - Assert.NotNull(examplesHeader); - examplesHeader.Should().BeEquivalentTo( - new OpenApiHeader() + var examplesHeader = openApiDoc.Components?.Headers?["examples-header"]; + Assert.NotNull(examplesHeader); + examplesHeader.Should().BeEquivalentTo( + new OpenApiHeader() + { + Description = "Test header with example", + Required = true, + Deprecated = true, + AllowEmptyValue = true, + AllowReserved = true, + Style = ParameterStyle.Simple, + Explode = true, + Examples = new Dictionary() { - Description = "Test header with example", - Required = true, - Deprecated = true, - AllowEmptyValue = true, - AllowReserved = true, - Style = ParameterStyle.Simple, - Explode = true, - Examples = new Dictionary() - { - { "uuid1", new OpenApiExample() - { - Value = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721") - } - }, - { "uuid2", new OpenApiExample() - { - Value = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721") - } + { "uuid1", new OpenApiExample() + { + Value = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721") } }, - Schema = new OpenApiSchema() - { - Type = "string", - Format = "uuid" - }, - Reference = new OpenApiReference() - { - Type = ReferenceType.Header, - Id = "examples-header" + { "uuid2", new OpenApiExample() + { + Value = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721") + } } - }); - } + }, + Schema = new OpenApiSchema() + { + Type = "string", + Format = "uuid" + }, + Reference = new OpenApiReference() + { + Type = ReferenceType.Header, + Id = "examples-header" + } + }); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs index 7f33491ff..2d3f7d3b6 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs @@ -20,54 +20,51 @@ public class OpenApiEncodingTests [Fact] public void ParseBasicEncodingShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicEncoding.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicEncoding.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var encoding = OpenApiV3Deserializer.LoadEncoding(node); + // Act + var encoding = OpenApiV3Deserializer.LoadEncoding(node); - // Assert - encoding.Should().BeEquivalentTo( - new OpenApiEncoding - { - ContentType = "application/xml; charset=utf-8" - }); - } + // Assert + encoding.Should().BeEquivalentTo( + new OpenApiEncoding + { + ContentType = "application/xml; charset=utf-8" + }); } [Fact] public void ParseAdvancedEncodingShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedEncoding.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedEncoding.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var encoding = OpenApiV3Deserializer.LoadEncoding(node); + // Act + var encoding = OpenApiV3Deserializer.LoadEncoding(node); - // Assert - encoding.Should().BeEquivalentTo( - new OpenApiEncoding + // Assert + encoding.Should().BeEquivalentTo( + new OpenApiEncoding + { + ContentType = "image/png, image/jpeg", + Headers = { - ContentType = "image/png, image/jpeg", - Headers = - { - ["X-Rate-Limit-Limit"] = + ["X-Rate-Limit-Limit"] = new OpenApiHeader { Description = "The number of allowed requests in the current period", @@ -76,9 +73,8 @@ public void ParseAdvancedEncodingShouldSucceed() Type = "integer" } } - } - }); - } + } + }); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs index ead84f201..68e218408 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs @@ -21,69 +21,65 @@ public class OpenApiExampleTests [Fact] public void ParseAdvancedExampleShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedExample.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedExample.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - var example = OpenApiV3Deserializer.LoadExample(node); + var example = OpenApiV3Deserializer.LoadExample(node); - diagnostic.Errors.Should().BeEmpty(); + diagnostic.Errors.Should().BeEmpty(); - example.Should().BeEquivalentTo( - new OpenApiExample + example.Should().BeEquivalentTo( + new OpenApiExample + { + Value = new OpenApiObject { - Value = new OpenApiObject + ["versions"] = new OpenApiArray { - ["versions"] = new OpenApiArray + new OpenApiObject { - new OpenApiObject + ["status"] = new OpenApiString("Status1"), + ["id"] = new OpenApiString("v1"), + ["links"] = new OpenApiArray { - ["status"] = new OpenApiString("Status1"), - ["id"] = new OpenApiString("v1"), - ["links"] = new OpenApiArray + new OpenApiObject { - new OpenApiObject - { - ["href"] = new OpenApiString("http://example.com/1"), - ["rel"] = new OpenApiString("sampleRel1") - } + ["href"] = new OpenApiString("http://example.com/1"), + ["rel"] = new OpenApiString("sampleRel1") } - }, + } + }, - new OpenApiObject + new OpenApiObject + { + ["status"] = new OpenApiString("Status2"), + ["id"] = new OpenApiString("v2"), + ["links"] = new OpenApiArray { - ["status"] = new OpenApiString("Status2"), - ["id"] = new OpenApiString("v2"), - ["links"] = new OpenApiArray + new OpenApiObject { - new OpenApiObject - { - ["href"] = new OpenApiString("http://example.com/2"), - ["rel"] = new OpenApiString("sampleRel2") - } + ["href"] = new OpenApiString("http://example.com/2"), + ["rel"] = new OpenApiString("sampleRel2") } } } } - }); - } + } + }); } [Fact] public void ParseExampleForcedStringSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "explicitString.yaml"))) - { - new OpenApiStreamReader().Read(stream, out var diagnostic); - diagnostic.Errors.Should().BeEmpty(); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "explicitString.yaml")); + new OpenApiStreamReader().Read(stream, out var diagnostic); + diagnostic.Errors.Should().BeEmpty(); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs index 29b23cb31..29852898f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs @@ -22,128 +22,122 @@ public class OpenApiInfoTests [Fact] public void ParseAdvancedInfoShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedInfo.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; - - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)yamlNode); - - // Act - var openApiInfo = OpenApiV3Deserializer.LoadInfo(node); - - // Assert - openApiInfo.Should().BeEquivalentTo( - new OpenApiInfo + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedInfo.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; + + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)yamlNode); + + // Act + var openApiInfo = OpenApiV3Deserializer.LoadInfo(node); + + // Assert + openApiInfo.Should().BeEquivalentTo( + new OpenApiInfo + { + Title = "Advanced Info", + Description = "Sample Description", + Version = "1.0.0", + TermsOfService = new Uri("http://example.org/termsOfService"), + Contact = new OpenApiContact { - Title = "Advanced Info", - Description = "Sample Description", - Version = "1.0.0", - TermsOfService = new Uri("http://example.org/termsOfService"), - Contact = new OpenApiContact + Email = "example@example.com", + Extensions = { - Email = "example@example.com", - Extensions = - { - ["x-twitter"] = new OpenApiString("@exampleTwitterHandler") - }, - Name = "John Doe", - Url = new Uri("http://www.example.com/url1") + ["x-twitter"] = new OpenApiString("@exampleTwitterHandler") }, - License = new OpenApiLicense + Name = "John Doe", + Url = new Uri("http://www.example.com/url1") + }, + License = new OpenApiLicense + { + Extensions = { ["x-disclaimer"] = new OpenApiString("Sample Extension String Disclaimer") }, + Name = "licenseName", + Url = new Uri("http://www.example.com/url2") + }, + Extensions = + { + ["x-something"] = new OpenApiString("Sample Extension String Something"), + ["x-contact"] = new OpenApiObject { - Extensions = { ["x-disclaimer"] = new OpenApiString("Sample Extension String Disclaimer") }, - Name = "licenseName", - Url = new Uri("http://www.example.com/url2") + ["name"] = new OpenApiString("John Doe"), + ["url"] = new OpenApiString("http://www.example.com/url3"), + ["email"] = new OpenApiString("example@example.com") }, - Extensions = + ["x-list"] = new OpenApiArray { - ["x-something"] = new OpenApiString("Sample Extension String Something"), - ["x-contact"] = new OpenApiObject - { - ["name"] = new OpenApiString("John Doe"), - ["url"] = new OpenApiString("http://www.example.com/url3"), - ["email"] = new OpenApiString("example@example.com") - }, - ["x-list"] = new OpenApiArray - { - new OpenApiString("1"), - new OpenApiString("2") - } + new OpenApiString("1"), + new OpenApiString("2") } - }); - } + } + }); } [Fact] public void ParseBasicInfoShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicInfo.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; - - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)yamlNode); - - // Act - var openApiInfo = OpenApiV3Deserializer.LoadInfo(node); - - // Assert - openApiInfo.Should().BeEquivalentTo( - new OpenApiInfo + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicInfo.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; + + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)yamlNode); + + // Act + var openApiInfo = OpenApiV3Deserializer.LoadInfo(node); + + // Assert + openApiInfo.Should().BeEquivalentTo( + new OpenApiInfo + { + Title = "Basic Info", + Description = "Sample Description", + Version = "1.0.1", + TermsOfService = new Uri("http://swagger.io/terms/"), + Contact = new OpenApiContact { - Title = "Basic Info", - Description = "Sample Description", - Version = "1.0.1", - TermsOfService = new Uri("http://swagger.io/terms/"), - Contact = new OpenApiContact - { - Email = "support@swagger.io", - Name = "API Support", - Url = new Uri("http://www.swagger.io/support") - }, - License = new OpenApiLicense - { - Name = "Apache 2.0", - Url = new Uri("http://www.apache.org/licenses/LICENSE-2.0.html") - } - }); - } + Email = "support@swagger.io", + Name = "API Support", + Url = new Uri("http://www.swagger.io/support") + }, + License = new OpenApiLicense + { + Name = "Apache 2.0", + Url = new Uri("http://www.apache.org/licenses/LICENSE-2.0.html") + } + }); } [Fact] public void ParseMinimalInfoShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalInfo.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; - - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)yamlNode); - - // Act - var openApiInfo = OpenApiV3Deserializer.LoadInfo(node); - - // Assert - openApiInfo.Should().BeEquivalentTo( - new OpenApiInfo - { - Title = "Minimal Info", - Version = "1.0.1" - }); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalInfo.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; + + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)yamlNode); + + // Act + var openApiInfo = OpenApiV3Deserializer.LoadInfo(node); + + // Assert + openApiInfo.Should().BeEquivalentTo( + new OpenApiInfo + { + Title = "Minimal Info", + Version = "1.0.1" + }); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs index a74c64154..836181532 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs @@ -18,14 +18,12 @@ public class OpenApiOperationTests [Fact] public void OperationWithSecurityRequirementShouldReferenceSecurityScheme() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "securedOperation.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "securedOperation.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - var securityRequirement = openApiDoc.Paths["/"].Operations[Models.OperationType.Get].Security.First(); + var securityRequirement = openApiDoc.Paths["/"].Operations[Models.OperationType.Get].Security.First(); - Assert.Same(securityRequirement.Keys.First(), openApiDoc.Components.SecuritySchemes.First().Value); - } + Assert.Same(securityRequirement.Keys.First(), openApiDoc.Components.SecuritySchemes.First().Value); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs index 60e3db6e4..c0768f7df 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs @@ -20,14 +20,12 @@ public class OpenApiResponseTests [Fact] public void ResponseWithReferencedHeaderShouldReferenceComponent() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "responseWithHeaderReference.yaml"))) - { - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "responseWithHeaderReference.yaml")); + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - var response = openApiDoc.Components.Responses["Test"]; + var response = openApiDoc.Components.Responses["Test"]; - Assert.Same(response.Headers.First().Value, openApiDoc.Components.Headers.First().Value); - } + Assert.Same(response.Headers.First().Value, openApiDoc.Components.Headers.First().Value); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index 0101d9c6e..a381864ac 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -22,53 +22,49 @@ public class OpenApiSchemaTests [Fact] public void ParsePrimitiveSchemaShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "primitiveSchema.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "primitiveSchema.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var schema = OpenApiV3Deserializer.LoadSchema(node); + // Act + var schema = OpenApiV3Deserializer.LoadSchema(node); - // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - schema.Should().BeEquivalentTo( - new OpenApiSchema - { - Type = "string", - Format = "email" - }); - } + schema.Should().BeEquivalentTo( + new OpenApiSchema + { + Type = "string", + Format = "email" + }); } [Fact] public void ParsePrimitiveSchemaFragmentShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "primitiveSchema.yaml"))) - { - var reader = new OpenApiStreamReader(); - var diagnostic = new OpenApiDiagnostic(); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "primitiveSchema.yaml")); + var reader = new OpenApiStreamReader(); + var diagnostic = new OpenApiDiagnostic(); - // Act - var schema = reader.ReadFragment(stream, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + // Act + var schema = reader.ReadFragment(stream, OpenApiSpecVersion.OpenApi3_0, out diagnostic); - // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - schema.Should().BeEquivalentTo( - new OpenApiSchema - { - Type = "string", - Format = "email" - }); - } + schema.Should().BeEquivalentTo( + new OpenApiSchema + { + Type = "string", + Format = "email" + }); } [Fact] @@ -154,51 +150,49 @@ public void ParseEnumFragmentShouldSucceed() [Fact] public void ParseSimpleSchemaShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "simpleSchema.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "simpleSchema.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var schema = OpenApiV3Deserializer.LoadSchema(node); + // Act + var schema = OpenApiV3Deserializer.LoadSchema(node); - // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - schema.Should().BeEquivalentTo( - new OpenApiSchema + schema.Should().BeEquivalentTo( + new OpenApiSchema + { + Type = "object", + Required = { - Type = "object", - Required = + "name" + }, + Properties = + { + ["name"] = new OpenApiSchema { - "name" + Type = "string" }, - Properties = + ["address"] = new OpenApiSchema { - ["name"] = new OpenApiSchema - { - Type = "string" - }, - ["address"] = new OpenApiSchema - { - Type = "string" - }, - ["age"] = new OpenApiSchema - { - Type = "integer", - Format = "int32", - Minimum = 0 - } + Type = "string" }, - AdditionalPropertiesAllowed = false - }); - } + ["age"] = new OpenApiSchema + { + Type = "integer", + Format = "int32", + Minimum = 0 + } + }, + AdditionalPropertiesAllowed = false + }); } [Fact] @@ -243,416 +237,406 @@ public void ParsePathFragmentShouldSucceed() [Fact] public void ParseDictionarySchemaShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "dictionarySchema.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "dictionarySchema.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var schema = OpenApiV3Deserializer.LoadSchema(node); + // Act + var schema = OpenApiV3Deserializer.LoadSchema(node); - // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - schema.Should().BeEquivalentTo( - new OpenApiSchema + schema.Should().BeEquivalentTo( + new OpenApiSchema + { + Type = "object", + AdditionalProperties = new OpenApiSchema { - Type = "object", - AdditionalProperties = new OpenApiSchema - { - Type = "string" - } - }); - } + Type = "string" + } + }); } [Fact] public void ParseBasicSchemaWithExampleShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicSchemaWithExample.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicSchemaWithExample.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var schema = OpenApiV3Deserializer.LoadSchema(node); + // Act + var schema = OpenApiV3Deserializer.LoadSchema(node); - // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); + // Assert + diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - schema.Should().BeEquivalentTo( - new OpenApiSchema + schema.Should().BeEquivalentTo( + new OpenApiSchema + { + Type = "object", + Properties = { - Type = "object", - Properties = - { - ["id"] = new OpenApiSchema - { - Type = "integer", - Format = "int64" - }, - ["name"] = new OpenApiSchema - { - Type = "string" - } - }, - Required = + ["id"] = new OpenApiSchema { - "name" + Type = "integer", + Format = "int64" }, - Example = new OpenApiObject + ["name"] = new OpenApiSchema { - ["name"] = new OpenApiString("Puma"), - ["id"] = new OpenApiLong(1) + Type = "string" } - }); - } + }, + Required = + { + "name" + }, + Example = new OpenApiObject + { + ["name"] = new OpenApiString("Puma"), + ["id"] = new OpenApiLong(1) + } + }); } [Fact] public void ParseBasicSchemaWithReferenceShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicSchemaWithReference.yaml"))) - { - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicSchemaWithReference.yaml")); + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - // Assert - var components = openApiDoc.Components; + // Assert + var components = openApiDoc.Components; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - components.Should().BeEquivalentTo( - new OpenApiComponents + components.Should().BeEquivalentTo( + new OpenApiComponents + { + Schemas = { - Schemas = + ["ErrorModel"] = new OpenApiSchema { - ["ErrorModel"] = new OpenApiSchema + Type = "object", + Properties = { - Type = "object", - Properties = + ["code"] = new OpenApiSchema { - ["code"] = new OpenApiSchema - { - Type = "integer", - Minimum = 100, - Maximum = 600 - }, - ["message"] = new OpenApiSchema - { - Type = "string" - } + Type = "integer", + Minimum = 100, + Maximum = 600 }, - Reference = new OpenApiReference + ["message"] = new OpenApiSchema { - Type = ReferenceType.Schema, - Id = "ErrorModel", - HostDocument = openApiDoc - }, - Required = - { - "message", - "code" + Type = "string" } }, - ["ExtendedErrorModel"] = new OpenApiSchema + Reference = new OpenApiReference { - Reference = new OpenApiReference - { - Type = ReferenceType.Schema, - Id = "ExtendedErrorModel", - HostDocument = openApiDoc - }, - AllOf = + Type = ReferenceType.Schema, + Id = "ErrorModel", + HostDocument = openApiDoc + }, + Required = + { + "message", + "code" + } + }, + ["ExtendedErrorModel"] = new OpenApiSchema + { + Reference = new OpenApiReference + { + Type = ReferenceType.Schema, + Id = "ExtendedErrorModel", + HostDocument = openApiDoc + }, + AllOf = + { + new OpenApiSchema { - new OpenApiSchema + Reference = new OpenApiReference { - Reference = new OpenApiReference - { - Type = ReferenceType.Schema, - Id = "ErrorModel", - HostDocument = openApiDoc - }, - // Schema should be dereferenced in our model, so all the properties - // from the ErrorModel above should be propagated here. - Type = "object", - Properties = + Type = ReferenceType.Schema, + Id = "ErrorModel", + HostDocument = openApiDoc + }, + // Schema should be dereferenced in our model, so all the properties + // from the ErrorModel above should be propagated here. + Type = "object", + Properties = + { + ["code"] = new OpenApiSchema { - ["code"] = new OpenApiSchema - { - Type = "integer", - Minimum = 100, - Maximum = 600 - }, - ["message"] = new OpenApiSchema - { - Type = "string" - } + Type = "integer", + Minimum = 100, + Maximum = 600 }, - Required = + ["message"] = new OpenApiSchema { - "message", - "code" + Type = "string" } }, - new OpenApiSchema + Required = + { + "message", + "code" + } + }, + new OpenApiSchema + { + Type = "object", + Required = {"rootCause"}, + Properties = { - Type = "object", - Required = {"rootCause"}, - Properties = + ["rootCause"] = new OpenApiSchema { - ["rootCause"] = new OpenApiSchema - { - Type = "string" - } + Type = "string" } } } } } - }, options => options.Excluding(m => m.Name == "HostDocument")); - } + } + }, options => options.Excluding(m => m.Name == "HostDocument")); } [Fact] public void ParseAdvancedSchemaWithReferenceShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedSchemaWithReference.yaml"))) - { - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedSchemaWithReference.yaml")); + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - // Assert - var components = openApiDoc.Components; + // Assert + var components = openApiDoc.Components; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - components.Should().BeEquivalentTo( - new OpenApiComponents + components.Should().BeEquivalentTo( + new OpenApiComponents + { + Schemas = { - Schemas = + ["Pet"] = new OpenApiSchema { - ["Pet"] = new OpenApiSchema + Type = "object", + Discriminator = new OpenApiDiscriminator { - Type = "object", - Discriminator = new OpenApiDiscriminator - { - PropertyName = "petType" - }, - Properties = - { - ["name"] = new OpenApiSchema - { - Type = "string" - }, - ["petType"] = new OpenApiSchema - { - Type = "string" - } - }, - Required = + PropertyName = "petType" + }, + Properties = + { + ["name"] = new OpenApiSchema { - "name", - "petType" + Type = "string" }, - Reference = new OpenApiReference() + ["petType"] = new OpenApiSchema { - Id= "Pet", - Type = ReferenceType.Schema, - HostDocument = openApiDoc + Type = "string" } }, - ["Cat"] = new OpenApiSchema + Required = + { + "name", + "petType" + }, + Reference = new OpenApiReference() { - Description = "A representation of a cat", - AllOf = + Id= "Pet", + Type = ReferenceType.Schema, + HostDocument = openApiDoc + } + }, + ["Cat"] = new OpenApiSchema + { + Description = "A representation of a cat", + AllOf = + { + new OpenApiSchema { - new OpenApiSchema + Reference = new OpenApiReference { - Reference = new OpenApiReference - { - Type = ReferenceType.Schema, - Id = "Pet", - HostDocument = openApiDoc - }, - // Schema should be dereferenced in our model, so all the properties - // from the Pet above should be propagated here. - Type = "object", - Discriminator = new OpenApiDiscriminator - { - PropertyName = "petType" - }, - Properties = + Type = ReferenceType.Schema, + Id = "Pet", + HostDocument = openApiDoc + }, + // Schema should be dereferenced in our model, so all the properties + // from the Pet above should be propagated here. + Type = "object", + Discriminator = new OpenApiDiscriminator + { + PropertyName = "petType" + }, + Properties = + { + ["name"] = new OpenApiSchema { - ["name"] = new OpenApiSchema - { - Type = "string" - }, - ["petType"] = new OpenApiSchema - { - Type = "string" - } + Type = "string" }, - Required = + ["petType"] = new OpenApiSchema { - "name", - "petType" + Type = "string" } }, - new OpenApiSchema + Required = + { + "name", + "petType" + } + }, + new OpenApiSchema + { + Type = "object", + Required = {"huntingSkill"}, + Properties = { - Type = "object", - Required = {"huntingSkill"}, - Properties = + ["huntingSkill"] = new OpenApiSchema { - ["huntingSkill"] = new OpenApiSchema + Type = "string", + Description = "The measured skill for hunting", + Enum = { - Type = "string", - Description = "The measured skill for hunting", - Enum = - { - new OpenApiString("clueless"), - new OpenApiString("lazy"), - new OpenApiString("adventurous"), - new OpenApiString("aggressive") - } + new OpenApiString("clueless"), + new OpenApiString("lazy"), + new OpenApiString("adventurous"), + new OpenApiString("aggressive") } } } - }, - Reference = new OpenApiReference() - { - Id= "Cat", - Type = ReferenceType.Schema, - HostDocument = openApiDoc } }, - ["Dog"] = new OpenApiSchema + Reference = new OpenApiReference() + { + Id= "Cat", + Type = ReferenceType.Schema, + HostDocument = openApiDoc + } + }, + ["Dog"] = new OpenApiSchema + { + Description = "A representation of a dog", + AllOf = { - Description = "A representation of a dog", - AllOf = + new OpenApiSchema { - new OpenApiSchema + Reference = new OpenApiReference { - Reference = new OpenApiReference - { - Type = ReferenceType.Schema, - Id = "Pet", - HostDocument = openApiDoc - }, - // Schema should be dereferenced in our model, so all the properties - // from the Pet above should be propagated here. - Type = "object", - Discriminator = new OpenApiDiscriminator - { - PropertyName = "petType" - }, - Properties = + Type = ReferenceType.Schema, + Id = "Pet", + HostDocument = openApiDoc + }, + // Schema should be dereferenced in our model, so all the properties + // from the Pet above should be propagated here. + Type = "object", + Discriminator = new OpenApiDiscriminator + { + PropertyName = "petType" + }, + Properties = + { + ["name"] = new OpenApiSchema { - ["name"] = new OpenApiSchema - { - Type = "string" - }, - ["petType"] = new OpenApiSchema - { - Type = "string" - } + Type = "string" }, - Required = + ["petType"] = new OpenApiSchema { - "name", - "petType" + Type = "string" } }, - new OpenApiSchema + Required = { - Type = "object", - Required = {"packSize"}, - Properties = - { - ["packSize"] = new OpenApiSchema - { - Type = "integer", - Format = "int32", - Description = "the size of the pack the dog is from", - Default = new OpenApiInteger(0), - Minimum = 0 - } - } + "name", + "petType" } }, - Reference = new OpenApiReference() + new OpenApiSchema { - Id= "Dog", - Type = ReferenceType.Schema, - HostDocument = openApiDoc + Type = "object", + Required = {"packSize"}, + Properties = + { + ["packSize"] = new OpenApiSchema + { + Type = "integer", + Format = "int32", + Description = "the size of the pack the dog is from", + Default = new OpenApiInteger(0), + Minimum = 0 + } + } } + }, + Reference = new OpenApiReference() + { + Id= "Dog", + Type = ReferenceType.Schema, + HostDocument = openApiDoc } } - }, options => options.Excluding(m => m.Name == "HostDocument")); - } + } + }, options => options.Excluding(m => m.Name == "HostDocument")); } [Fact] public void ParseSelfReferencingSchemaShouldNotStackOverflow() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "selfReferencingSchema.yaml"))) - { - // Act - var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "selfReferencingSchema.yaml")); + // Act + var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - // Assert - var components = openApiDoc.Components; + // Assert + var components = openApiDoc.Components; - diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + diagnostic.Should().BeEquivalentTo( + new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - var schemaExtension = new OpenApiSchema() - { - AllOf = { new OpenApiSchema() + var schemaExtension = new OpenApiSchema() + { + AllOf = { new OpenApiSchema() { Title = "schemaExtension", Type = "object", Properties = { - ["description"] = new OpenApiSchema() { Type = "string", Nullable = true}, - ["targetTypes"] = new OpenApiSchema() { - Type = "array", - Items = new OpenApiSchema() { - Type = "string" - } - }, - ["status"] = new OpenApiSchema() { Type = "string"}, - ["owner"] = new OpenApiSchema() { Type = "string"}, - ["child"] = null - } + ["description"] = new OpenApiSchema() { Type = "string", Nullable = true}, + ["targetTypes"] = new OpenApiSchema() { + Type = "array", + Items = new OpenApiSchema() { + Type = "string" + } + }, + ["status"] = new OpenApiSchema() { Type = "string"}, + ["owner"] = new OpenApiSchema() { Type = "string"}, + ["child"] = null } - }, - Reference = new OpenApiReference() - { - Type = ReferenceType.Schema, - Id = "microsoft.graph.schemaExtension" } - }; + }, + Reference = new OpenApiReference() + { + Type = ReferenceType.Schema, + Id = "microsoft.graph.schemaExtension" + } + }; - schemaExtension.AllOf[0].Properties["child"] = schemaExtension; + schemaExtension.AllOf[0].Properties["child"] = schemaExtension; - components.Schemas["microsoft.graph.schemaExtension"].Should().BeEquivalentTo(components.Schemas["microsoft.graph.schemaExtension"].AllOf[0].Properties["child"]); - } + components.Schemas["microsoft.graph.schemaExtension"].Should().BeEquivalentTo(components.Schemas["microsoft.graph.schemaExtension"].AllOf[0].Properties["child"]); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs index 9d7a27d72..6992e68f5 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs @@ -21,150 +21,140 @@ public class OpenApiSecuritySchemeTests [Fact] public void ParseHttpSecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "httpSecurityScheme.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; - - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)yamlNode); - - // Act - var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); - - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme - { - Type = SecuritySchemeType.Http, - Scheme = OpenApiConstants.Basic - }); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "httpSecurityScheme.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; + + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)yamlNode); + + // Act + var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); + + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.Http, + Scheme = OpenApiConstants.Basic + }); } [Fact] public void ParseApiKeySecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "apiKeySecurityScheme.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; - - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)yamlNode); - - // Act - var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); - - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme - { - Type = SecuritySchemeType.ApiKey, - Name = "api_key", - In = ParameterLocation.Header - }); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "apiKeySecurityScheme.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; + + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)yamlNode); + + // Act + var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); + + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.ApiKey, + Name = "api_key", + In = ParameterLocation.Header + }); } [Fact] public void ParseBearerSecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "bearerSecurityScheme.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; - - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)yamlNode); - - // Act - var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); - - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme - { - Type = SecuritySchemeType.Http, - Scheme = OpenApiConstants.Bearer, - BearerFormat = OpenApiConstants.Jwt - }); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "bearerSecurityScheme.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; + + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)yamlNode); + + // Act + var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); + + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.Http, + Scheme = OpenApiConstants.Bearer, + BearerFormat = OpenApiConstants.Jwt + }); } [Fact] public void ParseOAuth2SecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2SecurityScheme.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2SecurityScheme.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); + // Act + var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Implicit = new OpenApiOAuthFlow { - Implicit = new OpenApiOAuthFlow + AuthorizationUrl = new Uri("https://example.com/api/oauth/dialog"), + Scopes = { - AuthorizationUrl = new Uri("https://example.com/api/oauth/dialog"), - Scopes = - { - ["write:pets"] = "modify pets in your account", - ["read:pets"] = "read your pets" - } + ["write:pets"] = "modify pets in your account", + ["read:pets"] = "read your pets" } } - }); - } + } + }); } [Fact] public void ParseOpenIdConnectSecuritySchemeShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "openIdConnectSecurityScheme.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; - - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); - - var node = new MapNode(context, (YamlMappingNode)yamlNode); - - // Act - var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); - - // Assert - securityScheme.Should().BeEquivalentTo( - new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OpenIdConnect, - Description = "Sample Description", - OpenIdConnectUrl = new Uri("http://www.example.com") - }); - } + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "openIdConnectSecurityScheme.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; + + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); + + var node = new MapNode(context, (YamlMappingNode)yamlNode); + + // Act + var securityScheme = OpenApiV3Deserializer.LoadSecurityScheme(node); + + // Assert + securityScheme.Should().BeEquivalentTo( + new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OpenIdConnect, + Description = "Sample Description", + OpenIdConnectUrl = new Uri("http://www.example.com") + }); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs index a10d674a9..19e411e15 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs @@ -21,30 +21,28 @@ public class OpenApiXmlTests [Fact] public void ParseBasicXmlShouldSucceed() { - using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicXml.yaml"))) - { - var yamlStream = new YamlStream(); - yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicXml.yaml")); + var yamlStream = new YamlStream(); + yamlStream.Load(new StreamReader(stream)); + var yamlNode = yamlStream.Documents.First().RootNode; - var diagnostic = new OpenApiDiagnostic(); - var context = new ParsingContext(diagnostic); + var diagnostic = new OpenApiDiagnostic(); + var context = new ParsingContext(diagnostic); - var node = new MapNode(context, (YamlMappingNode)yamlNode); + var node = new MapNode(context, (YamlMappingNode)yamlNode); - // Act - var xml = OpenApiV3Deserializer.LoadXml(node); + // Act + var xml = OpenApiV3Deserializer.LoadXml(node); - // Assert - xml.Should().BeEquivalentTo( - new OpenApiXml - { - Name = "name1", - Namespace = new Uri("http://example.com/schema/namespaceSample"), - Prefix = "samplePrefix", - Wrapped = true - }); - } + // Assert + xml.Should().BeEquivalentTo( + new OpenApiXml + { + Name = "name1", + Namespace = new Uri("http://example.com/schema/namespaceSample"), + Prefix = "samplePrefix", + Wrapped = true + }); } } } From 4b341a04bfcba7242eb7ca424c3ba1e97ee381e5 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:18:24 +1100 Subject: [PATCH 641/855] remove some redundant braces --- .../Formatters/PowerShellFormatter.cs | 2 +- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 4 +- src/Microsoft.OpenApi.Hidi/Program.cs | 2 +- .../OpenApiYamlDocumentReader.cs | 4 +- .../ParseNodes/MapNode.cs | 4 +- .../V2/OpenApiDocumentDeserializer.cs | 6 +- .../V2/OpenApiOperationDeserializer.cs | 4 +- .../V2/OpenApiPathItemDeserializer.cs | 2 +- .../OpenApiSecurityRequirementDeserializer.cs | 4 +- .../V3/OpenApiDocumentDeserializer.cs | 2 +- .../V3/OpenApiOperationDeserializer.cs | 4 +- .../V3/OpenApiPathItemDeserializer.cs | 2 +- .../V3/OpenApiSchemaDeserializer.cs | 2 +- .../OpenApiSecurityRequirementDeserializer.cs | 4 +- src/Microsoft.OpenApi.Workbench/MainModel.cs | 3 +- .../OpenApiPrimaryErrorMessageExtension.cs | 3 +- .../Services/OpenApiReferenceResolver.cs | 4 +- .../Services/OperationSearch.cs | 2 +- .../Formatters/PowerShellFormatterTests.cs | 15 +- .../Services/OpenApiFilterServiceTests.cs | 7 +- .../Services/OpenApiServiceTests.cs | 6 +- .../UtilityFiles/OpenApiDocumentMock.cs | 134 +++++++++--------- .../OpenApiDiagnosticTests.cs | 2 +- .../OpenApiWorkspaceStreamTests.cs | 4 +- .../ParseNodeTests.cs | 6 +- .../ParseNodes/OpenApiAnyConverterTests.cs | 128 ++++++++--------- .../TryLoadReferenceV2Tests.cs | 4 +- .../TestCustomExtension.cs | 5 +- .../V2Tests/OpenApiDocumentTests.cs | 26 ++-- .../V2Tests/OpenApiHeaderTests.cs | 4 +- .../V2Tests/OpenApiOperationTests.cs | 30 ++-- .../V2Tests/OpenApiParameterTests.cs | 18 +-- .../V2Tests/OpenApiPathItemTests.cs | 8 +- .../V2Tests/OpenApiServerTests.cs | 26 ++-- .../V3Tests/OpenApiCallbackTests.cs | 20 +-- .../V3Tests/OpenApiDocumentTests.cs | 46 +++--- .../V3Tests/OpenApiMediaTypeTests.cs | 4 +- .../V3Tests/OpenApiOperationTests.cs | 4 +- .../V3Tests/OpenApiParameterTests.cs | 4 +- .../V3Tests/OpenApiSchemaTests.cs | 37 ++--- test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs | 2 +- .../GraphTests.cs | 2 +- .../Expressions/RuntimeExpressionTests.cs | 4 +- .../Models/OpenApiComponentsTests.cs | 18 +-- .../Models/OpenApiDocumentTests.cs | 61 ++++---- .../Models/OpenApiOperationTests.cs | 36 ++--- .../Models/OpenApiSchemaTests.cs | 8 +- .../PublicApi/PublicApiTests.cs | 2 +- .../Services/OpenApiUrlTreeNodeTests.cs | 69 ++++----- .../Services/OpenApiValidatorTests.cs | 8 +- .../OpenApiComponentsValidationTests.cs | 2 +- .../OpenApiContactValidationTests.cs | 2 +- .../OpenApiHeaderValidationTests.cs | 26 ++-- .../OpenApiMediaTypeValidationTests.cs | 26 ++-- .../OpenApiParameterValidationTests.cs | 36 ++--- .../OpenApiReferenceValidationTests.cs | 48 +++---- .../OpenApiSchemaValidationTests.cs | 38 ++--- .../Walkers/WalkerLocationTests.cs | 63 ++++---- .../Workspaces/OpenApiReferencableTests.cs | 4 +- .../Workspaces/OpenApiWorkspaceTests.cs | 49 ++++--- .../Writers/OpenApiYamlWriterTests.cs | 30 ++-- 61 files changed, 578 insertions(+), 552 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs index 450a05d21..4db55a05e 100644 --- a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs +++ b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs @@ -179,7 +179,7 @@ private void AddAdditionalPropertiesToSchema(OpenApiSchema schema) { if (schema != null && !_schemaLoop.Contains(schema) && "object".Equals(schema.Type, StringComparison.OrdinalIgnoreCase)) { - schema.AdditionalProperties = new OpenApiSchema() { Type = "object" }; + schema.AdditionalProperties = new OpenApiSchema { Type = "object" }; /* Because 'additionalProperties' are now being walked, * we need a way to keep track of visited schemas to avoid diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index b3e66cfe2..63a8bbb94 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -186,7 +186,7 @@ private static void WriteOpenApi(HidiOptions options, OpenApiFormat openApiForma using var outputStream = options.Output.Create(); using var textWriter = new StreamWriter(outputStream); - var settings = new OpenApiWriterSettings() + var settings = new OpenApiWriterSettings { InlineLocalReferences = options.InlineLocal, InlineExternalReferences = options.InlineExternal @@ -738,7 +738,7 @@ internal static async Task PluginManifest(HidiOptions options, ILogger logger, C WriteOpenApi(options, OpenApiFormat.Json, OpenApiSpecVersion.OpenApi3_0, document, logger); // Create OpenAIPluginManifest from ApiDependency and OpenAPI document - var manifest = new OpenAIPluginManifest() + var manifest = new OpenAIPluginManifest { NameForHuman = document.Info.Title, DescriptionForHuman = document.Info.Description, diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index b8508ab5f..faf09352f 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -22,7 +22,7 @@ static async Task Main(string[] args) internal static RootCommand CreateRootCommand() { - var rootCommand = new RootCommand() { }; + var rootCommand = new RootCommand { }; var commandOptions = new CommandOptions(); diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 4a120cbbf..5537366d0 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -133,7 +133,7 @@ public async Task ReadAsync(YamlDocument input, CancellationToken ca } } - return new ReadResult() + return new ReadResult { OpenApiDocument = document, OpenApiDiagnostic = diagnostic @@ -148,7 +148,7 @@ private async Task LoadExternalRefs(OpenApiDocument document, // Load this root document into the workspace var streamLoader = new DefaultStreamLoader(_settings.BaseUrl); var workspaceLoader = new OpenApiWorkspaceLoader(openApiWorkSpace, _settings.CustomExternalLoader ?? streamLoader, _settings); - return await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document, cancellationToken); + return await workspaceLoader.LoadAsync(new OpenApiReference { ExternalResource = "/" }, document, cancellationToken); } private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument document) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs index 0ee5934ce..92c49726b 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs @@ -120,7 +120,7 @@ public override Dictionary CreateMapWithReference( // If the component isn't a reference to another component, then point it to itself. if (entry.value.Reference == null) { - entry.value.Reference = new OpenApiReference() + entry.value.Reference = new OpenApiReference { Type = referenceType, Id = entry.key @@ -184,7 +184,7 @@ public override string GetRaw() public T GetReferencedObject(ReferenceType referenceType, string referenceId) where T : IOpenApiReferenceable, new() { - return new T() + return new T { UnresolvedReference = true, Reference = Context.VersionService.ConvertToOpenApiReference(referenceId, referenceType) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index fa3aa7224..806c96877 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -220,7 +220,7 @@ private static string BuildUrl(string scheme, string host, string basePath) port = int.Parse(pieces.Last(), CultureInfo.InvariantCulture); } - var uriBuilder = new UriBuilder() + var uriBuilder = new UriBuilder { Scheme = scheme, Host = host, @@ -327,10 +327,10 @@ public override void Visit(OpenApiOperation operation) if (body != null) { operation.Parameters.Remove(body); - operation.RequestBody = new OpenApiRequestBody() + operation.RequestBody = new OpenApiRequestBody { UnresolvedReference = true, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = body.Reference.Id, Type = ReferenceType.RequestBody diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index 1cf5b7ae8..cf54df8c3 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -221,10 +221,10 @@ private static OpenApiTag LoadTagByReference( ParsingContext context, string tagName) { - var tagObject = new OpenApiTag() + var tagObject = new OpenApiTag { UnresolvedReference = true, - Reference = new OpenApiReference() { Id = tagName, Type = ReferenceType.Tag } + Reference = new OpenApiReference { Id = tagName, Type = ReferenceType.Tag } }; return tagObject; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index d905ea42e..d9db5a8d8 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -20,7 +20,7 @@ internal static partial class OpenApiV2Deserializer { "$ref", (o, n) => { - o.Reference = new OpenApiReference() { ExternalResource = n.GetScalarValue() }; + o.Reference = new OpenApiReference { ExternalResource = n.GetScalarValue() }; o.UnresolvedReference =true; } }, diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs index c5e0776ee..c8384fb05 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs @@ -45,10 +45,10 @@ private static OpenApiSecurityScheme LoadSecuritySchemeByReference( ParsingContext context, string schemeName) { - var securitySchemeObject = new OpenApiSecurityScheme() + var securitySchemeObject = new OpenApiSecurityScheme { UnresolvedReference = true, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = schemeName, Type = ReferenceType.SecurityScheme diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs index df1434cd9..d5c437148 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs @@ -30,7 +30,7 @@ internal static partial class OpenApiV3Deserializer {"tags", (o, n) => {o.Tags = n.CreateList(LoadTag); foreach (var tag in o.Tags) { - tag.Reference = new OpenApiReference() + tag.Reference = new OpenApiReference { Id = tag.Name, Type = ReferenceType.Tag diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs index 16f7a16f4..d6cd2e387 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs @@ -112,10 +112,10 @@ private static OpenApiTag LoadTagByReference( ParsingContext context, string tagName) { - var tagObject = new OpenApiTag() + var tagObject = new OpenApiTag { UnresolvedReference = true, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Tag, Id = tagName diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs index 371e7da80..698fe64cc 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs @@ -18,7 +18,7 @@ internal static partial class OpenApiV3Deserializer { "$ref", (o,n) => { - o.Reference = new OpenApiReference() { ExternalResource = n.GetScalarValue() }; + o.Reference = new OpenApiReference { ExternalResource = n.GetScalarValue() }; o.UnresolvedReference =true; } }, diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs index 60727c4bb..e5482e22f 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs @@ -280,7 +280,7 @@ public static OpenApiSchema LoadSchema(ParseNode node) if (pointer != null) { - return new OpenApiSchema() + return new OpenApiSchema { UnresolvedReference = true, Reference = node.Context.VersionService.ConvertToOpenApiReference(pointer, ReferenceType.Schema) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs index b6b80cf7b..ed8322622 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs @@ -44,10 +44,10 @@ private static OpenApiSecurityScheme LoadSecuritySchemeByReference( ParsingContext context, string schemeName) { - var securitySchemeObject = new OpenApiSecurityScheme() + var securitySchemeObject = new OpenApiSecurityScheme { UnresolvedReference = true, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = schemeName, Type = ReferenceType.SecurityScheme diff --git a/src/Microsoft.OpenApi.Workbench/MainModel.cs b/src/Microsoft.OpenApi.Workbench/MainModel.cs index 70074736b..0d0d689ec 100644 --- a/src/Microsoft.OpenApi.Workbench/MainModel.cs +++ b/src/Microsoft.OpenApi.Workbench/MainModel.cs @@ -313,7 +313,8 @@ private string WriteContents(OpenApiDocument document) outputStream, Version, Format, - new OpenApiWriterSettings() { + new OpenApiWriterSettings + { InlineLocalReferences = InlineLocal, InlineExternalReferences = InlineExternal }); diff --git a/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtension.cs b/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtension.cs index adcaa85dd..9a92e0d6e 100644 --- a/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtension.cs +++ b/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtension.cs @@ -37,7 +37,8 @@ public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) public static OpenApiPrimaryErrorMessageExtension Parse(IOpenApiAny source) { if (source is not OpenApiBoolean rawObject) throw new ArgumentOutOfRangeException(nameof(source)); - return new OpenApiPrimaryErrorMessageExtension() { + return new OpenApiPrimaryErrorMessageExtension + { IsPrimaryErrorMessage = rawObject.Value }; } diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index 3b431d4b5..dc0fb1c8d 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -206,7 +206,7 @@ private void ResolveTags(IList tags) if (resolvedTag == null) { - resolvedTag = new OpenApiTag() + resolvedTag = new OpenApiTag { Name = tag.Reference.Id }; @@ -291,7 +291,7 @@ private void ResolveTags(IList tags) else { // Leave as unresolved reference - return new T() + return new T { UnresolvedReference = true, Reference = reference diff --git a/src/Microsoft.OpenApi/Services/OperationSearch.cs b/src/Microsoft.OpenApi/Services/OperationSearch.cs index 90e88cc70..8d251ec71 100644 --- a/src/Microsoft.OpenApi/Services/OperationSearch.cs +++ b/src/Microsoft.OpenApi/Services/OperationSearch.cs @@ -43,7 +43,7 @@ public override void Visit(OpenApiPathItem pathItem) if (_predicate(CurrentKeys.Path, operationType, operation)) { - _searchResults.Add(new SearchResult() + _searchResults.Add(new SearchResult { Operation = operation, Parameters = pathItem.Parameters, diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Formatters/PowerShellFormatterTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Formatters/PowerShellFormatterTests.cs index a22348897..c261a8e46 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Formatters/PowerShellFormatterTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Formatters/PowerShellFormatterTests.cs @@ -21,14 +21,15 @@ public class PowerShellFormatterTests public void FormatOperationIdsInOpenAPIDocument(string operationId, string expectedOperationId, OperationType operationType, string path = "/foo") { // Arrange - var openApiDocument = new OpenApiDocument() + var openApiDocument = new OpenApiDocument { Info = new() { Title = "Test", Version = "1.0" }, - Servers = new List() { new() { Url = "https://localhost/" } }, + Servers = new List { new() { Url = "https://localhost/" } }, Paths = new() { { path, new() { - Operations = new Dictionary() { + Operations = new Dictionary + { { operationType, new() { OperationId = operationId } } } } @@ -92,14 +93,14 @@ public void ResolveFunctionParameters() private static OpenApiDocument GetSampleOpenApiDocument() { - return new OpenApiDocument() + return new OpenApiDocument { Info = new() { Title = "Test", Version = "1.0" }, - Servers = new List() { new() { Url = "https://localhost/" } }, + Servers = new List { new() { Url = "https://localhost/" } }, Paths = new() { { "/foo", new() { - Operations = new Dictionary() + Operations = new Dictionary { { OperationType.Get, new() @@ -107,7 +108,7 @@ private static OpenApiDocument GetSampleOpenApiDocument() OperationId = "Foo.GetFoo", Parameters = new List { - new OpenApiParameter() + new OpenApiParameter { Name = "ids", In = ParameterLocation.Query, diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs index 34cdd3a0a..32d3db3b4 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs @@ -70,14 +70,15 @@ public void ReturnFilteredOpenApiDocumentBasedOnPostmanCollection() [Fact] public void TestPredicateFiltersUsingRelativeRequestUrls() { - var openApiDocument = new OpenApiDocument() + var openApiDocument = new OpenApiDocument { Info = new() { Title = "Test", Version = "1.0" }, - Servers = new List() { new() { Url = "https://localhost/" } }, + Servers = new List { new() { Url = "https://localhost/" } }, Paths = new() { {"/foo", new() { - Operations = new Dictionary() { + Operations = new Dictionary + { { OperationType.Get, new() }, { OperationType.Patch, new() }, { OperationType.Post, new() } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 9d73c8db6..fb2349e52 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -136,7 +136,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() { // create a dummy ILogger instance for testing - var options = new HidiOptions() + var options = new HidiOptions { OpenApi = Path.Combine("UtilityFiles", "SampleOpenApi.yml"), Output = new FileInfo("sample.md") @@ -151,7 +151,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() [Fact] public async Task ShowCommandGeneratesMermaidHtmlFileWithMermaidDiagram() { - var options = new HidiOptions() + var options = new HidiOptions { OpenApi = Path.Combine("UtilityFiles", "SampleOpenApi.yml") }; @@ -162,7 +162,7 @@ public async Task ShowCommandGeneratesMermaidHtmlFileWithMermaidDiagram() [Fact] public async Task ShowCommandGeneratesMermaidMarkdownFileFromCsdlWithMermaidDiagram() { - var options = new HidiOptions() + var options = new HidiOptions { Csdl = Path.Combine("UtilityFiles", "Todo.xml"), CsdlFilter = "todos", diff --git a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs index 58b85d91d..3fc77fc01 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs @@ -22,9 +22,9 @@ public static OpenApiDocument CreateOpenApiDocument() { var applicationJsonMediaType = "application/json"; - var document = new OpenApiDocument() + var document = new OpenApiDocument { - Info = new OpenApiInfo() + Info = new OpenApiInfo { Title = "People", Version = "v1.0" @@ -36,7 +36,7 @@ public static OpenApiDocument CreateOpenApiDocument() Url = "https://graph.microsoft.com/v1.0" } }, - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/"] = new OpenApiPathItem() // root path { @@ -46,10 +46,10 @@ public static OpenApiDocument CreateOpenApiDocument() OperationType.Get, new OpenApiOperation { OperationId = "graphService.GetGraphService", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200",new OpenApiResponse() + "200",new OpenApiResponse { Description = "OK" } @@ -59,7 +59,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/reports/microsoft.graph.getTeamsUserActivityCounts(period={period})"] = new OpenApiPathItem() + ["/reports/microsoft.graph.getTeamsUserActivityCounts(period={period})"] = new OpenApiPathItem { Operations = new Dictionary { @@ -69,7 +69,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "reports.Functions" } @@ -80,22 +80,22 @@ public static OpenApiDocument CreateOpenApiDocument() Parameters = new List { { - new OpenApiParameter() + new OpenApiParameter { Name = "period", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" } } } }, - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Success", Content = new Dictionary @@ -120,12 +120,12 @@ public static OpenApiDocument CreateOpenApiDocument() Parameters = new List { { - new OpenApiParameter() + new OpenApiParameter { Name = "period", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" } @@ -133,7 +133,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/reports/microsoft.graph.getTeamsUserActivityUserDetail(date={date})"] = new OpenApiPathItem() + ["/reports/microsoft.graph.getTeamsUserActivityUserDetail(date={date})"] = new OpenApiPathItem { Operations = new Dictionary { @@ -143,7 +143,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "reports.Functions" } @@ -154,22 +154,22 @@ public static OpenApiDocument CreateOpenApiDocument() Parameters = new List { { - new OpenApiParameter() + new OpenApiParameter { Name = "period", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" } } } }, - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Success", Content = new Dictionary @@ -198,14 +198,14 @@ public static OpenApiDocument CreateOpenApiDocument() Name = "period", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" } } } }, - ["/users"] = new OpenApiPathItem() + ["/users"] = new OpenApiPathItem { Operations = new Dictionary { @@ -215,7 +215,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "users.user" } @@ -223,10 +223,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "users.user.ListUser", Summary = "Get entities from users", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Retrieved entities", Content = new Dictionary @@ -268,7 +268,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/users/{user-id}"] = new OpenApiPathItem() + ["/users/{user-id}"] = new OpenApiPathItem { Operations = new Dictionary { @@ -278,7 +278,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "users.user" } @@ -286,10 +286,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "users.user.GetUser", Summary = "Get entity from users by key", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Retrieved entity", Content = new Dictionary @@ -320,7 +320,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "users.user" } @@ -328,10 +328,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "users.user.UpdateUser", Summary = "Update entity in users", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "204", new OpenApiResponse() + "204", new OpenApiResponse { Description = "Success" } @@ -341,7 +341,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/users/{user-id}/messages/{message-id}"] = new OpenApiPathItem() + ["/users/{user-id}/messages/{message-id}"] = new OpenApiPathItem { Operations = new Dictionary { @@ -351,7 +351,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "users.message" } @@ -362,23 +362,23 @@ public static OpenApiDocument CreateOpenApiDocument() Description = "The messages in a mailbox or folder. Read-only. Nullable.", Parameters = new List { - new OpenApiParameter() + new OpenApiParameter { Name = "$select", In = ParameterLocation.Query, Required = true, Description = "Select properties to be returned", - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "array" } // missing explode parameter } }, - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Retrieved navigation property", Content = new Dictionary @@ -405,7 +405,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/administrativeUnits/{administrativeUnit-id}/microsoft.graph.restore"] = new OpenApiPathItem() + ["/administrativeUnits/{administrativeUnit-id}/microsoft.graph.restore"] = new OpenApiPathItem { Operations = new Dictionary { @@ -415,7 +415,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "administrativeUnits.Actions" } @@ -426,23 +426,23 @@ public static OpenApiDocument CreateOpenApiDocument() Parameters = new List { { - new OpenApiParameter() + new OpenApiParameter { Name = "administrativeUnit-id", In = ParameterLocation.Path, Required = true, Description = "key: id of administrativeUnit", - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" } } } }, - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Success", Content = new Dictionary @@ -472,7 +472,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/applications/{application-id}/logo"] = new OpenApiPathItem() + ["/applications/{application-id}/logo"] = new OpenApiPathItem { Operations = new Dictionary { @@ -482,7 +482,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "applications.application" } @@ -490,10 +490,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "applications.application.UpdateLogo", Summary = "Update media content for application in applications", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "204", new OpenApiResponse() + "204", new OpenApiResponse { Description = "Success" } @@ -503,7 +503,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/security/hostSecurityProfiles"] = new OpenApiPathItem() + ["/security/hostSecurityProfiles"] = new OpenApiPathItem { Operations = new Dictionary { @@ -513,7 +513,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "security.hostSecurityProfile" } @@ -521,10 +521,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "security.ListHostSecurityProfiles", Summary = "Get hostSecurityProfiles from security", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Retrieved navigation property", Content = new Dictionary @@ -566,7 +566,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/communications/calls/{call-id}/microsoft.graph.keepAlive"] = new OpenApiPathItem() + ["/communications/calls/{call-id}/microsoft.graph.keepAlive"] = new OpenApiPathItem { Operations = new Dictionary { @@ -576,7 +576,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag() + new OpenApiTag { Name = "communications.Actions" } @@ -586,13 +586,13 @@ public static OpenApiDocument CreateOpenApiDocument() Summary = "Invoke action keepAlive", Parameters = new List { - new OpenApiParameter() + new OpenApiParameter { Name = "call-id", In = ParameterLocation.Path, Description = "key: id of call", Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" }, @@ -604,10 +604,10 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "204", new OpenApiResponse() + "204", new OpenApiResponse { Description = "Success" } @@ -623,7 +623,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/groups/{group-id}/events/{event-id}/calendar/events/microsoft.graph.delta"] = new OpenApiPathItem() + ["/groups/{group-id}/events/{event-id}/calendar/events/microsoft.graph.delta"] = new OpenApiPathItem { Operations = new Dictionary { @@ -632,7 +632,7 @@ public static OpenApiDocument CreateOpenApiDocument() { Tags = new List { - new OpenApiTag() + new OpenApiTag { Name = "groups.Functions" } @@ -641,13 +641,13 @@ public static OpenApiDocument CreateOpenApiDocument() Summary = "Invoke function delta", Parameters = new List { - new OpenApiParameter() + new OpenApiParameter { Name = "group-id", In = ParameterLocation.Path, Description = "key: id of group", Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" }, @@ -658,13 +658,13 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - new OpenApiParameter() + new OpenApiParameter { Name = "event-id", In = ParameterLocation.Path, Description = "key: id of event", Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" }, @@ -676,10 +676,10 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Success", Content = new Dictionary @@ -713,7 +713,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/applications/{application-id}/createdOnBehalfOf/$ref"] = new OpenApiPathItem() + ["/applications/{application-id}/createdOnBehalfOf/$ref"] = new OpenApiPathItem { Operations = new Dictionary { @@ -722,7 +722,7 @@ public static OpenApiDocument CreateOpenApiDocument() { Tags = new List { - new OpenApiTag() + new OpenApiTag { Name = "applications.directoryObject" } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs index 23c23b4d6..5b01e0444 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs @@ -45,7 +45,7 @@ public void DetectedSpecificationVersionShouldBeV3_0() public async Task DiagnosticReportMergedForExternalReference() { // Create a reader that will resolve all references - var reader = new OpenApiStreamReader(new OpenApiReaderSettings() + var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LoadExternalRefs = true, CustomExternalLoader = new ResourceLoader(), diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs index 4a2c2cafe..869d43fab 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs @@ -18,7 +18,7 @@ public class OpenApiWorkspaceStreamTests public async Task LoadingDocumentWithResolveAllReferencesShouldLoadDocumentIntoWorkspace() { // Create a reader that will resolve all references - var reader = new OpenApiStreamReader(new OpenApiReaderSettings() + var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LoadExternalRefs = true, CustomExternalLoader = new MockLoader(), @@ -48,7 +48,7 @@ public async Task LoadingDocumentWithResolveAllReferencesShouldLoadDocumentIntoW public async Task LoadDocumentWithExternalReferenceShouldLoadBothDocumentsIntoWorkspace() { // Create a reader that will resolve all references - var reader = new OpenApiStreamReader(new OpenApiReaderSettings() + var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LoadExternalRefs = true, CustomExternalLoader = new ResourceLoader(), diff --git a/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs index 677232ac4..2ece19537 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs @@ -25,7 +25,8 @@ public void BrokenSimpleList() var reader = new OpenApiStringReader(); reader.Read(input, out var diagnostic); - diagnostic.Errors.Should().BeEquivalentTo(new List() { + diagnostic.Errors.Should().BeEquivalentTo(new List + { new OpenApiError(new OpenApiReaderException("Expected a value.") { Pointer = "#line=4" }) @@ -53,7 +54,8 @@ public void BadSchema() var reader = new OpenApiStringReader(); reader.Read(input, out var diagnostic); - diagnostic.Errors.Should().BeEquivalentTo(new List() { + diagnostic.Errors.Should().BeEquivalentTo(new List + { new OpenApiError(new OpenApiReaderException("schema must be a map/object") { Pointer = "#/paths/~1foo/get/responses/200/content/application~1json/schema" }) diff --git a/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs index 7ee8c3439..3875b77b0 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs @@ -38,31 +38,31 @@ public void ParseObjectAsAnyShouldSucceed() var anyMap = node.CreateAny(); - var schema = new OpenApiSchema() + var schema = new OpenApiSchema { Type = "object", Properties = { - ["aString"] = new OpenApiSchema() + ["aString"] = new OpenApiSchema { Type = "string" }, - ["aInteger"] = new OpenApiSchema() + ["aInteger"] = new OpenApiSchema { Type = "integer", Format = "int32" }, - ["aDouble"] = new OpenApiSchema() + ["aDouble"] = new OpenApiSchema { Type = "number", Format = "double" }, - ["aDateTime"] = new OpenApiSchema() + ["aDateTime"] = new OpenApiSchema { Type = "string", Format = "date-time" }, - ["aDate"] = new OpenApiSchema() + ["aDate"] = new OpenApiSchema { Type = "string", Format = "date" @@ -124,59 +124,59 @@ public void ParseNestedObjectAsAnyShouldSucceed() var anyMap = node.CreateAny(); - var schema = new OpenApiSchema() + var schema = new OpenApiSchema { Type = "object", Properties = { - ["aString"] = new OpenApiSchema() + ["aString"] = new OpenApiSchema { Type = "string" }, - ["aInteger"] = new OpenApiSchema() + ["aInteger"] = new OpenApiSchema { Type = "integer", Format = "int32" }, - ["aArray"] = new OpenApiSchema() + ["aArray"] = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "integer", Format = "int64" } }, - ["aNestedArray"] = new OpenApiSchema() + ["aNestedArray"] = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "object", Properties = { - ["aFloat"] = new OpenApiSchema() + ["aFloat"] = new OpenApiSchema { Type = "number", Format = "float" }, - ["aPassword"] = new OpenApiSchema() + ["aPassword"] = new OpenApiSchema { Type = "string", Format = "password" }, - ["aArray"] = new OpenApiSchema() + ["aArray"] = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "string", } }, - ["aDictionary"] = new OpenApiSchema() + ["aDictionary"] = new OpenApiSchema { Type = "object", - AdditionalProperties = new OpenApiSchema() + AdditionalProperties = new OpenApiSchema { Type = "integer", Format = "int64" @@ -185,24 +185,24 @@ public void ParseNestedObjectAsAnyShouldSucceed() } } }, - ["aObject"] = new OpenApiSchema() + ["aObject"] = new OpenApiSchema { Type = "array", Properties = { - ["aDate"] = new OpenApiSchema() + ["aDate"] = new OpenApiSchema { Type = "string", Format = "date" } } }, - ["aDouble"] = new OpenApiSchema() + ["aDouble"] = new OpenApiSchema { Type = "number", Format = "double" }, - ["aDateTime"] = new OpenApiSchema() + ["aDateTime"] = new OpenApiSchema { Type = "string", Format = "date-time" @@ -219,44 +219,44 @@ public void ParseNestedObjectAsAnyShouldSucceed() { ["aString"] = new OpenApiString("fooBar"), ["aInteger"] = new OpenApiInteger(10), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiLong(1), new OpenApiLong(2), new OpenApiLong(3), }, - ["aNestedArray"] = new OpenApiArray() + ["aNestedArray"] = new OpenApiArray { - new OpenApiObject() + new OpenApiObject { ["aFloat"] = new OpenApiFloat(1), ["aPassword"] = new OpenApiPassword("1234"), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiString("abc"), new OpenApiString("def") }, - ["aDictionary"] = new OpenApiObject() + ["aDictionary"] = new OpenApiObject { ["arbitraryProperty"] = new OpenApiLong(1), ["arbitraryProperty2"] = new OpenApiLong(2), } }, - new OpenApiObject() + new OpenApiObject { ["aFloat"] = new OpenApiFloat((float)1.6), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiString("123"), }, - ["aDictionary"] = new OpenApiObject() + ["aDictionary"] = new OpenApiObject { ["arbitraryProperty"] = new OpenApiLong(1), ["arbitraryProperty3"] = new OpenApiLong(20), } } }, - ["aObject"] = new OpenApiObject() + ["aObject"] = new OpenApiObject { ["aDate"] = new OpenApiDate(DateTimeOffset.Parse("2017-02-03", CultureInfo.InvariantCulture).Date) }, @@ -304,41 +304,41 @@ public void ParseNestedObjectAsAnyWithPartialSchemaShouldSucceed() var anyMap = node.CreateAny(); - var schema = new OpenApiSchema() + var schema = new OpenApiSchema { Type = "object", Properties = { - ["aString"] = new OpenApiSchema() + ["aString"] = new OpenApiSchema { Type = "string" }, - ["aArray"] = new OpenApiSchema() + ["aArray"] = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "integer" } }, - ["aNestedArray"] = new OpenApiSchema() + ["aNestedArray"] = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "object", Properties = { - ["aFloat"] = new OpenApiSchema() + ["aFloat"] = new OpenApiSchema { }, - ["aPassword"] = new OpenApiSchema() + ["aPassword"] = new OpenApiSchema { }, - ["aArray"] = new OpenApiSchema() + ["aArray"] = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "string", } @@ -346,21 +346,21 @@ public void ParseNestedObjectAsAnyWithPartialSchemaShouldSucceed() } } }, - ["aObject"] = new OpenApiSchema() + ["aObject"] = new OpenApiSchema { Type = "array", Properties = { - ["aDate"] = new OpenApiSchema() + ["aDate"] = new OpenApiSchema { Type = "string" } } }, - ["aDouble"] = new OpenApiSchema() + ["aDouble"] = new OpenApiSchema { }, - ["aDateTime"] = new OpenApiSchema() + ["aDateTime"] = new OpenApiSchema { } } @@ -375,44 +375,44 @@ public void ParseNestedObjectAsAnyWithPartialSchemaShouldSucceed() { ["aString"] = new OpenApiString("fooBar"), ["aInteger"] = new OpenApiInteger(10), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiInteger(1), new OpenApiInteger(2), new OpenApiInteger(3), }, - ["aNestedArray"] = new OpenApiArray() + ["aNestedArray"] = new OpenApiArray { - new OpenApiObject() + new OpenApiObject { ["aFloat"] = new OpenApiInteger(1), ["aPassword"] = new OpenApiInteger(1234), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiString("abc"), new OpenApiString("def") }, - ["aDictionary"] = new OpenApiObject() + ["aDictionary"] = new OpenApiObject { ["arbitraryProperty"] = new OpenApiInteger(1), ["arbitraryProperty2"] = new OpenApiInteger(2), } }, - new OpenApiObject() + new OpenApiObject { ["aFloat"] = new OpenApiDouble(1.6), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiString("123"), }, - ["aDictionary"] = new OpenApiObject() + ["aDictionary"] = new OpenApiObject { ["arbitraryProperty"] = new OpenApiInteger(1), ["arbitraryProperty3"] = new OpenApiInteger(20), } } }, - ["aObject"] = new OpenApiObject() + ["aObject"] = new OpenApiObject { ["aDate"] = new OpenApiString("2017-02-03") }, @@ -468,44 +468,44 @@ public void ParseNestedObjectAsAnyWithoutUsingSchemaShouldSucceed() { ["aString"] = new OpenApiString("fooBar"), ["aInteger"] = new OpenApiInteger(10), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiInteger(1), new OpenApiInteger(2), new OpenApiInteger(3), }, - ["aNestedArray"] = new OpenApiArray() + ["aNestedArray"] = new OpenApiArray { - new OpenApiObject() + new OpenApiObject { ["aFloat"] = new OpenApiInteger(1), ["aPassword"] = new OpenApiInteger(1234), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiString("abc"), new OpenApiString("def") }, - ["aDictionary"] = new OpenApiObject() + ["aDictionary"] = new OpenApiObject { ["arbitraryProperty"] = new OpenApiInteger(1), ["arbitraryProperty2"] = new OpenApiInteger(2), } }, - new OpenApiObject() + new OpenApiObject { ["aFloat"] = new OpenApiDouble(1.6), - ["aArray"] = new OpenApiArray() + ["aArray"] = new OpenApiArray { new OpenApiInteger(123), }, - ["aDictionary"] = new OpenApiObject() + ["aDictionary"] = new OpenApiObject { ["arbitraryProperty"] = new OpenApiInteger(1), ["arbitraryProperty3"] = new OpenApiInteger(20), } } }, - ["aObject"] = new OpenApiObject() + ["aObject"] = new OpenApiObject { ["aDate"] = new OpenApiDateTime(DateTimeOffset.Parse("2017-02-03", CultureInfo.InvariantCulture)) }, diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs index a641b7d6f..9469de370 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs @@ -228,11 +228,11 @@ public void LoadResponseAndSchemaReference() Description = "Sample description", Required = new HashSet {"name" }, Properties = { - ["name"] = new OpenApiSchema() + ["name"] = new OpenApiSchema { Type = "string" }, - ["tag"] = new OpenApiSchema() + ["tag"] = new OpenApiSchema { Type = "string" } diff --git a/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs b/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs index 88866fd95..89468229a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs @@ -24,11 +24,12 @@ public void ParseCustomExtension() baz: hi! paths: {} "; - var settings = new OpenApiReaderSettings() + var settings = new OpenApiReaderSettings { ExtensionParsers = { { "x-foo", (a,v) => { var fooNode = (OpenApiObject)a; - return new FooExtension() { + return new FooExtension + { Bar = (fooNode["bar"] as OpenApiString)?.Value, Baz = (fooNode["baz"] as OpenApiString)?.Value }; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index ac5f99a86..4acdb583f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -122,16 +122,16 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) ["x-extension"] = new OpenApiDouble(2.335) } }, - Components = new OpenApiComponents() + Components = new OpenApiComponents { Schemas = { - ["sampleSchema"] = new OpenApiSchema() + ["sampleSchema"] = new OpenApiSchema { Type = "object", Properties = { - ["sampleProperty"] = new OpenApiSchema() + ["sampleProperty"] = new OpenApiSchema { Type = "double", Minimum = (decimal)100.54, @@ -140,7 +140,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) ExclusiveMinimum = false } }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "sampleSchema", Type = ReferenceType.Schema @@ -152,7 +152,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) }); context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi2_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi2_0 }); } [Fact] @@ -163,7 +163,7 @@ public void ShouldParseProducesInAnyOrder() var reader = new OpenApiStreamReader(); var doc = reader.Read(stream, out var diagnostic); - var okSchema = new OpenApiSchema() + var okSchema = new OpenApiSchema { Reference = new OpenApiReference { @@ -171,9 +171,9 @@ public void ShouldParseProducesInAnyOrder() Id = "Item", HostDocument = doc }, - Properties = new Dictionary() + Properties = new Dictionary { - { "id", new OpenApiSchema() + { "id", new OpenApiSchema { Type = "string", Description = "Item identifier." @@ -182,7 +182,7 @@ public void ShouldParseProducesInAnyOrder() } }; - var errorSchema = new OpenApiSchema() + var errorSchema = new OpenApiSchema { Reference = new OpenApiReference { @@ -190,20 +190,20 @@ public void ShouldParseProducesInAnyOrder() Id = "Error", HostDocument = doc }, - Properties = new Dictionary() + Properties = new Dictionary { - { "code", new OpenApiSchema() + { "code", new OpenApiSchema { Type = "integer", Format = "int32" } }, - { "message", new OpenApiSchema() + { "message", new OpenApiSchema { Type = "string" } }, - { "fields", new OpenApiSchema() + { "fields", new OpenApiSchema { Type = "string" } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs index 7a98c7a6d..eb3bb066c 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs @@ -34,7 +34,7 @@ public void ParseHeaderWithDefaultShouldSucceed() header.Should().BeEquivalentTo( new OpenApiHeader { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "number", Format = "float", @@ -60,7 +60,7 @@ public void ParseHeaderWithEnumShouldSucceed() header.Should().BeEquivalentTo( new OpenApiHeader { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "number", Format = "float", diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs index 3b0f32871..76da8a763 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs @@ -330,39 +330,39 @@ public void ParseOperationWithResponseExamplesShouldSucceed() // Assert operation.Should().BeEquivalentTo( - new OpenApiOperation() + new OpenApiOperation { - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { - { "200", new OpenApiResponse() + { "200", new OpenApiResponse { Description = "An array of float response", Content = { - ["application/json"] = new OpenApiMediaType() + ["application/json"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "number", Format = "float" } }, - Example = new OpenApiArray() + Example = new OpenApiArray { new OpenApiFloat(5), new OpenApiFloat(6), new OpenApiFloat(7), } }, - ["application/xml"] = new OpenApiMediaType() + ["application/xml"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "number", Format = "float" @@ -389,18 +389,18 @@ public void ParseOperationWithEmptyProducesArraySetsResponseSchemaIfExists() // Assert operation.Should().BeEquivalentTo( - new OpenApiOperation() + new OpenApiOperation { - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { - { "200", new OpenApiResponse() + { "200", new OpenApiResponse { Description = "OK", Content = { - ["application/octet-stream"] = new OpenApiMediaType() + ["application/octet-stream"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Format = "binary", Description = "The content of the file.", diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs index fc4e84f50..3f46f5a2b 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs @@ -155,15 +155,16 @@ public void ParseHeaderParameterShouldSucceed() new OpenApiLong(4), } }, - Default = new OpenApiArray() { + Default = new OpenApiArray + { new OpenApiLong(1), new OpenApiLong(2) }, Enum = new List { - new OpenApiArray() { new OpenApiLong(1), new OpenApiLong(2) }, - new OpenApiArray() { new OpenApiLong(2), new OpenApiLong(3) }, - new OpenApiArray() { new OpenApiLong(3), new OpenApiLong(4) } + new OpenApiArray { new OpenApiLong(1), new OpenApiLong(2) }, + new OpenApiArray { new OpenApiLong(2), new OpenApiLong(3) }, + new OpenApiArray { new OpenApiLong(3), new OpenApiLong(4) } } } }); @@ -207,15 +208,16 @@ public void ParseHeaderParameterWithIncorrectDataTypeShouldSucceed() new OpenApiString("4"), } }, - Default = new OpenApiArray() { + Default = new OpenApiArray + { new OpenApiString("1"), new OpenApiString("2") }, Enum = new List { - new OpenApiArray() { new OpenApiString("1"), new OpenApiString("2") }, - new OpenApiArray() { new OpenApiString("2"), new OpenApiString("3") }, - new OpenApiArray() { new OpenApiString("3"), new OpenApiString("4") } + new OpenApiArray { new OpenApiString("1"), new OpenApiString("2") }, + new OpenApiArray { new OpenApiString("2"), new OpenApiString("3") }, + new OpenApiArray { new OpenApiString("3"), new OpenApiString("4") } } } }); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs index a11497cdf..c32c15ff4 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs @@ -19,20 +19,20 @@ public class OpenApiPathItemTests { private const string SampleFolderPath = "V2Tests/Samples/OpenApiPathItem/"; - private static readonly OpenApiPathItem _basicPathItemWithFormData = new OpenApiPathItem() + private static readonly OpenApiPathItem _basicPathItemWithFormData = new OpenApiPathItem { Parameters = new List { - new OpenApiParameter() + new OpenApiParameter { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to use", Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "string" } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs index bf0fe7b78..5037007a2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs @@ -18,7 +18,7 @@ public void NoServer() version: 1.0.0 paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { }); @@ -39,7 +39,7 @@ public void JustSchemeNoDefault() - http paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { }); @@ -59,7 +59,7 @@ public void JustHostNoDefault() host: www.foo.com paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { }); @@ -83,7 +83,7 @@ public void NoBasePath() - http paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://www.foo.com/spec.yaml") }); @@ -106,7 +106,7 @@ public void JustBasePathNoDefault() basePath: /baz paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { }); @@ -129,7 +129,7 @@ public void JustSchemeWithCustomHost() - http paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://bing.com/foo") }); @@ -153,7 +153,7 @@ public void JustSchemeWithCustomHostWithEmptyPath() - http paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://bing.com") }); @@ -176,7 +176,7 @@ public void JustBasePathWithCustomHost() basePath: /api paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://bing.com") }); @@ -199,7 +199,7 @@ public void JustHostWithCustomHost() host: www.example.com paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://bing.com") }); @@ -222,7 +222,7 @@ public void JustHostWithCustomHostWithApi() host: prod.bing.com paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://dev.bing.com/api/description.yaml") }); @@ -247,7 +247,7 @@ public void MultipleServers() - https paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://dev.bing.com/api") }); @@ -271,7 +271,7 @@ public void LocalHostWithCustomHost() host: localhost:23232 paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://bing.com") }); @@ -294,7 +294,7 @@ public void InvalidHostShouldYieldError() host: http://test.microsoft.com paths: {} "; - var reader = new OpenApiStringReader(new OpenApiReaderSettings() + var reader = new OpenApiStringReader(new OpenApiReaderSettings { BaseUrl = new Uri("https://bing.com") }); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs index 320f01fae..1a45006db 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs @@ -89,7 +89,7 @@ public void ParseCallbackWithReferenceShouldSucceed() var callback = subscribeOperation.Callbacks["simpleHook"]; diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); callback.Should().BeEquivalentTo( new OpenApiCallback @@ -98,7 +98,7 @@ public void ParseCallbackWithReferenceShouldSucceed() { [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { Operations = { - [OperationType.Post] = new OpenApiOperation() + [OperationType.Post] = new OpenApiOperation { RequestBody = new OpenApiRequestBody { @@ -106,7 +106,7 @@ public void ParseCallbackWithReferenceShouldSucceed() { ["application/json"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "object" } @@ -146,7 +146,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() var subscribeOperation = path.Operations[OperationType.Post]; diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); var callback1 = subscribeOperation.Callbacks["simpleHook"]; @@ -157,7 +157,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { Operations = { - [OperationType.Post] = new OpenApiOperation() + [OperationType.Post] = new OpenApiOperation { RequestBody = new OpenApiRequestBody { @@ -165,7 +165,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { ["application/json"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "object" } @@ -198,7 +198,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { [RuntimeExpression.Build("/simplePath")]= new OpenApiPathItem { Operations = { - [OperationType.Post] = new OpenApiOperation() + [OperationType.Post] = new OpenApiOperation { RequestBody = new OpenApiRequestBody { @@ -207,7 +207,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { ["application/json"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" } @@ -234,7 +234,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { [RuntimeExpression.Build(@"http://example.com?transactionId={$request.body#/id}&email={$request.body#/email}")] = new OpenApiPathItem { Operations = { - [OperationType.Post] = new OpenApiOperation() + [OperationType.Post] = new OpenApiOperation { RequestBody = new OpenApiRequestBody { @@ -242,7 +242,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { ["application/xml"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "object" } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 8a0da3481..85a686e49 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -36,7 +36,7 @@ public T Clone(T element) where T : IOpenApiSerializable { IOpenApiWriter writer; var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); - writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() + writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings { InlineLocalReferences = true }); @@ -58,7 +58,7 @@ public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) { IOpenApiWriter writer; var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); - writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings() + writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings { InlineLocalReferences = true }); @@ -104,7 +104,7 @@ public void ParseDocumentFromInlineStringShouldSucceed() }); context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Theory] @@ -146,16 +146,16 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) Title = "Simple Document", Version = "0.9.1" }, - Components = new OpenApiComponents() + Components = new OpenApiComponents { Schemas = { - ["sampleSchema"] = new OpenApiSchema() + ["sampleSchema"] = new OpenApiSchema { Type = "object", Properties = { - ["sampleProperty"] = new OpenApiSchema() + ["sampleProperty"] = new OpenApiSchema { Type = "double", Minimum = (decimal)100.54, @@ -164,7 +164,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) ExclusiveMinimum = false } }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "sampleSchema", Type = ReferenceType.Schema @@ -176,7 +176,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) }); context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] @@ -187,7 +187,7 @@ public void ParseBasicDocumentWithMultipleServersShouldSucceed() var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); openApiDoc.Should().BeEquivalentTo( new OpenApiDocument @@ -263,7 +263,7 @@ public void ParseMinimalDocumentShouldSucceed() }); diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } } @@ -694,7 +694,7 @@ public void ParseStandardPetStoreDocumentShouldSucceed() } context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] @@ -1201,7 +1201,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() { Name = "tagName1", Description = "tagDescription1", - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "tagName1", Type = ReferenceType.Tag @@ -1227,7 +1227,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() } context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] @@ -1243,7 +1243,7 @@ public void ParsePetStoreExpandedShouldSucceed() } context.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); } [Fact] @@ -1269,7 +1269,7 @@ public void HeaderParameterShouldAllowExample() var exampleHeader = openApiDoc.Components?.Headers?["example-header"]; Assert.NotNull(exampleHeader); exampleHeader.Should().BeEquivalentTo( - new OpenApiHeader() + new OpenApiHeader { Description = "Test header with example", Required = true, @@ -1279,12 +1279,12 @@ public void HeaderParameterShouldAllowExample() Style = ParameterStyle.Simple, Explode = true, Example = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721"), - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string", Format = "uuid" }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Header, Id = "example-header" @@ -1294,7 +1294,7 @@ public void HeaderParameterShouldAllowExample() var examplesHeader = openApiDoc.Components?.Headers?["examples-header"]; Assert.NotNull(examplesHeader); examplesHeader.Should().BeEquivalentTo( - new OpenApiHeader() + new OpenApiHeader { Description = "Test header with example", Required = true, @@ -1303,25 +1303,25 @@ public void HeaderParameterShouldAllowExample() AllowReserved = true, Style = ParameterStyle.Simple, Explode = true, - Examples = new Dictionary() + Examples = new Dictionary { - { "uuid1", new OpenApiExample() + { "uuid1", new OpenApiExample { Value = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721") } }, - { "uuid2", new OpenApiExample() + { "uuid2", new OpenApiExample { Value = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721") } } }, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string", Format = "uuid" }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Header, Id = "examples-header" diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs index e62eabb53..47983a9a1 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs @@ -61,11 +61,11 @@ public void ParseMediaTypeWithExamplesShouldSucceed() { Examples = { - ["example1"] = new OpenApiExample() + ["example1"] = new OpenApiExample { Value = new OpenApiFloat(5), }, - ["example2"] = new OpenApiExample() + ["example2"] = new OpenApiExample { Value = new OpenApiFloat((float)7.5), } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs index a74c64154..37053c2a4 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs @@ -42,14 +42,14 @@ public void ParseOperationWithParameterWithNoLocationShouldSucceed() var operation = OpenApiV3Deserializer.LoadOperation(node); // Assert - operation.Should().BeEquivalentTo(new OpenApiOperation() + operation.Should().BeEquivalentTo(new OpenApiOperation { Tags = { new OpenApiTag { UnresolvedReference = true, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "user", Type = ReferenceType.Tag diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs index 44ba3316d..3234195e5 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs @@ -329,11 +329,11 @@ public void ParseParameterWithExamplesShouldSucceed() Required = true, Examples = { - ["example1"] = new OpenApiExample() + ["example1"] = new OpenApiExample { Value = new OpenApiFloat(5), }, - ["example2"] = new OpenApiExample() + ["example2"] = new OpenApiExample { Value = new OpenApiFloat((float)7.5), } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index 0101d9c6e..54553d5a5 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -119,7 +119,8 @@ public void ParseExampleStringFragmentShouldSucceed() new OpenApiObject { ["foo"] = new OpenApiString("bar"), - ["baz"] = new OpenApiArray() { + ["baz"] = new OpenApiArray + { new OpenApiInteger(1), new OpenApiInteger(2) } @@ -226,7 +227,7 @@ public void ParsePathFragmentShouldSucceed() Summary = "externally referenced path item", Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation() + [OperationType.Get] = new OpenApiOperation { Responses = new OpenApiResponses { @@ -333,7 +334,7 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() var components = openApiDoc.Components; diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); components.Should().BeEquivalentTo( new OpenApiComponents @@ -439,7 +440,7 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() var components = openApiDoc.Components; diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); components.Should().BeEquivalentTo( new OpenApiComponents @@ -469,7 +470,7 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() "name", "petType" }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id= "Pet", Type = ReferenceType.Schema, @@ -534,7 +535,7 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() } } }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id= "Cat", Type = ReferenceType.Schema, @@ -595,7 +596,7 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() } } }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id= "Dog", Type = ReferenceType.Schema, @@ -620,29 +621,31 @@ public void ParseSelfReferencingSchemaShouldNotStackOverflow() var components = openApiDoc.Components; diagnostic.Should().BeEquivalentTo( - new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); + new OpenApiDiagnostic { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); - var schemaExtension = new OpenApiSchema() + var schemaExtension = new OpenApiSchema { - AllOf = { new OpenApiSchema() - { + AllOf = { new OpenApiSchema + { Title = "schemaExtension", Type = "object", Properties = { - ["description"] = new OpenApiSchema() { Type = "string", Nullable = true}, - ["targetTypes"] = new OpenApiSchema() { + ["description"] = new OpenApiSchema { Type = "string", Nullable = true}, + ["targetTypes"] = new OpenApiSchema + { Type = "array", - Items = new OpenApiSchema() { + Items = new OpenApiSchema + { Type = "string" } }, - ["status"] = new OpenApiSchema() { Type = "string"}, - ["owner"] = new OpenApiSchema() { Type = "string"}, + ["status"] = new OpenApiSchema { Type = "string"}, + ["owner"] = new OpenApiSchema { Type = "string"}, ["child"] = null } } }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "microsoft.graph.schemaExtension" diff --git a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs index 6d2eafc01..efba7b9b0 100644 --- a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs +++ b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs @@ -28,7 +28,7 @@ public ApisGuruTests(ITestOutputHelper output) static ApisGuruTests() { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; - _httpClient = new HttpClient(new HttpClientHandler() + _httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); diff --git a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs index de3101e27..b7881a905 100644 --- a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs +++ b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs @@ -24,7 +24,7 @@ public GraphTests(ITestOutputHelper output) { _output = output; System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; - _httpClient = new HttpClient(new HttpClientHandler() + _httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip")); diff --git a/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs index 5c91249d3..a5b116faa 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs @@ -188,7 +188,7 @@ public void CompositeRuntimeExpressionContainsMultipleExpressions() var compositeExpression = runtimeExpression as CompositeExpression; Assert.Equal(2, compositeExpression.ContainedExpressions.Count); - compositeExpression.ContainedExpressions.Should().BeEquivalentTo(new List() + compositeExpression.ContainedExpressions.Should().BeEquivalentTo(new List { new UrlExpression(), new RequestExpression(new HeaderExpression("foo")) @@ -232,7 +232,7 @@ public void CompositeRuntimeExpressionWithMultipleRuntimeExpressionsAndFakeBrace response.Expression.Should().Be(expression); var compositeExpression = runtimeExpression as CompositeExpression; - compositeExpression.ContainedExpressions.Should().BeEquivalentTo(new List() + compositeExpression.ContainedExpressions.Should().BeEquivalentTo(new List { new UrlExpression(), new RequestExpression(new HeaderExpression("foo")) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs index 7ba6d132c..46a6bb772 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs @@ -170,13 +170,13 @@ public class OpenApiComponentsTests } }; - public static OpenApiComponents TopLevelReferencingComponents = new OpenApiComponents() + public static OpenApiComponents TopLevelReferencingComponents = new OpenApiComponents { Schemas = { ["schema1"] = new OpenApiSchema { - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "schema2" @@ -187,7 +187,7 @@ public class OpenApiComponentsTests Type = "object", Properties = { - ["property1"] = new OpenApiSchema() + ["property1"] = new OpenApiSchema { Type = "string" } @@ -196,7 +196,7 @@ public class OpenApiComponentsTests } }; - public static OpenApiComponents TopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiComponents() + public static OpenApiComponents TopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiComponents { Schemas = { @@ -205,12 +205,12 @@ public class OpenApiComponentsTests Type = "object", Properties = { - ["property1"] = new OpenApiSchema() + ["property1"] = new OpenApiSchema { Type = "string" } }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "schema1" @@ -221,7 +221,7 @@ public class OpenApiComponentsTests Type = "object", Properties = { - ["property1"] = new OpenApiSchema() + ["property1"] = new OpenApiSchema { Type = "string" } @@ -230,13 +230,13 @@ public class OpenApiComponentsTests } }; - public static OpenApiComponents TopLevelSelfReferencingComponents = new OpenApiComponents() + public static OpenApiComponents TopLevelSelfReferencingComponents = new OpenApiComponents { Schemas = { ["schema1"] = new OpenApiSchema { - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "schema1" diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 924699bdf..becc91d97 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -24,13 +24,13 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiDocumentTests { - public static OpenApiComponents TopLevelReferencingComponents = new OpenApiComponents() + public static OpenApiComponents TopLevelReferencingComponents = new OpenApiComponents { Schemas = { ["schema1"] = new OpenApiSchema { - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "schema2" @@ -41,7 +41,7 @@ public class OpenApiDocumentTests Type = "object", Properties = { - ["property1"] = new OpenApiSchema() + ["property1"] = new OpenApiSchema { Type = "string" } @@ -50,7 +50,7 @@ public class OpenApiDocumentTests } }; - public static OpenApiComponents TopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiComponents() + public static OpenApiComponents TopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiComponents { Schemas = { @@ -59,12 +59,12 @@ public class OpenApiDocumentTests Type = "object", Properties = { - ["property1"] = new OpenApiSchema() + ["property1"] = new OpenApiSchema { Type = "string" } }, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "schema1" @@ -75,7 +75,7 @@ public class OpenApiDocumentTests Type = "object", Properties = { - ["property1"] = new OpenApiSchema() + ["property1"] = new OpenApiSchema { Type = "string" } @@ -84,13 +84,13 @@ public class OpenApiDocumentTests } }; - public static OpenApiComponents TopLevelSelfReferencingComponents = new OpenApiComponents() + public static OpenApiComponents TopLevelSelfReferencingComponents = new OpenApiComponents { Schemas = { ["schema1"] = new OpenApiSchema { - Reference = new OpenApiReference() + Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "schema1" @@ -99,27 +99,27 @@ public class OpenApiDocumentTests } }; - public static OpenApiDocument SimpleDocumentWithTopLevelReferencingComponents = new OpenApiDocument() + public static OpenApiDocument SimpleDocumentWithTopLevelReferencingComponents = new OpenApiDocument { - Info = new OpenApiInfo() + Info = new OpenApiInfo { Version = "1.0.0" }, Components = TopLevelReferencingComponents }; - public static OpenApiDocument SimpleDocumentWithTopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiDocument() + public static OpenApiDocument SimpleDocumentWithTopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiDocument { - Info = new OpenApiInfo() + Info = new OpenApiInfo { Version = "1.0.0" }, Components = TopLevelSelfReferencingComponentsWithOtherProperties }; - public static OpenApiDocument SimpleDocumentWithTopLevelSelfReferencingComponents = new OpenApiDocument() + public static OpenApiDocument SimpleDocumentWithTopLevelSelfReferencingComponents = new OpenApiDocument { - Info = new OpenApiInfo() + Info = new OpenApiInfo { Version = "1.0.0" }, @@ -1485,7 +1485,7 @@ public void SerializeSimpleDocumentWithTopLevelSelfReferencingWithOtherPropertie public void SerializeDocumentWithReferenceButNoComponents() { // Arrange - var document = new OpenApiDocument() + var document = new OpenApiDocument { Info = new OpenApiInfo { @@ -1504,7 +1504,7 @@ public void SerializeDocumentWithReferenceButNoComponents() { ["200"] = new OpenApiResponse { - Content = new Dictionary() + Content = new Dictionary { ["application/json"] = new OpenApiMediaType { @@ -1546,11 +1546,12 @@ public void SerializeRelativePathAsV2JsonWorks() version: 1.0.0 basePath: /server1 paths: { }"; - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Info = new OpenApiInfo() { Version = "1.0.0" }, - Servers = new List() { - new OpenApiServer() + Info = new OpenApiInfo { Version = "1.0.0" }, + Servers = new List + { + new OpenApiServer { Url = "/server1" } @@ -1577,11 +1578,12 @@ public void SerializeRelativePathWithHostAsV2JsonWorks() host: //example.org basePath: /server1 paths: { }"; - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Info = new OpenApiInfo() { Version = "1.0.0" }, - Servers = new List() { - new OpenApiServer() + Info = new OpenApiInfo { Version = "1.0.0" }, + Servers = new List + { + new OpenApiServer { Url = "//example.org/server1" } @@ -1607,11 +1609,12 @@ public void SerializeRelativeRootPathWithHostAsV2JsonWorks() version: 1.0.0 host: //example.org paths: { }"; - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Info = new OpenApiInfo() { Version = "1.0.0" }, - Servers = new List() { - new OpenApiServer() + Info = new OpenApiInfo { Version = "1.0.0" }, + Servers = new List + { + new OpenApiServer { Url = "//example.org/" } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index de56df52e..11d8dc517 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -212,70 +212,70 @@ [new OpenApiSecurityScheme }; private static readonly OpenApiOperation _operationWithFormData = - new OpenApiOperation() + new OpenApiOperation { Summary = "Updates a pet in the store with form data", Description = "", OperationId = "updatePetWithForm", - Parameters = new List() + Parameters = new List { - new OpenApiParameter() + new OpenApiParameter { Name = "petId", In = ParameterLocation.Path, Description = "ID of pet that needs to be updated", Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string" } } }, - RequestBody = new OpenApiRequestBody() + RequestBody = new OpenApiRequestBody { Content = { - ["application/x-www-form-urlencoded"] = new OpenApiMediaType() + ["application/x-www-form-urlencoded"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Properties = { - ["name"] = new OpenApiSchema() + ["name"] = new OpenApiSchema { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema() + ["status"] = new OpenApiSchema { Description = "Updated status of the pet", Type = "string" } }, - Required = new HashSet() + Required = new HashSet { "name" } } }, - ["multipart/form-data"] = new OpenApiMediaType() + ["multipart/form-data"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Properties = { - ["name"] = new OpenApiSchema() + ["name"] = new OpenApiSchema { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema() + ["status"] = new OpenApiSchema { Description = "Updated status of the pet", Type = "string" } }, - Required = new HashSet() + Required = new HashSet { "name" } @@ -283,13 +283,13 @@ [new OpenApiSecurityScheme } } }, - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { - ["200"] = new OpenApiResponse() + ["200"] = new OpenApiResponse { Description = "Pet updated." }, - ["405"] = new OpenApiResponse() + ["405"] = new OpenApiResponse { Description = "Invalid input" } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index 9d84ab63d..d59c026e3 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -168,12 +168,12 @@ public class OpenApiSchemaTests public static OpenApiSchema AdvancedSchemaWithRequiredPropertiesObject = new OpenApiSchema { Title = "title1", - Required = new HashSet() { "property1" }, + Required = new HashSet { "property1" }, Properties = new Dictionary { ["property1"] = new OpenApiSchema { - Required = new HashSet() { "property3" }, + Required = new HashSet { "property3" }, Properties = new Dictionary { ["property2"] = new OpenApiSchema @@ -425,7 +425,7 @@ public async Task SerializeSchemaWRequiredPropertiesAsV2JsonWorksAsync(bool prod public void SerializeAsV2ShouldSetFormatPropertyInParentSchemaIfPresentInChildrenSchema() { // Arrange - var schema = new OpenApiSchema() + var schema = new OpenApiSchema { OneOf = new List { @@ -465,7 +465,7 @@ public void SerializeAsV2ShouldSetFormatPropertyInParentSchemaIfPresentInChildre [Fact] public void OpenApiSchemaCopyConstructorSucceeds() { - var baseSchema = new OpenApiSchema() + var baseSchema = new OpenApiSchema { Type = "string", Format = "date" diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs index 418a526d0..8bb4901a0 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs @@ -26,7 +26,7 @@ public void ReviewPublicApiChanges() // It takes a human to read the change, determine if it is breaking and update the PublicApi.approved.txt with the new approved API surface // Arrange - var publicApi = typeof(OpenApiSpecVersion).Assembly.GeneratePublicApi(new ApiGeneratorOptions() { AllowNamespacePrefixes = new[] { "Microsoft.OpenApi" } } ); + var publicApi = typeof(OpenApiSpecVersion).Assembly.GeneratePublicApi(new ApiGeneratorOptions { AllowNamespacePrefixes = new[] { "Microsoft.OpenApi" } } ); // Act var approvedFilePath = Path.Combine("PublicApi", "PublicApi.approved.txt"); diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs index cf9f0b0c6..0110cadf0 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs @@ -15,27 +15,28 @@ namespace Microsoft.OpenApi.Tests.Services [UsesVerify] public class OpenApiUrlTreeNodeTests { - private OpenApiDocument OpenApiDocumentSample_1 => new OpenApiDocument() + private OpenApiDocument OpenApiDocumentSample_1 => new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { - ["/"] = new OpenApiPathItem() { - Operations = new Dictionary() + ["/"] = new OpenApiPathItem + { + Operations = new Dictionary { [OperationType.Get] = new OpenApiOperation(), } }, - ["/houses"] = new OpenApiPathItem() + ["/houses"] = new OpenApiPathItem { - Operations = new Dictionary() + Operations = new Dictionary { [OperationType.Get] = new OpenApiOperation(), [OperationType.Post] = new OpenApiOperation() } }, - ["/cars"] = new OpenApiPathItem() + ["/cars"] = new OpenApiPathItem { - Operations = new Dictionary() + Operations = new Dictionary { [OperationType.Post] = new OpenApiOperation() } @@ -43,9 +44,9 @@ public class OpenApiUrlTreeNodeTests } }; - private OpenApiDocument OpenApiDocumentSample_2 => new OpenApiDocument() + private OpenApiDocument OpenApiDocumentSample_2 => new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/"] = new OpenApiPathItem(), ["/hotels"] = new OpenApiPathItem(), @@ -64,9 +65,9 @@ public void CreateUrlSpaceWithoutOpenApiDocument() [Fact] public void CreateSingleRootWorks() { - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/"] = new OpenApiPathItem() } @@ -84,9 +85,9 @@ public void CreateSingleRootWorks() [Fact] public void CreatePathWithoutRootWorks() { - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/houses"] = new OpenApiPathItem() } @@ -154,10 +155,10 @@ public void AttachPathWorks() OperationType.Get, new OpenApiOperation { OperationId = "motorcycles.ListMotorcycle", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Retrieved entities" } @@ -179,10 +180,10 @@ public void AttachPathWorks() OperationType.Get, new OpenApiOperation { OperationId = "computers.ListComputer", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Retrieved entities" } @@ -207,9 +208,9 @@ public void AttachPathWorks() [Fact] public void CreatePathsWithMultipleSegmentsWorks() { - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/"] = new OpenApiPathItem(), ["/houses/apartments/{apartment-id}"] = new OpenApiPathItem(), @@ -232,13 +233,13 @@ public void CreatePathsWithMultipleSegmentsWorks() [Fact] public void HasOperationsWorks() { - var doc1 = new OpenApiDocument() + var doc1 = new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/"] = new OpenApiPathItem(), ["/houses"] = new OpenApiPathItem(), - ["/cars/{car-id}"] = new OpenApiPathItem() + ["/cars/{car-id}"] = new OpenApiPathItem { Operations = new Dictionary { @@ -246,10 +247,10 @@ public void HasOperationsWorks() OperationType.Get, new OpenApiOperation { OperationId = "cars.GetCar", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Retrieved entity" } @@ -262,11 +263,11 @@ public void HasOperationsWorks() } }; - var doc2 = new OpenApiDocument() + var doc2 = new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { - ["/cars/{car-id}"] = new OpenApiPathItem() + ["/cars/{car-id}"] = new OpenApiPathItem { Operations = new Dictionary { @@ -274,10 +275,10 @@ public void HasOperationsWorks() OperationType.Get, new OpenApiOperation { OperationId = "cars.GetCar", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "200", new OpenApiResponse() + "200", new OpenApiResponse { Description = "Retrieved entity" } @@ -289,10 +290,10 @@ public void HasOperationsWorks() OperationType.Put, new OpenApiOperation { OperationId = "cars.UpdateCar", - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { { - "204", new OpenApiResponse() + "204", new OpenApiResponse { Description = "Success." } @@ -326,9 +327,9 @@ public void HasOperationsWorks() [Fact] public void SegmentIsParameterWorks() { - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/"] = new OpenApiPathItem(), ["/houses/apartments/{apartment-id}"] = new OpenApiPathItem() diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs index 45cc9c3d9..813cb9517 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs @@ -30,7 +30,7 @@ public OpenApiValidatorTests(ITestOutputHelper output) public void ResponseMustHaveADescription() { var openApiDocument = new OpenApiDocument(); - openApiDocument.Info = new OpenApiInfo() + openApiDocument.Info = new OpenApiInfo { Title = "foo", Version = "1.2.2" @@ -69,7 +69,7 @@ public void ServersShouldBeReferencedByIndex() { var openApiDocument = new OpenApiDocument { - Info = new OpenApiInfo() + Info = new OpenApiInfo { Title = "foo", Version = "1.2.2" @@ -117,7 +117,7 @@ public void ValidateCustomExtension() var openApiDocument = new OpenApiDocument { - Info = new OpenApiInfo() + Info = new OpenApiInfo { Title = "foo", Version = "1.2.2" @@ -125,7 +125,7 @@ public void ValidateCustomExtension() Paths = new OpenApiPaths() }; - var fooExtension = new FooExtension() + var fooExtension = new FooExtension { Bar = "hey", Baz = "baz" diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs index d10eaf590..8188d6334 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs @@ -21,7 +21,7 @@ public void ValidateKeyMustMatchRegularExpressionInComponents() // Arrange const string key = "%@abc"; - OpenApiComponents components = new OpenApiComponents() + OpenApiComponents components = new OpenApiComponents { Responses = new Dictionary { diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs index ec6bba7b5..221c245a5 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs @@ -20,7 +20,7 @@ public void ValidateEmailFieldIsEmailAddressInContact() // Arrange const string testEmail = "support/example.com"; - OpenApiContact contact = new OpenApiContact() + OpenApiContact contact = new OpenApiContact { Email = testEmail }; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs index 6a082ec0f..429c460a4 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs @@ -22,11 +22,11 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange IEnumerable errors; - var header = new OpenApiHeader() + var header = new OpenApiHeader { Required = true, Example = new OpenApiInteger(55), - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string", } @@ -59,43 +59,43 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() // Arrange IEnumerable warnings; - var header = new OpenApiHeader() + var header = new OpenApiHeader { Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "object", - AdditionalProperties = new OpenApiSchema() + AdditionalProperties = new OpenApiSchema { Type = "integer", } }, Examples = { - ["example0"] = new OpenApiExample() + ["example0"] = new OpenApiExample { Value = new OpenApiString("1"), }, - ["example1"] = new OpenApiExample() + ["example1"] = new OpenApiExample { - Value = new OpenApiObject() - { + Value = new OpenApiObject + { ["x"] = new OpenApiInteger(2), ["y"] = new OpenApiString("20"), ["z"] = new OpenApiString("200") } }, - ["example2"] = new OpenApiExample() + ["example2"] = new OpenApiExample { Value = - new OpenApiArray() + new OpenApiArray { new OpenApiInteger(3) } }, - ["example3"] = new OpenApiExample() + ["example3"] = new OpenApiExample { - Value = new OpenApiObject() + Value = new OpenApiObject { ["x"] = new OpenApiInteger(4), ["y"] = new OpenApiInteger(40), diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs index bdffaff28..a68d91578 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs @@ -22,10 +22,10 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange IEnumerable warnings; - var mediaType = new OpenApiMediaType() + var mediaType = new OpenApiMediaType { Example = new OpenApiInteger(55), - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string", } @@ -58,42 +58,42 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() // Arrange IEnumerable warnings; - var mediaType = new OpenApiMediaType() + var mediaType = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "object", - AdditionalProperties = new OpenApiSchema() + AdditionalProperties = new OpenApiSchema { Type = "integer", } }, Examples = { - ["example0"] = new OpenApiExample() + ["example0"] = new OpenApiExample { Value = new OpenApiString("1"), }, - ["example1"] = new OpenApiExample() + ["example1"] = new OpenApiExample { - Value = new OpenApiObject() - { + Value = new OpenApiObject + { ["x"] = new OpenApiInteger(2), ["y"] = new OpenApiString("20"), ["z"] = new OpenApiString("200") } }, - ["example2"] = new OpenApiExample() + ["example2"] = new OpenApiExample { Value = - new OpenApiArray() + new OpenApiArray { new OpenApiInteger(3) } }, - ["example3"] = new OpenApiExample() + ["example3"] = new OpenApiExample { - Value = new OpenApiObject() + Value = new OpenApiObject { ["x"] = new OpenApiInteger(4), ["y"] = new OpenApiInteger(40), diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs index 89be676c5..24f28e4eb 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs @@ -41,7 +41,7 @@ public void ValidateFieldIsRequiredInParameter() public void ValidateRequiredIsTrueWhenInIsPathInParameter() { // Arrange - var parameter = new OpenApiParameter() + var parameter = new OpenApiParameter { Name = "name", In = ParameterLocation.Path @@ -66,13 +66,13 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange IEnumerable warnings; - var parameter = new OpenApiParameter() + var parameter = new OpenApiParameter { Name = "parameter1", In = ParameterLocation.Path, Required = true, Example = new OpenApiInteger(55), - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string", } @@ -105,45 +105,45 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() // Arrange IEnumerable warnings; - var parameter = new OpenApiParameter() + var parameter = new OpenApiParameter { Name = "parameter1", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "object", - AdditionalProperties = new OpenApiSchema() + AdditionalProperties = new OpenApiSchema { Type = "integer", } }, Examples = { - ["example0"] = new OpenApiExample() + ["example0"] = new OpenApiExample { Value = new OpenApiString("1"), }, - ["example1"] = new OpenApiExample() + ["example1"] = new OpenApiExample { - Value = new OpenApiObject() - { + Value = new OpenApiObject + { ["x"] = new OpenApiInteger(2), ["y"] = new OpenApiString("20"), ["z"] = new OpenApiString("200") } }, - ["example2"] = new OpenApiExample() + ["example2"] = new OpenApiExample { Value = - new OpenApiArray() + new OpenApiArray { new OpenApiInteger(3) } }, - ["example3"] = new OpenApiExample() + ["example3"] = new OpenApiExample { - Value = new OpenApiObject() + Value = new OpenApiObject { ["x"] = new OpenApiInteger(4), ["y"] = new OpenApiInteger(40), @@ -185,12 +185,12 @@ public void PathParameterNotInThePathShouldReturnAnError() // Arrange IEnumerable errors; - var parameter = new OpenApiParameter() + var parameter = new OpenApiParameter { Name = "parameter1", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string", } @@ -223,12 +223,12 @@ public void PathParameterInThePathShouldBeOk() // Arrange IEnumerable errors; - var parameter = new OpenApiParameter() + var parameter = new OpenApiParameter { Name = "parameter1", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { Type = "string", } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs index 3ed365c8d..57f9f2cae 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs @@ -24,7 +24,7 @@ public void ReferencedSchemaShouldOnlyBeValidatedOnce() var sharedSchema = new OpenApiSchema { Type = "string", - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "test" }, @@ -32,29 +32,29 @@ public void ReferencedSchemaShouldOnlyBeValidatedOnce() }; OpenApiDocument document = new OpenApiDocument(); - document.Components = new OpenApiComponents() + document.Components = new OpenApiComponents { - Schemas = new Dictionary() + Schemas = new Dictionary { [sharedSchema.Reference.Id] = sharedSchema } }; - document.Paths = new OpenApiPaths() + document.Paths = new OpenApiPaths { - ["/"] = new OpenApiPathItem() + ["/"] = new OpenApiPathItem { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation() + [OperationType.Get] = new OpenApiOperation { - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { - ["200"] = new OpenApiResponse() + ["200"] = new OpenApiResponse { - Content = new Dictionary() + Content = new Dictionary { - ["application/json"] = new OpenApiMediaType() + ["application/json"] = new OpenApiMediaType { Schema = sharedSchema } @@ -67,7 +67,7 @@ public void ReferencedSchemaShouldOnlyBeValidatedOnce() }; // Act - var errors = document.Validate(new ValidationRuleSet() { new AlwaysFailRule() }); + var errors = document.Validate(new ValidationRuleSet { new AlwaysFailRule() }); // Assert @@ -81,7 +81,7 @@ public void UnresolvedReferenceSchemaShouldNotBeValidated() var sharedSchema = new OpenApiSchema { Type = "string", - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "test" }, @@ -89,16 +89,16 @@ public void UnresolvedReferenceSchemaShouldNotBeValidated() }; OpenApiDocument document = new OpenApiDocument(); - document.Components = new OpenApiComponents() + document.Components = new OpenApiComponents { - Schemas = new Dictionary() + Schemas = new Dictionary { [sharedSchema.Reference.Id] = sharedSchema } }; // Act - var errors = document.Validate(new ValidationRuleSet() { new AlwaysFailRule() }); + var errors = document.Validate(new ValidationRuleSet { new AlwaysFailRule() }); // Assert Assert.True(errors.Count() == 0); @@ -111,7 +111,7 @@ public void UnresolvedSchemaReferencedShouldNotBeValidated() var sharedSchema = new OpenApiSchema { - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "test" }, @@ -120,21 +120,21 @@ public void UnresolvedSchemaReferencedShouldNotBeValidated() OpenApiDocument document = new OpenApiDocument(); - document.Paths = new OpenApiPaths() + document.Paths = new OpenApiPaths { - ["/"] = new OpenApiPathItem() + ["/"] = new OpenApiPathItem { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation() + [OperationType.Get] = new OpenApiOperation { - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { - ["200"] = new OpenApiResponse() + ["200"] = new OpenApiResponse { - Content = new Dictionary() + Content = new Dictionary { - ["application/json"] = new OpenApiMediaType() + ["application/json"] = new OpenApiMediaType { Schema = sharedSchema } @@ -147,7 +147,7 @@ public void UnresolvedSchemaReferencedShouldNotBeValidated() }; // Act - var errors = document.Validate(new ValidationRuleSet() { new AlwaysFailRule() }); + var errors = document.Validate(new ValidationRuleSet { new AlwaysFailRule() }); // Assert Assert.True(errors.Count() == 0); diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs index 04acf7737..3ea545af9 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs @@ -22,7 +22,7 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange IEnumerable warnings; - var schema = new OpenApiSchema() + var schema = new OpenApiSchema { Default = new OpenApiInteger(55), Type = "string", @@ -53,7 +53,7 @@ public void ValidateExampleAndDefaultShouldNotHaveDataTypeMismatchForSimpleSchem { // Arrange IEnumerable warnings; - var schema = new OpenApiSchema() + var schema = new OpenApiSchema { Example = new OpenApiLong(55), Default = new OpenApiPassword("1234"), @@ -87,29 +87,29 @@ public void ValidateEnumShouldNotHaveDataTypeMismatchForSimpleSchema() { // Arrange IEnumerable warnings; - var schema = new OpenApiSchema() + var schema = new OpenApiSchema { Enum = { new OpenApiString("1"), - new OpenApiObject() + new OpenApiObject { ["x"] = new OpenApiInteger(2), ["y"] = new OpenApiString("20"), ["z"] = new OpenApiString("200") }, - new OpenApiArray() + new OpenApiArray { new OpenApiInteger(3) }, - new OpenApiObject() + new OpenApiObject { ["x"] = new OpenApiInteger(4), ["y"] = new OpenApiInteger(40), }, }, Type = "object", - AdditionalProperties = new OpenApiSchema() + AdditionalProperties = new OpenApiSchema { Type = "integer", } @@ -146,54 +146,54 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForComplexSchema() { // Arrange IEnumerable warnings; - var schema = new OpenApiSchema() + var schema = new OpenApiSchema { Type = "object", Properties = { - ["property1"] = new OpenApiSchema() + ["property1"] = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "integer", Format = "int64" } }, - ["property2"] = new OpenApiSchema() + ["property2"] = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema() + Items = new OpenApiSchema { Type = "object", - AdditionalProperties = new OpenApiSchema() + AdditionalProperties = new OpenApiSchema { Type = "boolean" } } }, - ["property3"] = new OpenApiSchema() + ["property3"] = new OpenApiSchema { Type = "string", Format = "password" }, - ["property4"] = new OpenApiSchema() + ["property4"] = new OpenApiSchema { Type = "string" } }, - Default = new OpenApiObject() + Default = new OpenApiObject { - ["property1"] = new OpenApiArray() + ["property1"] = new OpenApiArray { new OpenApiInteger(12), new OpenApiLong(13), new OpenApiString("1"), }, - ["property2"] = new OpenApiArray() + ["property2"] = new OpenApiArray { new OpenApiInteger(2), - new OpenApiObject() + new OpenApiObject { ["x"] = new OpenApiBoolean(true), ["y"] = new OpenApiBoolean(false), diff --git a/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs b/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs index fc947da20..58d4d3d4c 100644 --- a/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs @@ -32,14 +32,15 @@ public void LocateTopLevelObjects() [Fact] public void LocateTopLevelArrayItems() { - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Servers = new List() { + Servers = new List + { new OpenApiServer(), new OpenApiServer() }, Paths = new OpenApiPaths(), - Tags = new List() + Tags = new List { new OpenApiTag() } @@ -66,15 +67,15 @@ public void LocatePathOperationContentSchema() { Paths = new OpenApiPaths() }; - doc.Paths.Add("/test", new OpenApiPathItem() + doc.Paths.Add("/test", new OpenApiPathItem { - Operations = new Dictionary() + Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation() + [OperationType.Get] = new OpenApiOperation { - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { - ["200"] = new OpenApiResponse() + ["200"] = new OpenApiResponse { Content = new Dictionary { @@ -117,21 +118,21 @@ public void LocatePathOperationContentSchema() [Fact] public void WalkDOMWithCycles() { - var loopySchema = new OpenApiSchema() + var loopySchema = new OpenApiSchema { Type = "object", - Properties = new Dictionary() + Properties = new Dictionary { - ["name"] = new OpenApiSchema() { Type = "string" } + ["name"] = new OpenApiSchema { Type = "string" } } }; loopySchema.Properties.Add("parent", loopySchema); - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { Paths = new OpenApiPaths(), - Components = new OpenApiComponents() + Components = new OpenApiComponents { Schemas = new Dictionary { @@ -161,9 +162,9 @@ public void WalkDOMWithCycles() public void LocateReferences() { - var baseSchema = new OpenApiSchema() + var baseSchema = new OpenApiSchema { - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "base", Type = ReferenceType.Schema @@ -173,8 +174,8 @@ public void LocateReferences() var derivedSchema = new OpenApiSchema { - AnyOf = new List() { baseSchema }, - Reference = new OpenApiReference() + AnyOf = new List { baseSchema }, + Reference = new OpenApiReference { Id = "derived", Type = ReferenceType.Schema @@ -182,10 +183,10 @@ public void LocateReferences() UnresolvedReference = false }; - var testHeader = new OpenApiHeader() + var testHeader = new OpenApiHeader { Schema = derivedSchema, - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "test-header", Type = ReferenceType.Header @@ -195,26 +196,26 @@ public void LocateReferences() var doc = new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { - ["/"] = new OpenApiPathItem() + ["/"] = new OpenApiPathItem { - Operations = new Dictionary() + Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation() + [OperationType.Get] = new OpenApiOperation { - Responses = new OpenApiResponses() + Responses = new OpenApiResponses { - ["200"] = new OpenApiResponse() + ["200"] = new OpenApiResponse { - Content = new Dictionary() + Content = new Dictionary { - ["application/json"] = new OpenApiMediaType() + ["application/json"] = new OpenApiMediaType { Schema = derivedSchema } }, - Headers = new Dictionary() + Headers = new Dictionary { ["test-header"] = testHeader } @@ -224,14 +225,14 @@ public void LocateReferences() } } }, - Components = new OpenApiComponents() + Components = new OpenApiComponents { - Schemas = new Dictionary() + Schemas = new Dictionary { ["derived"] = derivedSchema, ["base"] = baseSchema, }, - Headers = new Dictionary() + Headers = new Dictionary { ["test-header"] = testHeader } diff --git a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs index 2bae02b1f..d3c44c29b 100644 --- a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs +++ b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs @@ -18,7 +18,7 @@ public class OpenApiReferencableTests private static readonly OpenApiCallback _callbackFragment = new OpenApiCallback(); private static readonly OpenApiExample _exampleFragment = new OpenApiExample(); private static readonly OpenApiLink _linkFragment = new OpenApiLink(); - private static readonly OpenApiHeader _headerFragment = new OpenApiHeader() + private static readonly OpenApiHeader _headerFragment = new OpenApiHeader { Schema = new OpenApiSchema(), Examples = new Dictionary @@ -35,7 +35,7 @@ public class OpenApiReferencableTests } }; private static readonly OpenApiRequestBody _requestBodyFragment = new OpenApiRequestBody(); - private static readonly OpenApiResponse _responseFragment = new OpenApiResponse() + private static readonly OpenApiResponse _responseFragment = new OpenApiResponse { Headers = new Dictionary { diff --git a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs index 63045847b..6e1ff7bf8 100644 --- a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs @@ -31,25 +31,27 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther() { var workspace = new OpenApiWorkspace(); - workspace.AddDocument("root", new OpenApiDocument() { - Paths = new OpenApiPaths() + workspace.AddDocument("root", new OpenApiDocument + { + Paths = new OpenApiPaths { - ["/"] = new OpenApiPathItem() + ["/"] = new OpenApiPathItem { - Operations = new Dictionary() + Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation() { - Responses = new OpenApiResponses() + [OperationType.Get] = new OpenApiOperation + { + Responses = new OpenApiResponses { - ["200"] = new OpenApiResponse() + ["200"] = new OpenApiResponse { - Content = new Dictionary() + Content = new Dictionary { - ["application/json"] = new OpenApiMediaType() + ["application/json"] = new OpenApiMediaType { - Schema = new OpenApiSchema() + Schema = new OpenApiSchema { - Reference = new OpenApiReference() + Reference = new OpenApiReference { Id = "test", Type = ReferenceType.Schema @@ -64,11 +66,13 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther() } } }); - workspace.AddDocument("common", new OpenApiDocument() { - Components = new OpenApiComponents() + workspace.AddDocument("common", new OpenApiDocument + { + Components = new OpenApiComponents { Schemas = { - ["test"] = new OpenApiSchema() { + ["test"] = new OpenApiSchema + { Type = "string", Description = "The referenced one" } @@ -84,7 +88,7 @@ public void OpenApiWorkspacesCanResolveExternalReferences() { var workspace = new OpenApiWorkspace(); workspace.AddDocument("common", CreateCommonDocument()); - var schema = workspace.ResolveReference(new OpenApiReference() + var schema = workspace.ResolveReference(new OpenApiReference { Id = "test", Type = ReferenceType.Schema, @@ -109,7 +113,7 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther_short() { re.Description = "Success"; re.CreateContent("application/json", co => - co.Schema = new OpenApiSchema() + co.Schema = new OpenApiSchema { Reference = new OpenApiReference() // Reference { @@ -165,7 +169,7 @@ public void OpenApiWorkspacesCanResolveReferencesToDocumentFragments() workspace.AddFragment("fragment", schemaFragment); // Act - var schema = workspace.ResolveReference(new OpenApiReference() + var schema = workspace.ResolveReference(new OpenApiReference { ExternalResource = "fragment" }) as OpenApiSchema; @@ -180,7 +184,7 @@ public void OpenApiWorkspacesCanResolveReferencesToDocumentFragmentsWithJsonPoin { // Arrange var workspace = new OpenApiWorkspace(); - var responseFragment = new OpenApiResponse() + var responseFragment = new OpenApiResponse { Headers = new Dictionary { @@ -190,7 +194,7 @@ public void OpenApiWorkspacesCanResolveReferencesToDocumentFragmentsWithJsonPoin workspace.AddFragment("fragment", responseFragment); // Act - var resolvedElement = workspace.ResolveReference(new OpenApiReference() + var resolvedElement = workspace.ResolveReference(new OpenApiReference { Id = "headers/header1", ExternalResource = "fragment" @@ -205,12 +209,13 @@ public void OpenApiWorkspacesCanResolveReferencesToDocumentFragmentsWithJsonPoin private static OpenApiDocument CreateCommonDocument() { - return new OpenApiDocument() + return new OpenApiDocument { - Components = new OpenApiComponents() + Components = new OpenApiComponents { Schemas = { - ["test"] = new OpenApiSchema() { + ["test"] = new OpenApiSchema + { Type = "string", Description = "The referenced one" } diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs index 1a15ea3b4..13f70f1e9 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs @@ -424,7 +424,7 @@ public void WriteInlineSchemaV2() private static OpenApiDocument CreateDocWithSimpleSchemaToInline() { // Arrange - var thingSchema = new OpenApiSchema() + var thingSchema = new OpenApiSchema { Type = "object", UnresolvedReference = false, @@ -435,24 +435,26 @@ private static OpenApiDocument CreateDocWithSimpleSchemaToInline() } }; - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Info = new OpenApiInfo() + Info = new OpenApiInfo { Title = "Demo", Version = "1.0.0" }, - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/"] = new OpenApiPathItem { Operations = { - [OperationType.Get] = new OpenApiOperation() { + [OperationType.Get] = new OpenApiOperation + { Responses = { ["200"] = new OpenApiResponse { Description = "OK", Content = { - ["application/json"] = new OpenApiMediaType() { + ["application/json"] = new OpenApiMediaType + { Schema = thingSchema } } @@ -531,7 +533,7 @@ public void WriteInlineRecursiveSchema() private static OpenApiDocument CreateDocWithRecursiveSchemaReference() { - var thingSchema = new OpenApiSchema() + var thingSchema = new OpenApiSchema { Type = "object", UnresolvedReference = false, @@ -543,31 +545,33 @@ private static OpenApiDocument CreateDocWithRecursiveSchemaReference() }; thingSchema.Properties["children"] = thingSchema; - var relatedSchema = new OpenApiSchema() + var relatedSchema = new OpenApiSchema { Type = "integer", }; thingSchema.Properties["related"] = relatedSchema; - var doc = new OpenApiDocument() + var doc = new OpenApiDocument { - Info = new OpenApiInfo() + Info = new OpenApiInfo { Title = "Demo", Version = "1.0.0" }, - Paths = new OpenApiPaths() + Paths = new OpenApiPaths { ["/"] = new OpenApiPathItem { Operations = { - [OperationType.Get] = new OpenApiOperation() { + [OperationType.Get] = new OpenApiOperation + { Responses = { ["200"] = new OpenApiResponse { Description = "OK", Content = { - ["application/json"] = new OpenApiMediaType() { + ["application/json"] = new OpenApiMediaType + { Schema = thingSchema } } From 545d4b392bfc273fa5e182d130738a9f5a36d82f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:20:00 +1100 Subject: [PATCH 642/855] remove some usings --- src/Microsoft.OpenApi.Hidi/Program.cs | 1 - .../Interface/IOpenApiVersionService.cs | 1 - .../OpenApiYamlDocumentReader.cs | 1 - .../ParseNodes/AnyMapFieldMapParameter.cs | 1 - src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs | 2 -- src/Microsoft.OpenApi.Readers/ReadResult.cs | 5 ----- .../Services/OpenApiWorkspaceLoader.cs | 4 ---- .../V2/OpenApiInfoDeserializer.cs | 1 - .../V2/OpenApiXmlDeserializer.cs | 1 - .../V3/OpenApiComponentsDeserializer.cs | 2 -- .../V3/OpenApiDocumentDeserializer.cs | 3 --- .../V3/OpenApiEncodingDeserializer.cs | 1 - .../V3/OpenApiMediaTypeDeserializer.cs | 4 ---- .../V3/OpenApiSchemaDeserializer.cs | 1 - src/Microsoft.OpenApi.Workbench/MainModel.cs | 1 - src/Microsoft.OpenApi.Workbench/StatsVisitor.cs | 3 --- src/Microsoft.OpenApi/Any/OpenApiArray.cs | 1 - .../Extensions/OpenAPIWriterExtensions.cs | 5 ----- src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiContact.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiLicense.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiLink.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiTag.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiXml.cs | 1 - src/Microsoft.OpenApi/Services/LoopDetector.cs | 3 --- src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs | 5 ----- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 1 - src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs | 3 --- .../Validations/OpenApiValidatiorWarning.cs | 6 +----- src/Microsoft.OpenApi/Validations/OpenApiValidator.cs | 1 - .../Validations/OpenApiValidatorError.cs | 5 ----- .../Validations/Rules/OpenApiExtensionRules.cs | 1 - .../Validations/Rules/OpenApiHeaderRules.cs | 2 -- src/Microsoft.OpenApi/Validations/ValidationExtensions.cs | 7 ------- src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs | 1 - .../Services/OpenApiServiceTests.cs | 1 - .../UtilityFiles/OpenApiDocumentMock.cs | 2 -- .../OpenApiReaderTests/OpenApiDiagnosticTests.cs | 1 - .../ReferenceService/TryLoadReferenceV2Tests.cs | 5 ----- .../V2Tests/OpenApiDocumentTests.cs | 3 --- .../V2Tests/OpenApiHeaderTests.cs | 1 - .../V2Tests/OpenApiOperationTests.cs | 1 - .../V2Tests/OpenApiPathItemTests.cs | 2 -- .../V2Tests/OpenApiSchemaTests.cs | 1 - .../V3Tests/OpenApiDocumentTests.cs | 4 ---- .../V3Tests/OpenApiResponseTests.cs | 5 ----- test/Microsoft.OpenApi.SmokeTests/GraphTests.cs | 4 ---- test/Microsoft.OpenApi.SmokeTests/WorkspaceTests.cs | 8 +------- .../OpenApiEnumValuesDescriptionExtensionTests.cs | 4 +--- .../OpenApiPrimaryErrorMessageExtensionTests.cs | 1 - .../Models/OpenApiDocumentTests.cs | 2 -- .../Models/OpenApiOperationTests.cs | 1 - .../Validations/OpenApiComponentsValidationTests.cs | 1 - .../Validations/OpenApiContactValidationTests.cs | 2 -- .../Validations/OpenApiExternalDocsValidationTests.cs | 2 -- .../Validations/OpenApiHeaderValidationTests.cs | 3 --- .../Validations/OpenApiInfoValidationTests.cs | 2 -- .../Validations/OpenApiMediaTypeValidationTests.cs | 3 --- .../Validations/OpenApiReferenceValidationTests.cs | 3 --- .../Validations/OpenApiServerValidationTests.cs | 1 - .../Validations/OpenApiTagValidationTests.cs | 1 - test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs | 5 +---- .../Workspaces/OpenApiWorkspaceTests.cs | 2 -- 69 files changed, 4 insertions(+), 153 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Program.cs b/src/Microsoft.OpenApi.Hidi/Program.cs index b8508ab5f..13c355cce 100644 --- a/src/Microsoft.OpenApi.Hidi/Program.cs +++ b/src/Microsoft.OpenApi.Hidi/Program.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.CommandLine; -using System.CommandLine.Parsing; using System.Threading.Tasks; using Microsoft.OpenApi.Hidi.Handlers; using Microsoft.OpenApi.Hidi.Options; diff --git a/src/Microsoft.OpenApi.Readers/Interface/IOpenApiVersionService.cs b/src/Microsoft.OpenApi.Readers/Interface/IOpenApiVersionService.cs index a7a98d781..9ba9e83a5 100644 --- a/src/Microsoft.OpenApi.Readers/Interface/IOpenApiVersionService.cs +++ b/src/Microsoft.OpenApi.Readers/Interface/IOpenApiVersionService.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 4a120cbbf..5a5d81d8e 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMapParameter.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMapParameter.cs index 1aa899978..a50c46324 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMapParameter.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMapParameter.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.Readers.ParseNodes diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs index 295b02bf3..f57f4927c 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs @@ -3,9 +3,7 @@ using System; using System.Collections.Generic; -using System.Text.RegularExpressions; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.Exceptions; diff --git a/src/Microsoft.OpenApi.Readers/ReadResult.cs b/src/Microsoft.OpenApi.Readers/ReadResult.cs index 7479d345f..80b31316a 100644 --- a/src/Microsoft.OpenApi.Readers/ReadResult.cs +++ b/src/Microsoft.OpenApi.Readers/ReadResult.cs @@ -1,11 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.Readers diff --git a/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs b/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs index 79f6206d0..3ba8ed2a3 100644 --- a/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs index 5854672d3..ea17c850d 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System; -using System.Collections.Generic; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs index ac7db2db6..9824bc477 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System; -using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.Exceptions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs index 30d711d33..b7f78a355 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs @@ -1,9 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs index df1434cd9..8eced2903 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs index fc2f990e7..d965a7a58 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs index c8bd3d240..c0e9ffd75 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs @@ -1,10 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs index 60727c4bb..480b69fb4 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Workbench/MainModel.cs b/src/Microsoft.OpenApi.Workbench/MainModel.cs index 70074736b..f28d4fcee 100644 --- a/src/Microsoft.OpenApi.Workbench/MainModel.cs +++ b/src/Microsoft.OpenApi.Workbench/MainModel.cs @@ -4,7 +4,6 @@ using System; using System.ComponentModel; using System.Diagnostics; -using System.Globalization; using System.IO; using System.Net.Http; using System.Text; diff --git a/src/Microsoft.OpenApi.Workbench/StatsVisitor.cs b/src/Microsoft.OpenApi.Workbench/StatsVisitor.cs index 85faef630..c8cf28799 100644 --- a/src/Microsoft.OpenApi.Workbench/StatsVisitor.cs +++ b/src/Microsoft.OpenApi.Workbench/StatsVisitor.cs @@ -3,9 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Services; diff --git a/src/Microsoft.OpenApi/Any/OpenApiArray.cs b/src/Microsoft.OpenApi/Any/OpenApiArray.cs index 2c877d631..4e0317437 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiArray.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiArray.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using Microsoft.OpenApi.Writers; -using System; using System.Collections.Generic; namespace Microsoft.OpenApi.Any diff --git a/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs index a32807ab6..7181c3b38 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs @@ -1,9 +1,4 @@ using Microsoft.OpenApi.Writers; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Microsoft.OpenApi { diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs index 7abd1bfdd..2969168c8 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; namespace Microsoft.OpenApi.Interfaces { diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 93cb11bca..113c91b13 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 345f07d59..91d750e6c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index df0aa0a49..e903c8947 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 866515835..e22441dc3 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index b682744e9..801ef2ce1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index 9c12fb5a9..a9cd2b7df 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index 8443e6730..d9e71510c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 616a6a022..64a65bf83 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -3,8 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index 70164bc59..4512f76dc 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index ba4129142..a0bae5015 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index c6719d85e..1fb18d508 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Services/LoopDetector.cs b/src/Microsoft.OpenApi/Services/LoopDetector.cs index 249cab51d..1a796f60b 100644 --- a/src/Microsoft.OpenApi/Services/LoopDetector.cs +++ b/src/Microsoft.OpenApi/Services/LoopDetector.cs @@ -1,8 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Microsoft.OpenApi.Services { diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs index 7e2ebdcac..d27a0a47a 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs @@ -1,11 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 9f4ccb8be..9a2db5883 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.IO; using System.Linq; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs index 7827a50c1..c2ee18870 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs @@ -4,9 +4,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs index 77480584d..5a22ff621 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Microsoft.OpenApi.Exceptions; -using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.Validations { diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index a0aee12e7..997da26e2 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Services; diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidatorError.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidatorError.cs index c24d48fe3..95f60dedd 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidatorError.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidatorError.cs @@ -1,11 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.Validations diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs index c44983ffb..ef11e23e2 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs @@ -3,7 +3,6 @@ using System; using Microsoft.OpenApi.Interfaces; -using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; namespace Microsoft.OpenApi.Validations.Rules diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs index 9ffbc38f4..b5e66134b 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs @@ -1,9 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using Microsoft.OpenApi.Models; -using Microsoft.OpenApi.Properties; namespace Microsoft.OpenApi.Validations.Rules { diff --git a/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs b/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs index 195df89cd..b951cc393 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs @@ -1,13 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.OpenApi.Models; - namespace Microsoft.OpenApi.Validations { /// diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs index 4d7f11032..fe24f460c 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.IO; using Microsoft.OpenApi.Exceptions; -using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; namespace Microsoft.OpenApi.Writers diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index 9d73c8db6..fd620502d 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -3,7 +3,6 @@ using System.CommandLine; using System.CommandLine.Invocation; -using System.CommandLine.Parsing; using System.Text.Json; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; diff --git a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs index 58b85d91d..3f5604ff0 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System.Collections.Generic; -using System.Security.Policy; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs index 23c23b4d6..bb555b264 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs @@ -7,7 +7,6 @@ using FluentAssertions; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Models; -using Microsoft.OpenApi.Readers.Tests.OpenApiWorkspaceTests; using Xunit; using Microsoft.OpenApi.Readers.Interface; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs index a641b7d6f..420314f07 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs @@ -1,15 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using System.IO; -using System.Linq; using FluentAssertions; using Microsoft.OpenApi.Models; -using Microsoft.OpenApi.Readers.ParseNodes; -using Microsoft.OpenApi.Readers.V2; -using SharpYaml.Serialization; using Xunit; namespace Microsoft.OpenApi.Readers.Tests.ReferenceService diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index ac5f99a86..5a0d6c734 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -8,10 +8,7 @@ using FluentAssertions; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Exceptions; -using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; -using Microsoft.OpenApi.Writers; using Xunit; namespace Microsoft.OpenApi.Readers.Tests.V2Tests diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs index 7a98c7a6d..7de477ce9 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System.Collections.Generic; using System.IO; using FluentAssertions; using Microsoft.OpenApi.Any; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs index 3b0f32871..e6667a51e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs @@ -7,7 +7,6 @@ using FluentAssertions; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; -using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; using Microsoft.OpenApi.Readers.V2; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs index a11497cdf..29b4c7a4e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs @@ -4,9 +4,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using FluentAssertions; -using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; using Microsoft.OpenApi.Readers.V2; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSchemaTests.cs index 9a75e5c8d..9179964bf 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSchemaTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System.Collections.Generic; using System.IO; using FluentAssertions; using Microsoft.OpenApi.Any; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 8a0da3481..699e8b749 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -3,21 +3,17 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; -using System.Text; using System.Threading; using FluentAssertions; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Validations; using Microsoft.OpenApi.Validations.Rules; using Microsoft.OpenApi.Writers; -using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs index 60e3db6e4..f73bc1608 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs @@ -3,11 +3,6 @@ using System.IO; using System.Linq; -using FluentAssertions; -using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Models; -using Microsoft.OpenApi.Readers.ParseNodes; -using Microsoft.OpenApi.Readers.V3; using Xunit; namespace Microsoft.OpenApi.Readers.Tests.V3Tests diff --git a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs index de3101e27..8308102dd 100644 --- a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs +++ b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs @@ -2,12 +2,8 @@ using Microsoft.OpenApi.Readers; using Microsoft.OpenApi.Services; using System; -using System.Collections.Generic; -using System.Linq; using System.Net; using System.Net.Http; -using System.Text; -using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; diff --git a/test/Microsoft.OpenApi.SmokeTests/WorkspaceTests.cs b/test/Microsoft.OpenApi.SmokeTests/WorkspaceTests.cs index 84f9d74ad..0d0056fe3 100644 --- a/test/Microsoft.OpenApi.SmokeTests/WorkspaceTests.cs +++ b/test/Microsoft.OpenApi.SmokeTests/WorkspaceTests.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Microsoft.OpenApi.SmokeTests +namespace Microsoft.OpenApi.SmokeTests { public class WorkspaceTests { diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtensionTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtensionTests.cs index 571c28461..e8ea2fe07 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtensionTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtensionTests.cs @@ -1,8 +1,6 @@ -using System.Collections.Generic; -using System.IO; +using System.IO; using Microsoft.OpenApi.MicrosoftExtensions; using Microsoft.OpenApi.Writers; -using Moq; using Xunit; namespace Microsoft.OpenApi.Tests.MicrosoftExtensions; diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs index 6b400671b..89c427935 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs @@ -3,7 +3,6 @@ // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------ -using System; using System.IO; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Writers; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 924699bdf..7c017c2ce 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -5,14 +5,12 @@ using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers; -using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Writers; using VerifyXunit; using Xunit; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index de56df52e..ef28ecb8f 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -6,7 +6,6 @@ using FluentAssertions; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; -using NuGet.Frameworks; using Xunit; using Xunit.Abstractions; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs index d10eaf590..b9c230d92 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs @@ -7,7 +7,6 @@ using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; -using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Validations.Rules; using Xunit; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs index ec6bba7b5..157967037 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs @@ -2,12 +2,10 @@ // Licensed under the MIT license. using System; -using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; -using Microsoft.OpenApi.Services; using Xunit; namespace Microsoft.OpenApi.Validations.Tests diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs index fee728f76..d93951f12 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs @@ -2,12 +2,10 @@ // Licensed under the MIT license. using System; -using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; -using Microsoft.OpenApi.Services; using Xunit; namespace Microsoft.OpenApi.Validations.Tests diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs index 6a082ec0f..897de89b1 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs @@ -1,14 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; -using Microsoft.OpenApi.Properties; using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Validations.Rules; using Xunit; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs index 1a58fff04..f3006d2cd 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs @@ -2,12 +2,10 @@ // Licensed under the MIT license. using System; -using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; -using Microsoft.OpenApi.Services; using Xunit; namespace Microsoft.OpenApi.Validations.Tests diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs index bdffaff28..aacb83f42 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs @@ -1,14 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; -using Microsoft.OpenApi.Properties; using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Validations.Rules; using Xunit; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs index 3ed365c8d..eb8809f18 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs @@ -1,11 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs index bbc4c7e10..b09b14f3b 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs @@ -6,7 +6,6 @@ using System.Linq; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; -using Microsoft.OpenApi.Services; using Xunit; namespace Microsoft.OpenApi.Validations.Tests diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs index a039b39c2..49f5643d8 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs @@ -8,7 +8,6 @@ using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; -using Microsoft.OpenApi.Services; using Xunit; namespace Microsoft.OpenApi.Validations.Tests diff --git a/test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs b/test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs index 102100019..4adfe9da4 100644 --- a/test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs @@ -1,9 +1,6 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; -using System.Text; -using System.Threading.Tasks; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Services; diff --git a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs index 63045847b..a01d720cb 100644 --- a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Services; using Xunit; From b23a53a66f77dceba3e8b251639847c5d080947d Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:48:02 +1100 Subject: [PATCH 643/855] use some raw strings --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 55 +- .../OpenApiWorkspaceStreamTests.cs | 12 +- .../ParseNodeTests.cs | 44 +- .../ParseNodes/OpenApiAnyConverterTests.cs | 162 ++-- .../ParseNodes/OpenApiAnyTests.cs | 34 +- .../TestCustomExtension.cs | 21 +- .../V2Tests/OpenApiContactTests.cs | 15 +- .../V2Tests/OpenApiDocumentTests.cs | 98 +-- .../V2Tests/OpenApiServerTests.cs | 234 +++--- .../V3Tests/OpenApiContactTests.cs | 15 +- .../V3Tests/OpenApiDocumentTests.cs | 49 +- .../V3Tests/OpenApiSchemaTests.cs | 53 +- .../Models/OpenApiComponentsTests.cs | 383 ++++----- .../Models/OpenApiContactTests.cs | 24 +- .../Models/OpenApiDocumentTests.cs | 179 +++-- .../Models/OpenApiEncodingTests.cs | 24 +- .../Models/OpenApiExternalDocsTests.cs | 16 +- .../Models/OpenApiInfoTests.cs | 90 ++- .../Models/OpenApiLicenseTests.cs | 28 +- .../Models/OpenApiMediaTypeTests.cs | 311 ++++---- .../Models/OpenApiOAuthFlowTests.cs | 44 +- .../Models/OpenApiOAuthFlowsTests.cs | 56 +- .../Models/OpenApiOperationTests.cs | 727 +++++++++--------- .../Models/OpenApiParameterTests.cs | 85 +- .../Models/OpenApiReferenceTests.cs | 36 +- .../Models/OpenApiResponseTests.cs | 189 ++--- .../Models/OpenApiSchemaTests.cs | 202 ++--- .../Models/OpenApiSecurityRequirementTests.cs | 88 ++- .../Models/OpenApiSecuritySchemeTests.cs | 150 ++-- .../Models/OpenApiServerTests.cs | 54 +- .../Models/OpenApiServerVariableTests.cs | 30 +- .../Models/OpenApiTagTests.cs | 28 +- .../Models/OpenApiXmlTests.cs | 32 +- .../Writers/OpenApiYamlWriterTests.cs | 326 ++++---- 34 files changed, 2089 insertions(+), 1805 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index b3e66cfe2..79c427e27 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -662,18 +662,21 @@ internal static void WriteTreeDocumentAsHtml(string sourceUrl, OpenApiDocument d { var rootNode = OpenApiUrlTreeNode.Create(document, "main"); - writer.WriteLine(@" - - - - - - -"); + writer.WriteLine( + """ + + + + + + + + + """); writer.WriteLine("

" + document.Info.Title + "

"); writer.WriteLine(); writer.WriteLine($"

API Description: {sourceUrl}

"); @@ -684,6 +687,7 @@ internal static void WriteTreeDocumentAsHtml(string sourceUrl, OpenApiDocument d { writer.WriteLine($"{style.Key.Replace("_", " ", StringComparison.OrdinalIgnoreCase)}"); } + writer.WriteLine(""); writer.WriteLine("
"); writer.WriteLine(""); @@ -691,18 +695,21 @@ internal static void WriteTreeDocumentAsHtml(string sourceUrl, OpenApiDocument d writer.WriteLine(""); // Write script tag to include JS library for rendering markdown - writer.WriteLine(@""); + writer.WriteLine( + """ + + """); // Write script tag to include JS library for rendering mermaid writer.WriteLine(" { diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs index 71489d39f..c80c05a4f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs @@ -13,13 +13,14 @@ public class OpenApiContactTests [Fact] public void ParseStringContactFragmentShouldSucceed() { - var input = @" -{ - ""name"": ""API Support"", - ""url"": ""http://www.swagger.io/support"", - ""email"": ""support@swagger.io"" -} -"; + var input = + """ + { + "name": "API Support", + "url": "http://www.swagger.io/support", + "email": "support@swagger.io" + } + """; var reader = new OpenApiStringReader(); var diagnostic = new OpenApiDiagnostic(); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index ac5f99a86..b53be6f28 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -22,26 +22,24 @@ public class OpenApiDocumentTests { private const string SampleFolderPath = "V2Tests/Samples/"; - - - [Fact] public void ShouldThrowWhenReferenceTypeIsInvalid() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -paths: - '/': - get: - responses: - '200': - description: ok - schema: - $ref: '#/defi888nition/does/notexist' -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + paths: + '/': + get: + responses: + '200': + description: ok + schema: + $ref: '#/defi888nition/does/notexist' + """; var reader = new OpenApiStringReader(); var doc = reader.Read(input, out var diagnostic); @@ -54,21 +52,22 @@ public void ShouldThrowWhenReferenceTypeIsInvalid() [Fact] public void ShouldThrowWhenReferenceDoesNotExist() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -paths: - '/': - get: - produces: ['application/json'] - responses: - '200': - description: ok - schema: - $ref: '#/definitions/doesnotexist' -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + paths: + '/': + get: + produces: ['application/json'] + responses: + '200': + description: ok + schema: + $ref: '#/definitions/doesnotexist' + """; var reader = new OpenApiStringReader(); @@ -91,23 +90,24 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture); var openApiDoc = new OpenApiStringReader().Read( - @" -swagger: 2.0 -info: - title: Simple Document - version: 0.9.1 - x-extension: 2.335 -definitions: - sampleSchema: - type: object - properties: - sampleProperty: - type: double - minimum: 100.54 - maximum: 60000000.35 - exclusiveMaximum: true - exclusiveMinimum: false -paths: {}", + """ + swagger: 2.0 + info: + title: Simple Document + version: 0.9.1 + x-extension: 2.335 + definitions: + sampleSchema: + type: object + properties: + sampleProperty: + type: double + minimum: 100.54 + maximum: 60000000.35 + exclusiveMaximum: true + exclusiveMinimum: false + paths: {} + """, out var context); openApiDoc.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs index bf0fe7b78..7b0983d3d 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs @@ -11,13 +11,14 @@ public class OpenApiServerTests [Fact] public void NoServer() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { }); @@ -30,15 +31,16 @@ public void NoServer() [Fact] public void JustSchemeNoDefault() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -schemes: - - http -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + schemes: + - http + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { }); @@ -51,14 +53,16 @@ public void JustSchemeNoDefault() [Fact] public void JustHostNoDefault() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -host: www.foo.com -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + host: www.foo.com + paths: {} + + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { }); @@ -73,16 +77,17 @@ public void JustHostNoDefault() [Fact] public void NoBasePath() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -host: www.foo.com -schemes: - - http -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + host: www.foo.com + schemes: + - http + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://www.foo.com/spec.yaml") @@ -98,14 +103,15 @@ public void NoBasePath() [Fact] public void JustBasePathNoDefault() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -basePath: /baz -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + basePath: /baz + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { }); @@ -120,15 +126,16 @@ public void JustBasePathNoDefault() [Fact] public void JustSchemeWithCustomHost() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -schemes: - - http -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + schemes: + - http + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://bing.com/foo") @@ -144,15 +151,16 @@ public void JustSchemeWithCustomHost() [Fact] public void JustSchemeWithCustomHostWithEmptyPath() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -schemes: - - http -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + schemes: + - http + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://bing.com") @@ -168,14 +176,15 @@ public void JustSchemeWithCustomHostWithEmptyPath() [Fact] public void JustBasePathWithCustomHost() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -basePath: /api -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + basePath: /api + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://bing.com") @@ -191,14 +200,15 @@ public void JustBasePathWithCustomHost() [Fact] public void JustHostWithCustomHost() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -host: www.example.com -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + host: www.example.com + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://bing.com") @@ -214,14 +224,15 @@ public void JustHostWithCustomHost() [Fact] public void JustHostWithCustomHostWithApi() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -host: prod.bing.com -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + host: prod.bing.com + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://dev.bing.com/api/description.yaml") @@ -237,16 +248,17 @@ public void JustHostWithCustomHostWithApi() [Fact] public void MultipleServers() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -schemes: - - http - - https -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + schemes: + - http + - https + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://dev.bing.com/api") @@ -263,14 +275,15 @@ public void MultipleServers() [Fact] public void LocalHostWithCustomHost() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -host: localhost:23232 -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + host: localhost:23232 + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://bing.com") @@ -286,14 +299,15 @@ public void LocalHostWithCustomHost() [Fact] public void InvalidHostShouldYieldError() { - var input = @" -swagger: 2.0 -info: - title: test - version: 1.0.0 -host: http://test.microsoft.com -paths: {} -"; + var input = + """ + swagger: 2.0 + info: + title: test + version: 1.0.0 + host: http://test.microsoft.com + paths: {} + """; var reader = new OpenApiStringReader(new OpenApiReaderSettings() { BaseUrl = new Uri("https://bing.com") diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs index be78f942b..7e4cfad75 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs @@ -13,13 +13,14 @@ public class OpenApiContactTests [Fact] public void ParseStringContactFragmentShouldSucceed() { - var input = @" -{ - ""name"": ""API Support"", - ""url"": ""http://www.swagger.io/support"", - ""email"": ""support@swagger.io"" -} -"; + var input = + """ + { + "name": "API Support", + "url": "http://www.swagger.io/support", + "email": "support@swagger.io" + } + """; var reader = new OpenApiStringReader(); var diagnostic = new OpenApiDiagnostic(); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 8a0da3481..6356b105c 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -84,12 +84,14 @@ public OpenApiDocumentTests(ITestOutputHelper output) public void ParseDocumentFromInlineStringShouldSucceed() { var openApiDoc = new OpenApiStringReader().Read( - @" -openapi : 3.0.0 -info: - title: Simple Document - version: 0.9.1 -paths: {}", + """ + + openapi : 3.0.0 + info: + title: Simple Document + version: 0.9.1 + paths: {} + """, out var context); openApiDoc.Should().BeEquivalentTo( @@ -119,23 +121,24 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture); var openApiDoc = new OpenApiStringReader().Read( - @" -openapi : 3.0.0 -info: - title: Simple Document - version: 0.9.1 -components: - schemas: - sampleSchema: - type: object - properties: - sampleProperty: - type: double - minimum: 100.54 - maximum: 60000000.35 - exclusiveMaximum: true - exclusiveMinimum: false -paths: {}", + """ + openapi : 3.0.0 + info: + title: Simple Document + version: 0.9.1 + components: + schemas: + sampleSchema: + type: object + properties: + sampleProperty: + type: double + minimum: 100.54 + maximum: 60000000.35 + exclusiveMaximum: true + exclusiveMinimum: false + paths: {} + """, out var context); openApiDoc.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index 0101d9c6e..c20aee105 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -74,12 +74,14 @@ public void ParsePrimitiveSchemaFragmentShouldSucceed() [Fact] public void ParsePrimitiveStringSchemaFragmentShouldSucceed() { - var input = @" -{ ""type"": ""integer"", -""format"": ""int64"", -""default"": 88 -} -"; + var input = + """ + { + "type": "integer", + "format": "int64", + "default": 88 + } + """; var reader = new OpenApiStringReader(); var diagnostic = new OpenApiDiagnostic(); @@ -101,11 +103,13 @@ public void ParsePrimitiveStringSchemaFragmentShouldSucceed() [Fact] public void ParseExampleStringFragmentShouldSucceed() { - var input = @" -{ - ""foo"": ""bar"", - ""baz"": [ 1,2] -}"; + var input = + """ + { + "foo": "bar", + "baz": [ 1,2] + } + """; var reader = new OpenApiStringReader(); var diagnostic = new OpenApiDiagnostic(); @@ -129,11 +133,13 @@ public void ParseExampleStringFragmentShouldSucceed() [Fact] public void ParseEnumFragmentShouldSucceed() { - var input = @" -[ - ""foo"", - ""baz"" -]"; + var input = + """ + [ + "foo", + "baz" + ] + """; var reader = new OpenApiStringReader(); var diagnostic = new OpenApiDiagnostic(); @@ -204,13 +210,14 @@ public void ParseSimpleSchemaShouldSucceed() [Fact] public void ParsePathFragmentShouldSucceed() { - var input = @" -summary: externally referenced path item -get: - responses: - '200': - description: Ok -"; + var input = + """ + summary: externally referenced path item + get: + responses: + '200': + description: Ok + """; var reader = new OpenApiStringReader(); var diagnostic = new OpenApiDiagnostic(); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs index 7ba6d132c..7713c3dd1 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs @@ -286,41 +286,44 @@ public void SerializeBasicComponentsAsYamlWorks() public void SerializeAdvancedComponentsAsJsonV3Works() { // Arrange - var expected = @"{ - ""schemas"": { - ""schema1"": { - ""properties"": { - ""property2"": { - ""type"": ""integer"" - }, - ""property3"": { - ""maxLength"": 15, - ""type"": ""string"" - } - } - } - }, - ""securitySchemes"": { - ""securityScheme1"": { - ""type"": ""oauth2"", - ""description"": ""description1"", - ""flows"": { - ""implicit"": { - ""authorizationUrl"": ""https://example.com/api/oauth"", - ""scopes"": { - ""operation1:object1"": ""operation 1 on object 1"", - ""operation2:object2"": ""operation 2 on object 2"" - } - } - } - }, - ""securityScheme2"": { - ""type"": ""openIdConnect"", - ""description"": ""description1"", - ""openIdConnectUrl"": ""https://example.com/openIdConnect"" - } - } -}"; + var expected = + """ + { + "schemas": { + "schema1": { + "properties": { + "property2": { + "type": "integer" + }, + "property3": { + "maxLength": 15, + "type": "string" + } + } + } + }, + "securitySchemes": { + "securityScheme1": { + "type": "oauth2", + "description": "description1", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth", + "scopes": { + "operation1:object1": "operation 1 on object 1", + "operation2:object2": "operation 2 on object 2" + } + } + } + }, + "securityScheme2": { + "type": "openIdConnect", + "description": "description1", + "openIdConnectUrl": "https://example.com/openIdConnect" + } + } + } + """; // Act var actual = AdvancedComponents.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -335,47 +338,50 @@ public void SerializeAdvancedComponentsAsJsonV3Works() public void SerializeAdvancedComponentsWithReferenceAsJsonV3Works() { // Arrange - var expected = @"{ - ""schemas"": { - ""schema1"": { - ""properties"": { - ""property2"": { - ""type"": ""integer"" - }, - ""property3"": { - ""$ref"": ""#/components/schemas/schema2"" - } - } - }, - ""schema2"": { - ""properties"": { - ""property2"": { - ""type"": ""integer"" - } - } - } - }, - ""securitySchemes"": { - ""securityScheme1"": { - ""type"": ""oauth2"", - ""description"": ""description1"", - ""flows"": { - ""implicit"": { - ""authorizationUrl"": ""https://example.com/api/oauth"", - ""scopes"": { - ""operation1:object1"": ""operation 1 on object 1"", - ""operation2:object2"": ""operation 2 on object 2"" - } - } - } - }, - ""securityScheme2"": { - ""type"": ""openIdConnect"", - ""description"": ""description1"", - ""openIdConnectUrl"": ""https://example.com/openIdConnect"" - } - } -}"; + var expected = + """ + { + "schemas": { + "schema1": { + "properties": { + "property2": { + "type": "integer" + }, + "property3": { + "$ref": "#/components/schemas/schema2" + } + } + }, + "schema2": { + "properties": { + "property2": { + "type": "integer" + } + } + } + }, + "securitySchemes": { + "securityScheme1": { + "type": "oauth2", + "description": "description1", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth", + "scopes": { + "operation1:object1": "operation 1 on object 1", + "operation2:object2": "operation 2 on object 2" + } + } + } + }, + "securityScheme2": { + "type": "openIdConnect", + "description": "description1", + "openIdConnectUrl": "https://example.com/openIdConnect" + } + } + } + """; // Act var actual = AdvancedComponentsWithReference.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -390,28 +396,31 @@ public void SerializeAdvancedComponentsWithReferenceAsJsonV3Works() public void SerializeAdvancedComponentsAsYamlV3Works() { // Arrange - var expected = @"schemas: - schema1: - properties: - property2: - type: integer - property3: - maxLength: 15 - type: string -securitySchemes: - securityScheme1: - type: oauth2 - description: description1 - flows: - implicit: - authorizationUrl: https://example.com/api/oauth - scopes: - operation1:object1: operation 1 on object 1 - operation2:object2: operation 2 on object 2 - securityScheme2: - type: openIdConnect - description: description1 - openIdConnectUrl: https://example.com/openIdConnect"; + var expected = + """ + schemas: + schema1: + properties: + property2: + type: integer + property3: + maxLength: 15 + type: string + securitySchemes: + securityScheme1: + type: oauth2 + description: description1 + flows: + implicit: + authorizationUrl: https://example.com/api/oauth + scopes: + operation1:object1: operation 1 on object 1 + operation2:object2: operation 2 on object 2 + securityScheme2: + type: openIdConnect + description: description1 + openIdConnectUrl: https://example.com/openIdConnect + """; // Act var actual = AdvancedComponents.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -426,31 +435,34 @@ public void SerializeAdvancedComponentsAsYamlV3Works() public void SerializeAdvancedComponentsWithReferenceAsYamlV3Works() { // Arrange - var expected = @"schemas: - schema1: - properties: - property2: - type: integer - property3: - $ref: '#/components/schemas/schema2' - schema2: - properties: - property2: - type: integer -securitySchemes: - securityScheme1: - type: oauth2 - description: description1 - flows: - implicit: - authorizationUrl: https://example.com/api/oauth - scopes: - operation1:object1: operation 1 on object 1 - operation2:object2: operation 2 on object 2 - securityScheme2: - type: openIdConnect - description: description1 - openIdConnectUrl: https://example.com/openIdConnect"; + var expected = + """ + schemas: + schema1: + properties: + property2: + type: integer + property3: + $ref: '#/components/schemas/schema2' + schema2: + properties: + property2: + type: integer + securitySchemes: + securityScheme1: + type: oauth2 + description: description1 + flows: + implicit: + authorizationUrl: https://example.com/api/oauth + scopes: + operation1:object1: operation 1 on object 1 + operation2:object2: operation 2 on object 2 + securityScheme2: + type: openIdConnect + description: description1 + openIdConnectUrl: https://example.com/openIdConnect + """; // Act var actual = AdvancedComponentsWithReference.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -465,27 +477,30 @@ public void SerializeAdvancedComponentsWithReferenceAsYamlV3Works() public void SerializeBrokenComponentsAsJsonV3Works() { // Arrange - var expected = @"{ - ""schemas"": { - ""schema1"": { - ""type"": ""string"" - }, - ""schema2"": null, - ""schema3"": null, - ""schema4"": { - ""type"": ""string"", - ""allOf"": [ - null, - null, - { - ""type"": ""string"" - }, - null, - null - ] - } - } -}"; + var expected = + """ + { + "schemas": { + "schema1": { + "type": "string" + }, + "schema2": null, + "schema3": null, + "schema4": { + "type": "string", + "allOf": [ + null, + null, + { + "type": "string" + }, + null, + null + ] + } + } + } + """; // Act var actual = BrokenComponents.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -500,19 +515,22 @@ public void SerializeBrokenComponentsAsJsonV3Works() public void SerializeBrokenComponentsAsYamlV3Works() { // Arrange - var expected = @"schemas: - schema1: - type: string - schema2: - schema3: - schema4: - type: string - allOf: - - - - - - type: string - - - - "; + var expected = + """ + schemas: + schema1: + type: string + schema2: + schema3: + schema4: + type: string + allOf: + - + - + - type: string + - + - + """; // Act var actual = BrokenComponents.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -527,14 +545,17 @@ public void SerializeBrokenComponentsAsYamlV3Works() public void SerializeTopLevelReferencingComponentsAsYamlV3Works() { // Arrange - var expected = @"schemas: - schema1: - $ref: '#/components/schemas/schema2' - schema2: - type: object - properties: - property1: - type: string"; + var expected = + """ + schemas: + schema1: + $ref: '#/components/schemas/schema2' + schema2: + type: object + properties: + property1: + type: string + """; // Act var actual = TopLevelReferencingComponents.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -549,8 +570,11 @@ public void SerializeTopLevelReferencingComponentsAsYamlV3Works() public void SerializeTopLevelSelfReferencingComponentsAsYamlV3Works() { // Arrange - var expected = @"schemas: - schema1: { }"; + var expected = + """ + schemas: + schema1: { } + """; // Act var actual = TopLevelSelfReferencingComponents.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -565,17 +589,20 @@ public void SerializeTopLevelSelfReferencingComponentsAsYamlV3Works() public void SerializeTopLevelSelfReferencingWithOtherPropertiesComponentsAsYamlV3Works() { // Arrange - var expected = @"schemas: - schema1: - type: object - properties: - property1: - type: string - schema2: - type: object - properties: - property1: - type: string"; + var expected = + """ + schemas: + schema1: + type: object + properties: + property1: + type: string + schema2: + type: object + properties: + property1: + type: string + """; // Act var actual = TopLevelSelfReferencingComponentsWithOtherProperties.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs index 1a99241d1..d1ffab249 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs @@ -54,12 +54,14 @@ public void SerializeAdvanceContactAsJsonWorks(OpenApiSpecVersion version) { // Arrange var expected = - @"{ - ""name"": ""API Support"", - ""url"": ""http://www.example.com/support"", - ""email"": ""support@example.com"", - ""x-internal-id"": 42 -}"; + """ + { + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com", + "x-internal-id": 42 + } + """; // Act var actual = AdvanceContact.SerializeAsJson(version); @@ -77,10 +79,12 @@ public void SerializeAdvanceContactAsYamlWorks(OpenApiSpecVersion version) { // Arrange var expected = - @"name: API Support -url: http://www.example.com/support -email: support@example.com -x-internal-id: 42"; + """ + name: API Support + url: http://www.example.com/support + email: support@example.com + x-internal-id: 42 + """; // Act var actual = AdvanceContact.SerializeAsYaml(version); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 924699bdf..e5d27348b 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1410,18 +1410,21 @@ public async Task SerializeAdvancedDocumentWithReferenceAsV2JsonWorks(bool produ public void SerializeSimpleDocumentWithTopLevelReferencingComponentsAsYamlV2Works() { // Arrange - var expected = @"swagger: '2.0' -info: - version: 1.0.0 -paths: { } -definitions: - schema1: - $ref: '#/definitions/schema2' - schema2: - type: object - properties: - property1: - type: string"; + var expected = + """ + swagger: '2.0' + info: + version: 1.0.0 + paths: { } + definitions: + schema1: + $ref: '#/definitions/schema2' + schema2: + type: object + properties: + property1: + type: string + """; // Act var actual = SimpleDocumentWithTopLevelReferencingComponents.SerializeAsYaml(OpenApiSpecVersion.OpenApi2_0); @@ -1436,12 +1439,15 @@ public void SerializeSimpleDocumentWithTopLevelReferencingComponentsAsYamlV2Work public void SerializeSimpleDocumentWithTopLevelSelfReferencingComponentsAsYamlV3Works() { // Arrange - var expected = @"swagger: '2.0' -info: - version: 1.0.0 -paths: { } -definitions: - schema1: { }"; + var expected = + """ + swagger: '2.0' + info: + version: 1.0.0 + paths: { } + definitions: + schema1: { } + """; // Act var actual = SimpleDocumentWithTopLevelSelfReferencingComponents.SerializeAsYaml(OpenApiSpecVersion.OpenApi2_0); @@ -1456,21 +1462,24 @@ public void SerializeSimpleDocumentWithTopLevelSelfReferencingComponentsAsYamlV3 public void SerializeSimpleDocumentWithTopLevelSelfReferencingWithOtherPropertiesComponentsAsYamlV3Works() { // Arrange - var expected = @"swagger: '2.0' -info: - version: 1.0.0 -paths: { } -definitions: - schema1: - type: object - properties: - property1: - type: string - schema2: - type: object - properties: - property1: - type: string"; + var expected = + """ + swagger: '2.0' + info: + version: 1.0.0 + paths: { } + definitions: + schema1: + type: object + properties: + property1: + type: string + schema2: + type: object + properties: + property1: + type: string + """; // Act var actual = SimpleDocumentWithTopLevelSelfReferencingComponentsWithOtherProperties.SerializeAsYaml(OpenApiSpecVersion.OpenApi2_0); @@ -1541,11 +1550,13 @@ public void SerializeRelativePathAsV2JsonWorks() { // Arrange var expected = - @"swagger: '2.0' -info: - version: 1.0.0 -basePath: /server1 -paths: { }"; + """ + swagger: '2.0' + info: + version: 1.0.0 + basePath: /server1 + paths: { } + """; var doc = new OpenApiDocument() { Info = new OpenApiInfo() { Version = "1.0.0" }, @@ -1571,12 +1582,14 @@ public void SerializeRelativePathWithHostAsV2JsonWorks() { // Arrange var expected = - @"swagger: '2.0' -info: - version: 1.0.0 -host: //example.org -basePath: /server1 -paths: { }"; + """ + swagger: '2.0' + info: + version: 1.0.0 + host: //example.org + basePath: /server1 + paths: { } + """; var doc = new OpenApiDocument() { Info = new OpenApiInfo() { Version = "1.0.0" }, @@ -1602,11 +1615,13 @@ public void SerializeRelativeRootPathWithHostAsV2JsonWorks() { // Arrange var expected = - @"swagger: '2.0' -info: - version: 1.0.0 -host: //example.org -paths: { }"; + """ + swagger: '2.0' + info: + version: 1.0.0 + host: //example.org + paths: { } + """; var doc = new OpenApiDocument() { Info = new OpenApiInfo() { Version = "1.0.0" }, @@ -1680,15 +1695,18 @@ private static OpenApiDocument ParseInputFile(string filePath) public void SerializeV2DocumentWithNonArraySchemaTypeDoesNotWriteOutCollectionFormat() { // Arrange - var expected = @"swagger: '2.0' -info: { } -paths: - /foo: - get: - parameters: - - in: query - type: string - responses: { }"; + var expected = + """ + swagger: '2.0' + info: { } + paths: + /foo: + get: + parameters: + - in: query + type: string + responses: { } + """; var doc = new OpenApiDocument { @@ -1732,27 +1750,30 @@ public void SerializeV2DocumentWithNonArraySchemaTypeDoesNotWriteOutCollectionFo public void SerializeV2DocumentWithStyleAsNullDoesNotWriteOutStyleValue() { // Arrange - var expected = @"openapi: 3.0.1 -info: - title: magic style - version: 1.0.0 -paths: - /foo: - get: - parameters: - - name: id - in: query - schema: - type: object - additionalProperties: - type: integer - responses: - '200': - description: foo - content: - text/plain: - schema: - type: string"; + var expected = + """ + openapi: 3.0.1 + info: + title: magic style + version: 1.0.0 + paths: + /foo: + get: + parameters: + - name: id + in: query + schema: + type: object + additionalProperties: + type: integer + responses: + '200': + description: foo + content: + text/plain: + schema: + type: string + """; var doc = new OpenApiDocument { diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs index 24bfca242..9f273f280 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs @@ -40,12 +40,14 @@ public void SerializeAdvanceEncodingAsV3JsonWorks() { // Arrange var expected = - @"{ - ""contentType"": ""image/png, image/jpeg"", - ""style"": ""simple"", - ""explode"": true, - ""allowReserved"": true -}"; + """ + { + "contentType": "image/png, image/jpeg", + "style": "simple", + "explode": true, + "allowReserved": true + } + """; // Act var actual = AdvanceEncoding.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -61,10 +63,12 @@ public void SerializeAdvanceEncodingAsV3YamlWorks() { // Arrange var expected = - @"contentType: 'image/png, image/jpeg' -style: simple -explode: true -allowReserved: true"; + """ + contentType: 'image/png, image/jpeg' + style: simple + explode: true + allowReserved: true + """; // Act var actual = AdvanceEncoding.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs index 7d37fc9a4..a9ba66e88 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs @@ -41,10 +41,12 @@ public void SerializeAdvanceExDocsAsV3JsonWorks() { // Arrange var expected = - @"{ - ""description"": ""Find more info here"", - ""url"": ""https://example.com"" -}"; + """ + { + "description": "Find more info here", + "url": "https://example.com" + } + """; // Act var actual = AdvanceExDocs.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -60,8 +62,10 @@ public void SerializeAdvanceExDocsAsV3YamlWorks() { // Arrange var expected = - @"description: Find more info here -url: https://example.com"; + """ + description: Find more info here + url: https://example.com + """; // Act var actual = AdvanceExDocs.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs index b2395a9ed..a28ea2598 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs @@ -43,10 +43,12 @@ public static IEnumerable BasicInfoJsonExpected() yield return new object[] { specVersion, - @"{ - ""title"": ""Sample Pet Store App"", - ""version"": ""1.0"" -}" + """ + { + "title": "Sample Pet Store App", + "version": "1.0" + } + """ }; } } @@ -72,8 +74,10 @@ public static IEnumerable BasicInfoYamlExpected() yield return new object[] { specVersion, - @"title: Sample Pet Store App -version: '1.0'" + """ + title: Sample Pet Store App + version: '1.0' + """ }; } } @@ -99,24 +103,26 @@ public static IEnumerable AdvanceInfoJsonExpect() yield return new object[] { specVersion, - @"{ - ""title"": ""Sample Pet Store App"", - ""description"": ""This is a sample server for a pet store."", - ""termsOfService"": ""http://example.com/terms/"", - ""contact"": { - ""name"": ""API Support"", - ""url"": ""http://www.example.com/support"", - ""email"": ""support@example.com"", - ""x-internal-id"": 42 - }, - ""license"": { - ""name"": ""Apache 2.0"", - ""url"": ""http://www.apache.org/licenses/LICENSE-2.0.html"", - ""x-copyright"": ""Abc"" - }, - ""version"": ""1.1.1"", - ""x-updated"": ""metadata"" -}" + """ + { + "title": "Sample Pet Store App", + "description": "This is a sample server for a pet store.", + "termsOfService": "http://example.com/terms/", + "contact": { + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com", + "x-internal-id": 42 + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html", + "x-copyright": "Abc" + }, + "version": "1.1.1", + "x-updated": "metadata" + } + """ }; } } @@ -142,20 +148,22 @@ public static IEnumerable AdvanceInfoYamlExpect() yield return new object[] { specVersion, - @"title: Sample Pet Store App -description: This is a sample server for a pet store. -termsOfService: http://example.com/terms/ -contact: - name: API Support - url: http://www.example.com/support - email: support@example.com - x-internal-id: 42 -license: - name: Apache 2.0 - url: http://www.apache.org/licenses/LICENSE-2.0.html - x-copyright: Abc -version: '1.1.1' -x-updated: metadata" + """ + title: Sample Pet Store App + description: This is a sample server for a pet store. + termsOfService: http://example.com/terms/ + contact: + name: API Support + url: http://www.example.com/support + email: support@example.com + x-internal-id: 42 + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + x-copyright: Abc + version: '1.1.1' + x-updated: metadata + """ }; } } @@ -184,8 +192,10 @@ public void InfoVersionShouldAcceptDateStyledAsVersions() }; var expected = - @"title: Sample Pet Store App -version: '2017-03-01'"; + """ + title: Sample Pet Store App + version: '2017-03-01' + """; // Act var actual = info.Serialize(OpenApiSpecVersion.OpenApi3_0, OpenApiFormat.Yaml); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs index 46717ecec..1f5bb1d5b 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs @@ -37,9 +37,11 @@ public void SerializeBasicLicenseAsJsonWorks(OpenApiSpecVersion version) { // Arrange var expected = - @"{ - ""name"": ""Apache 2.0"" -}"; + """ + { + "name": "Apache 2.0" + } + """; // Act var actual = BasicLicense.SerializeAsJson(version); @@ -74,11 +76,13 @@ public void SerializeAdvanceLicenseAsJsonWorks(OpenApiSpecVersion version) { // Arrange var expected = - @"{ - ""name"": ""Apache 2.0"", - ""url"": ""http://www.apache.org/licenses/LICENSE-2.0.html"", - ""x-copyright"": ""Abc"" -}"; + """ + { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html", + "x-copyright": "Abc" + } + """; // Act var actual = AdvanceLicense.SerializeAsJson(version); @@ -96,9 +100,11 @@ public void SerializeAdvanceLicenseAsYamlWorks(OpenApiSpecVersion version) { // Arrange var expected = - @"name: Apache 2.0 -url: http://www.apache.org/licenses/LICENSE-2.0.html -x-copyright: Abc"; + """ + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + x-copyright: Abc + """; // Act var actual = AdvanceLicense.SerializeAsYaml(version); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs index c59da1e86..161be20d9 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs @@ -147,17 +147,19 @@ public void SerializeAdvanceMediaTypeAsV3JsonWorks() { // Arrange var expected = - @"{ - ""example"": 42, - ""encoding"": { - ""testEncoding"": { - ""contentType"": ""image/png, image/jpeg"", - ""style"": ""simple"", - ""explode"": true, - ""allowReserved"": true - } - } -}"; + """ + { + "example": 42, + "encoding": { + "testEncoding": { + "contentType": "image/png, image/jpeg", + "style": "simple", + "explode": true, + "allowReserved": true + } + } + } + """; // Act var actual = AdvanceMediaType.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -173,13 +175,15 @@ public void SerializeAdvanceMediaTypeAsV3YamlWorks() { // Arrange var expected = - @"example: 42 -encoding: - testEncoding: - contentType: 'image/png, image/jpeg' - style: simple - explode: true - allowReserved: true"; + """ + example: 42 + encoding: + testEncoding: + contentType: 'image/png, image/jpeg' + style: simple + explode: true + allowReserved: true + """; // Act var actual = AdvanceMediaType.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -195,24 +199,26 @@ public void SerializeMediaTypeWithObjectExampleAsV3YamlWorks() { // Arrange var expected = - @"example: - versions: - - status: Status1 - id: v1 - links: - - href: http://example.com/1 - rel: sampleRel1 - - status: Status2 - id: v2 - links: - - href: http://example.com/2 - rel: sampleRel2 -encoding: - testEncoding: - contentType: 'image/png, image/jpeg' - style: simple - explode: true - allowReserved: true"; + """ + example: + versions: + - status: Status1 + id: v1 + links: + - href: http://example.com/1 + rel: sampleRel1 + - status: Status2 + id: v2 + links: + - href: http://example.com/2 + rel: sampleRel2 + encoding: + testEncoding: + contentType: 'image/png, image/jpeg' + style: simple + explode: true + allowReserved: true + """; // Act var actual = MediaTypeWithObjectExample.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -228,40 +234,42 @@ public void SerializeMediaTypeWithObjectExampleAsV3JsonWorks() { // Arrange var expected = - @"{ - ""example"": { - ""versions"": [ - { - ""status"": ""Status1"", - ""id"": ""v1"", - ""links"": [ - { - ""href"": ""http://example.com/1"", - ""rel"": ""sampleRel1"" - } - ] - }, - { - ""status"": ""Status2"", - ""id"": ""v2"", - ""links"": [ - { - ""href"": ""http://example.com/2"", - ""rel"": ""sampleRel2"" - } - ] - } - ] - }, - ""encoding"": { - ""testEncoding"": { - ""contentType"": ""image/png, image/jpeg"", - ""style"": ""simple"", - ""explode"": true, - ""allowReserved"": true - } - } -}"; + """ + { + "example": { + "versions": [ + { + "status": "Status1", + "id": "v1", + "links": [ + { + "href": "http://example.com/1", + "rel": "sampleRel1" + } + ] + }, + { + "status": "Status2", + "id": "v2", + "links": [ + { + "href": "http://example.com/2", + "rel": "sampleRel2" + } + ] + } + ] + }, + "encoding": { + "testEncoding": { + "contentType": "image/png, image/jpeg", + "style": "simple", + "explode": true, + "allowReserved": true + } + } + } + """; // Act var actual = MediaTypeWithObjectExample.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -277,13 +285,15 @@ public void SerializeMediaTypeWithXmlExampleAsV3YamlWorks() { // Arrange var expected = - @"example: 123 -encoding: - testEncoding: - contentType: 'image/png, image/jpeg' - style: simple - explode: true - allowReserved: true"; + """ + example: 123 + encoding: + testEncoding: + contentType: 'image/png, image/jpeg' + style: simple + explode: true + allowReserved: true + """; // Act var actual = MediaTypeWithXmlExample.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -298,17 +308,20 @@ public void SerializeMediaTypeWithXmlExampleAsV3YamlWorks() public void SerializeMediaTypeWithXmlExampleAsV3JsonWorks() { // Arrange - var expected = @"{ - ""example"": ""123"", - ""encoding"": { - ""testEncoding"": { - ""contentType"": ""image/png, image/jpeg"", - ""style"": ""simple"", - ""explode"": true, - ""allowReserved"": true - } - } -}"; + var expected = + """ + { + "example": "123", + "encoding": { + "testEncoding": { + "contentType": "image/png, image/jpeg", + "style": "simple", + "explode": true, + "allowReserved": true + } + } + } + """; // Act var actual = MediaTypeWithXmlExample.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -323,26 +336,29 @@ public void SerializeMediaTypeWithXmlExampleAsV3JsonWorks() public void SerializeMediaTypeWithObjectExamplesAsV3YamlWorks() { // Arrange - var expected = @"examples: - object1: - value: - versions: - - status: Status1 - id: v1 - links: - - href: http://example.com/1 - rel: sampleRel1 - - status: Status2 - id: v2 - links: - - href: http://example.com/2 - rel: sampleRel2 -encoding: - testEncoding: - contentType: 'image/png, image/jpeg' - style: simple - explode: true - allowReserved: true"; + var expected = + """ + examples: + object1: + value: + versions: + - status: Status1 + id: v1 + links: + - href: http://example.com/1 + rel: sampleRel1 + - status: Status2 + id: v2 + links: + - href: http://example.com/2 + rel: sampleRel2 + encoding: + testEncoding: + contentType: 'image/png, image/jpeg' + style: simple + explode: true + allowReserved: true + """; // Act var actual = MediaTypeWithObjectExamples.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -358,44 +374,47 @@ public void SerializeMediaTypeWithObjectExamplesAsV3YamlWorks() public void SerializeMediaTypeWithObjectExamplesAsV3JsonWorks() { // Arrange - var expected = @"{ - ""examples"": { - ""object1"": { - ""value"": { - ""versions"": [ - { - ""status"": ""Status1"", - ""id"": ""v1"", - ""links"": [ - { - ""href"": ""http://example.com/1"", - ""rel"": ""sampleRel1"" - } - ] - }, - { - ""status"": ""Status2"", - ""id"": ""v2"", - ""links"": [ - { - ""href"": ""http://example.com/2"", - ""rel"": ""sampleRel2"" - } - ] - } - ] - } - } - }, - ""encoding"": { - ""testEncoding"": { - ""contentType"": ""image/png, image/jpeg"", - ""style"": ""simple"", - ""explode"": true, - ""allowReserved"": true - } - } -}"; + var expected = + """ + { + "examples": { + "object1": { + "value": { + "versions": [ + { + "status": "Status1", + "id": "v1", + "links": [ + { + "href": "http://example.com/1", + "rel": "sampleRel1" + } + ] + }, + { + "status": "Status2", + "id": "v2", + "links": [ + { + "href": "http://example.com/2", + "rel": "sampleRel2" + } + ] + } + ] + } + } + }, + "encoding": { + "testEncoding": { + "contentType": "image/png, image/jpeg", + "style": "simple", + "explode": true, + "allowReserved": true + } + } + } + """; // Act var actual = MediaTypeWithObjectExamples.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs index 80040f566..cd46ae02a 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs @@ -50,9 +50,11 @@ public void SerializeBasicOAuthFlowAsV3JsonWorks() { // Arrange var expected = - @"{ - ""scopes"": { } -}"; + """ + { + "scopes": { } + } + """; // Act var actual = BasicOAuthFlow.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -84,13 +86,15 @@ public void SerializePartialOAuthFlowAsV3JsonWorks() { // Arrange var expected = - @"{ - ""authorizationUrl"": ""http://example.com/authorization"", - ""scopes"": { - ""scopeName3"": ""description3"", - ""scopeName4"": ""description4"" - } -}"; + """ + { + "authorizationUrl": "http://example.com/authorization", + "scopes": { + "scopeName3": "description3", + "scopeName4": "description4" + } + } + """; // Act var actual = PartialOAuthFlow.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -106,15 +110,17 @@ public void SerializeCompleteOAuthFlowAsV3JsonWorks() { // Arrange var expected = - @"{ - ""authorizationUrl"": ""http://example.com/authorization"", - ""tokenUrl"": ""http://example.com/token"", - ""refreshUrl"": ""http://example.com/refresh"", - ""scopes"": { - ""scopeName3"": ""description3"", - ""scopeName4"": ""description4"" - } -}"; + """ + { + "authorizationUrl": "http://example.com/authorization", + "tokenUrl": "http://example.com/token", + "refreshUrl": "http://example.com/refresh", + "scopes": { + "scopeName3": "description3", + "scopeName4": "description4" + } + } + """; // Act var actual = CompleteOAuthFlow.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs index 7d4882bbb..9860a926a 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs @@ -96,15 +96,17 @@ public void SerializeOAuthFlowsWithSingleFlowAsV3JsonWorks() { // Arrange var expected = - @"{ - ""implicit"": { - ""authorizationUrl"": ""http://example.com/authorization"", - ""scopes"": { - ""scopeName1"": ""description1"", - ""scopeName2"": ""description2"" - } - } -}"; + """ + { + "implicit": { + "authorizationUrl": "http://example.com/authorization", + "scopes": { + "scopeName1": "description1", + "scopeName2": "description2" + } + } + } + """; // Act var actual = OAuthFlowsWithSingleFlow.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -120,23 +122,25 @@ public void SerializeOAuthFlowsWithMultipleFlowsAsV3JsonWorks() { // Arrange var expected = - @"{ - ""implicit"": { - ""authorizationUrl"": ""http://example.com/authorization"", - ""scopes"": { - ""scopeName1"": ""description1"", - ""scopeName2"": ""description2"" - } - }, - ""password"": { - ""tokenUrl"": ""http://example.com/token"", - ""refreshUrl"": ""http://example.com/refresh"", - ""scopes"": { - ""scopeName3"": ""description3"", - ""scopeName4"": ""description4"" - } - } -}"; + """ + { + "implicit": { + "authorizationUrl": "http://example.com/authorization", + "scopes": { + "scopeName1": "description1", + "scopeName2": "description2" + } + }, + "password": { + "tokenUrl": "http://example.com/token", + "refreshUrl": "http://example.com/refresh", + "scopes": { + "scopeName3": "description3", + "scopeName4": "description4" + } + } + } + """; // Act var actual = OAuthFlowsWithMultipleFlows.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index de56df52e..d87b55820 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -307,9 +307,12 @@ public OpenApiOperationTests(ITestOutputHelper output) public void SerializeBasicOperationAsV3JsonWorks() { // Arrange - var expected = @"{ - ""responses"": { } -}"; + var expected = + """ + { + "responses": { } + } + """; // Act var actual = _basicOperation.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -324,61 +327,64 @@ public void SerializeBasicOperationAsV3JsonWorks() public void SerializeOperationWithBodyAsV3JsonWorks() { // Arrange - var expected = @"{ - ""summary"": ""summary1"", - ""description"": ""operationDescription"", - ""externalDocs"": { - ""description"": ""externalDocsDescription"", - ""url"": ""http://external.com"" - }, - ""operationId"": ""operationId1"", - ""parameters"": [ - { - ""name"": ""parameter1"", - ""in"": ""path"" - }, - { - ""name"": ""parameter2"", - ""in"": ""header"" - } - ], - ""requestBody"": { - ""description"": ""description2"", - ""content"": { - ""application/json"": { - ""schema"": { - ""maximum"": 10, - ""minimum"": 5, - ""type"": ""number"" - } - } - }, - ""required"": true - }, - ""responses"": { - ""200"": { - ""$ref"": ""#/components/responses/response1"" - }, - ""400"": { - ""description"": null, - ""content"": { - ""application/json"": { - ""schema"": { - ""maximum"": 10, - ""minimum"": 5, - ""type"": ""number"" - } - } - } - } - }, - ""servers"": [ - { - ""url"": ""http://server.com"", - ""description"": ""serverDescription"" - } - ] -}"; + var expected = + """ + { + "summary": "summary1", + "description": "operationDescription", + "externalDocs": { + "description": "externalDocsDescription", + "url": "http://external.com" + }, + "operationId": "operationId1", + "parameters": [ + { + "name": "parameter1", + "in": "path" + }, + { + "name": "parameter2", + "in": "header" + } + ], + "requestBody": { + "description": "description2", + "content": { + "application/json": { + "schema": { + "maximum": 10, + "minimum": 5, + "type": "number" + } + } + }, + "required": true + }, + "responses": { + "200": { + "$ref": "#/components/responses/response1" + }, + "400": { + "description": null, + "content": { + "application/json": { + "schema": { + "maximum": 10, + "minimum": 5, + "type": "number" + } + } + } + } + }, + "servers": [ + { + "url": "http://server.com", + "description": "serverDescription" + } + ] + } + """; // Act var actual = _operationWithBody.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -393,74 +399,77 @@ public void SerializeOperationWithBodyAsV3JsonWorks() public void SerializeAdvancedOperationWithTagAndSecurityAsV3JsonWorks() { // Arrange - var expected = @"{ - ""tags"": [ - ""tagName1"", - ""tagId1"" - ], - ""summary"": ""summary1"", - ""description"": ""operationDescription"", - ""externalDocs"": { - ""description"": ""externalDocsDescription"", - ""url"": ""http://external.com"" - }, - ""operationId"": ""operationId1"", - ""parameters"": [ - { - ""name"": ""parameter1"", - ""in"": ""path"" - }, - { - ""name"": ""parameter2"", - ""in"": ""header"" - } - ], - ""requestBody"": { - ""description"": ""description2"", - ""content"": { - ""application/json"": { - ""schema"": { - ""maximum"": 10, - ""minimum"": 5, - ""type"": ""number"" - } - } - }, - ""required"": true - }, - ""responses"": { - ""200"": { - ""$ref"": ""#/components/responses/response1"" - }, - ""400"": { - ""description"": null, - ""content"": { - ""application/json"": { - ""schema"": { - ""maximum"": 10, - ""minimum"": 5, - ""type"": ""number"" - } - } - } - } - }, - ""security"": [ - { - ""securitySchemeId1"": [ ], - ""securitySchemeId2"": [ - ""scopeName1"", - ""scopeName2"" - ] - } - ], - ""servers"": [ - { - ""url"": ""http://server.com"", - ""description"": ""serverDescription"" - } - ] -}"; + var expected = + """ + { + "tags": [ + "tagName1", + "tagId1" + ], + "summary": "summary1", + "description": "operationDescription", + "externalDocs": { + "description": "externalDocsDescription", + "url": "http://external.com" + }, + "operationId": "operationId1", + "parameters": [ + { + "name": "parameter1", + "in": "path" + }, + { + "name": "parameter2", + "in": "header" + } + ], + "requestBody": { + "description": "description2", + "content": { + "application/json": { + "schema": { + "maximum": 10, + "minimum": 5, + "type": "number" + } + } + }, + "required": true + }, + "responses": { + "200": { + "$ref": "#/components/responses/response1" + }, + "400": { + "description": null, + "content": { + "application/json": { + "schema": { + "maximum": 10, + "minimum": 5, + "type": "number" + } + } + } + } + }, + "security": [ + { + "securitySchemeId1": [ ], + "securitySchemeId2": [ + "scopeName1", + "scopeName2" + ] + } + ], + "servers": [ + { + "url": "http://server.com", + "description": "serverDescription" + } + ] + } + """; // Act var actual = _advancedOperationWithTagsAndSecurity.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -475,9 +484,12 @@ public void SerializeAdvancedOperationWithTagAndSecurityAsV3JsonWorks() public void SerializeBasicOperationAsV2JsonWorks() { // Arrange - var expected = @"{ - ""responses"": { } -}"; + var expected = + """ + { + "responses": { } + } + """; // Act var actual = _basicOperation.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); @@ -492,68 +504,71 @@ public void SerializeBasicOperationAsV2JsonWorks() public void SerializeOperationWithFormDataAsV3JsonWorks() { // Arrange - var expected = @"{ - ""summary"": ""Updates a pet in the store with form data"", - ""description"": """", - ""operationId"": ""updatePetWithForm"", - ""parameters"": [ - { - ""name"": ""petId"", - ""in"": ""path"", - ""description"": ""ID of pet that needs to be updated"", - ""required"": true, - ""schema"": { - ""type"": ""string"" - } - } - ], - ""requestBody"": { - ""content"": { - ""application/x-www-form-urlencoded"": { - ""schema"": { - ""required"": [ - ""name"" - ], - ""properties"": { - ""name"": { - ""type"": ""string"", - ""description"": ""Updated name of the pet"" - }, - ""status"": { - ""type"": ""string"", - ""description"": ""Updated status of the pet"" - } - } - } - }, - ""multipart/form-data"": { - ""schema"": { - ""required"": [ - ""name"" - ], - ""properties"": { - ""name"": { - ""type"": ""string"", - ""description"": ""Updated name of the pet"" - }, - ""status"": { - ""type"": ""string"", - ""description"": ""Updated status of the pet"" - } - } - } - } - } - }, - ""responses"": { - ""200"": { - ""description"": ""Pet updated."" - }, - ""405"": { - ""description"": ""Invalid input"" - } - } -}"; + var expected = + """ + { + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "description": "Updated name of the pet" + }, + "status": { + "type": "string", + "description": "Updated status of the pet" + } + } + } + }, + "multipart/form-data": { + "schema": { + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "description": "Updated name of the pet" + }, + "status": { + "type": "string", + "description": "Updated status of the pet" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Pet updated." + }, + "405": { + "description": "Invalid input" + } + } + } + """; // Act var actual = _operationWithFormData.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -568,45 +583,48 @@ public void SerializeOperationWithFormDataAsV3JsonWorks() public void SerializeOperationWithFormDataAsV2JsonWorks() { // Arrange - var expected = @"{ - ""summary"": ""Updates a pet in the store with form data"", - ""description"": """", - ""operationId"": ""updatePetWithForm"", - ""consumes"": [ - ""application/x-www-form-urlencoded"", - ""multipart/form-data"" - ], - ""parameters"": [ - { - ""in"": ""path"", - ""name"": ""petId"", - ""description"": ""ID of pet that needs to be updated"", - ""required"": true, - ""type"": ""string"" - }, - { - ""in"": ""formData"", - ""name"": ""name"", - ""description"": ""Updated name of the pet"", - ""required"": true, - ""type"": ""string"" - }, - { - ""in"": ""formData"", - ""name"": ""status"", - ""description"": ""Updated status of the pet"", - ""type"": ""string"" - } - ], - ""responses"": { - ""200"": { - ""description"": ""Pet updated."" - }, - ""405"": { - ""description"": ""Invalid input"" - } - } -}"; + var expected = + """ + { + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded", + "multipart/form-data" + ], + "parameters": [ + { + "in": "path", + "name": "petId", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "string" + }, + { + "in": "formData", + "name": "name", + "description": "Updated name of the pet", + "required": true, + "type": "string" + }, + { + "in": "formData", + "name": "status", + "description": "Updated status of the pet", + "type": "string" + } + ], + "responses": { + "200": { + "description": "Pet updated." + }, + "405": { + "description": "Invalid input" + } + } + } + """; // Act var actual = _operationWithFormData.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); @@ -621,58 +639,61 @@ public void SerializeOperationWithFormDataAsV2JsonWorks() public void SerializeOperationWithBodyAsV2JsonWorks() { // Arrange - var expected = @"{ - ""summary"": ""summary1"", - ""description"": ""operationDescription"", - ""externalDocs"": { - ""description"": ""externalDocsDescription"", - ""url"": ""http://external.com"" - }, - ""operationId"": ""operationId1"", - ""consumes"": [ - ""application/json"" - ], - ""produces"": [ - ""application/json"" - ], - ""parameters"": [ - { - ""in"": ""path"", - ""name"": ""parameter1"" - }, - { - ""in"": ""header"", - ""name"": ""parameter2"" - }, - { - ""in"": ""body"", - ""name"": ""body"", - ""description"": ""description2"", - ""required"": true, - ""schema"": { - ""maximum"": 10, - ""minimum"": 5, - ""type"": ""number"" - } - } - ], - ""responses"": { - ""200"": { - ""$ref"": ""#/responses/response1"" - }, - ""400"": { - ""description"": null, - ""schema"": { - ""maximum"": 10, - ""minimum"": 5, - ""type"": ""number"" - } - } - }, - ""schemes"": [ - ""http"" - ] -}"; + var expected = + """ + { + "summary": "summary1", + "description": "operationDescription", + "externalDocs": { + "description": "externalDocsDescription", + "url": "http://external.com" + }, + "operationId": "operationId1", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "in": "path", + "name": "parameter1" + }, + { + "in": "header", + "name": "parameter2" + }, + { + "in": "body", + "name": "body", + "description": "description2", + "required": true, + "schema": { + "maximum": 10, + "minimum": 5, + "type": "number" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/response1" + }, + "400": { + "description": null, + "schema": { + "maximum": 10, + "minimum": 5, + "type": "number" + } + } + }, + "schemes": [ + "http" + ] + } + """; // Act var actual = _operationWithBody.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); @@ -687,71 +708,74 @@ public void SerializeOperationWithBodyAsV2JsonWorks() public void SerializeAdvancedOperationWithTagAndSecurityAsV2JsonWorks() { // Arrange - var expected = @"{ - ""tags"": [ - ""tagName1"", - ""tagId1"" - ], - ""summary"": ""summary1"", - ""description"": ""operationDescription"", - ""externalDocs"": { - ""description"": ""externalDocsDescription"", - ""url"": ""http://external.com"" - }, - ""operationId"": ""operationId1"", - ""consumes"": [ - ""application/json"" - ], - ""produces"": [ - ""application/json"" - ], - ""parameters"": [ - { - ""in"": ""path"", - ""name"": ""parameter1"" - }, - { - ""in"": ""header"", - ""name"": ""parameter2"" - }, - { - ""in"": ""body"", - ""name"": ""body"", - ""description"": ""description2"", - ""required"": true, - ""schema"": { - ""maximum"": 10, - ""minimum"": 5, - ""type"": ""number"" - } - } - ], - ""responses"": { - ""200"": { - ""$ref"": ""#/responses/response1"" - }, - ""400"": { - ""description"": null, - ""schema"": { - ""maximum"": 10, - ""minimum"": 5, - ""type"": ""number"" - } - } - }, - ""schemes"": [ - ""http"" - ], - ""security"": [ - { - ""securitySchemeId1"": [ ], - ""securitySchemeId2"": [ - ""scopeName1"", - ""scopeName2"" - ] - } - ] -}"; + var expected = + """ + { + "tags": [ + "tagName1", + "tagId1" + ], + "summary": "summary1", + "description": "operationDescription", + "externalDocs": { + "description": "externalDocsDescription", + "url": "http://external.com" + }, + "operationId": "operationId1", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "in": "path", + "name": "parameter1" + }, + { + "in": "header", + "name": "parameter2" + }, + { + "in": "body", + "name": "body", + "description": "description2", + "required": true, + "schema": { + "maximum": 10, + "minimum": 5, + "type": "number" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/response1" + }, + "400": { + "description": null, + "schema": { + "maximum": 10, + "minimum": 5, + "type": "number" + } + } + }, + "schemes": [ + "http" + ], + "security": [ + { + "securitySchemeId1": [ ], + "securitySchemeId2": [ + "scopeName1", + "scopeName2" + ] + } + ] + } + """; // Act var actual = _advancedOperationWithTagsAndSecurity.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); @@ -766,9 +790,12 @@ public void SerializeAdvancedOperationWithTagAndSecurityAsV2JsonWorks() public void SerializeOperationWithNullCollectionAsV2JsonWorks() { // Arrange - var expected = @"{ - ""responses"": { } -}"; + var expected = + """ + { + "responses": { } + } + """; var operation = new OpenApiOperation { Parameters = null, diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index 2a2c65202..8ffb122ef 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs @@ -211,10 +211,13 @@ public void WhenStyleAndInIsNullTheDefaultValueOfStyleShouldBeSimple(ParameterLo public void SerializeBasicParameterAsV3JsonWorks() { // Arrange - var expected = @"{ - ""name"": ""name1"", - ""in"": ""path"" -}"; + var expected = + """ + { + "name": "name1", + "in": "path" + } + """; // Act var actual = BasicParameter.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -229,33 +232,36 @@ public void SerializeBasicParameterAsV3JsonWorks() public void SerializeAdvancedParameterAsV3JsonWorks() { // Arrange - var expected = @"{ - ""name"": ""name1"", - ""in"": ""path"", - ""description"": ""description1"", - ""required"": true, - ""style"": ""simple"", - ""explode"": true, - ""schema"": { - ""title"": ""title2"", - ""oneOf"": [ - { - ""type"": ""number"", - ""format"": ""double"" - }, - { - ""type"": ""string"" - } - ], - ""description"": ""description2"" - }, - ""examples"": { - ""test"": { - ""summary"": ""summary3"", - ""description"": ""description3"" - } - } -}"; + var expected = + """ + { + "name": "name1", + "in": "path", + "description": "description1", + "required": true, + "style": "simple", + "explode": true, + "schema": { + "title": "title2", + "oneOf": [ + { + "type": "number", + "format": "double" + }, + { + "type": "string" + } + ], + "description": "description2" + }, + "examples": { + "test": { + "summary": "summary3", + "description": "description3" + } + } + } + """; // Act var actual = AdvancedPathParameterWithSchema.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -270,13 +276,16 @@ public void SerializeAdvancedParameterAsV3JsonWorks() public void SerializeAdvancedParameterAsV2JsonWorks() { // Arrange - var expected = @"{ - ""in"": ""path"", - ""name"": ""name1"", - ""description"": ""description1"", - ""required"": true, - ""format"": ""double"" -}"; + var expected = + """ + { + "in": "path", + "name": "name1", + "description": "description1", + "required": true, + "format": "double" + } + """; // Act var actual = AdvancedPathParameterWithSchema.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs index b9edd2a32..5b7426fca 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs @@ -90,9 +90,12 @@ public void SerializeSchemaReferenceAsJsonV3Works() { // Arrange var reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "Pet" }; - var expected = @"{ - ""$ref"": ""#/components/schemas/Pet"" -}"; + var expected = + """ + { + "$ref": "#/components/schemas/Pet" + } + """; // Act var actual = reference.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -132,9 +135,12 @@ public void SerializeSchemaReferenceAsJsonV2Works() Id = "Pet" }; - var expected = @"{ - ""$ref"": ""#/definitions/Pet"" -}".MakeLineBreaksEnvironmentNeutral(); + var expected = + """ + { + "$ref": "#/definitions/Pet" + } + """.MakeLineBreaksEnvironmentNeutral(); // Act var actual = reference.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); @@ -172,9 +178,12 @@ public void SerializeExternalReferenceAsJsonV2Works() Id = "Pets" }; - var expected = @"{ - ""$ref"": ""main.json#/definitions/Pets"" -}"; + var expected = + """ + { + "$ref": "main.json#/definitions/Pets" + } + """; // Act var actual = reference.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); @@ -210,9 +219,12 @@ public void SerializeExternalReferenceAsJsonV3Works() // Arrange var reference = new OpenApiReference { ExternalResource = "main.json", Type = ReferenceType.Schema,Id = "Pets" }; - var expected = @"{ - ""$ref"": ""main.json#/components/schemas/Pets"" -}"; + var expected = + """ + { + "$ref": "main.json#/components/schemas/Pets" + } + """; // Act var actual = reference.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs index 0010e8cb6..373305603 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs @@ -126,9 +126,13 @@ public void SerializeBasicResponseWorks( OpenApiFormat format) { // Arrange - var expected = format == OpenApiFormat.Json ? @"{ - ""description"": null -}" : @"description: "; + var expected = format == OpenApiFormat.Json ? + """ + { + "description": null + } + """ : + @"description: "; // Act var actual = BasicResponse.Serialize(version, format); @@ -143,35 +147,37 @@ public void SerializeBasicResponseWorks( public void SerializeAdvancedResponseAsV3JsonWorks() { // Arrange - var expected = @"{ - ""description"": ""A complex object array response"", - ""headers"": { - ""X-Rate-Limit-Limit"": { - ""description"": ""The number of allowed requests in the current period"", - ""schema"": { - ""type"": ""integer"" - } - }, - ""X-Rate-Limit-Reset"": { - ""description"": ""The number of seconds left in the current period"", - ""schema"": { - ""type"": ""integer"" - } - } - }, - ""content"": { - ""text/plain"": { - ""schema"": { - ""type"": ""array"", - ""items"": { - ""$ref"": ""#/components/schemas/customType"" - } - }, - ""example"": ""Blabla"", - ""myextension"": ""myextensionvalue"" - } - } -}"; + var expected = """ + { + "description": "A complex object array response", + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "schema": { + "type": "integer" + } + } + }, + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/customType" + } + }, + "example": "Blabla", + "myextension": "myextensionvalue" + } + } + } + """; // Act var actual = AdvancedResponse.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -187,24 +193,26 @@ public void SerializeAdvancedResponseAsV3YamlWorks() { // Arrange var expected = - @"description: A complex object array response -headers: - X-Rate-Limit-Limit: - description: The number of allowed requests in the current period - schema: - type: integer - X-Rate-Limit-Reset: - description: The number of seconds left in the current period - schema: - type: integer -content: - text/plain: - schema: - type: array - items: - $ref: '#/components/schemas/customType' - example: Blabla - myextension: myextensionvalue"; + """ + description: A complex object array response + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer + X-Rate-Limit-Reset: + description: The number of seconds left in the current period + schema: + type: integer + content: + text/plain: + schema: + type: array + items: + $ref: '#/components/schemas/customType' + example: Blabla + myextension: myextensionvalue + """; // Act var actual = AdvancedResponse.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -219,29 +227,32 @@ public void SerializeAdvancedResponseAsV3YamlWorks() public void SerializeAdvancedResponseAsV2JsonWorks() { // Arrange - var expected = @"{ - ""description"": ""A complex object array response"", - ""schema"": { - ""type"": ""array"", - ""items"": { - ""$ref"": ""#/definitions/customType"" - } - }, - ""examples"": { - ""text/plain"": ""Blabla"" - }, - ""myextension"": ""myextensionvalue"", - ""headers"": { - ""X-Rate-Limit-Limit"": { - ""description"": ""The number of allowed requests in the current period"", - ""type"": ""integer"" - }, - ""X-Rate-Limit-Reset"": { - ""description"": ""The number of seconds left in the current period"", - ""type"": ""integer"" - } - } -}"; + var expected = + """ + { + "description": "A complex object array response", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/customType" + } + }, + "examples": { + "text/plain": "Blabla" + }, + "myextension": "myextensionvalue", + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "type": "integer" + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "type": "integer" + } + } + } + """; // Act var actual = AdvancedResponse.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); @@ -257,21 +268,23 @@ public void SerializeAdvancedResponseAsV2YamlWorks() { // Arrange var expected = - @"description: A complex object array response -schema: - type: array - items: - $ref: '#/definitions/customType' -examples: - text/plain: Blabla -myextension: myextensionvalue -headers: - X-Rate-Limit-Limit: - description: The number of allowed requests in the current period - type: integer - X-Rate-Limit-Reset: - description: The number of seconds left in the current period - type: integer"; + """ + description: A complex object array response + schema: + type: array + items: + $ref: '#/definitions/customType' + examples: + text/plain: Blabla + myextension: myextensionvalue + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + type: integer + X-Rate-Limit-Reset: + description: The number of seconds left in the current period + type: integer + """; // Act var actual = AdvancedResponse.SerializeAsYaml(OpenApiSpecVersion.OpenApi2_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index 9d84ab63d..63767c498 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -245,19 +245,22 @@ public void SerializeBasicSchemaAsV3JsonWorks() public void SerializeAdvancedSchemaNumberAsV3JsonWorks() { // Arrange - var expected = @"{ - ""title"": ""title1"", - ""multipleOf"": 3, - ""maximum"": 42, - ""minimum"": 10, - ""exclusiveMinimum"": true, - ""type"": ""integer"", - ""default"": 15, - ""nullable"": true, - ""externalDocs"": { - ""url"": ""http://example.com/externalDocs"" - } -}"; + var expected = + """ + { + "title": "title1", + "multipleOf": 3, + "maximum": 42, + "minimum": 10, + "exclusiveMinimum": true, + "type": "integer", + "default": 15, + "nullable": true, + "externalDocs": { + "url": "http://example.com/externalDocs" + } + } + """; // Act var actual = AdvancedSchemaNumber.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -272,41 +275,44 @@ public void SerializeAdvancedSchemaNumberAsV3JsonWorks() public void SerializeAdvancedSchemaObjectAsV3JsonWorks() { // Arrange - var expected = @"{ - ""title"": ""title1"", - ""properties"": { - ""property1"": { - ""properties"": { - ""property2"": { - ""type"": ""integer"" - }, - ""property3"": { - ""maxLength"": 15, - ""type"": ""string"" - } - } - }, - ""property4"": { - ""properties"": { - ""property5"": { - ""properties"": { - ""property6"": { - ""type"": ""boolean"" - } - } - }, - ""property7"": { - ""minLength"": 2, - ""type"": ""string"" - } - } - } - }, - ""nullable"": true, - ""externalDocs"": { - ""url"": ""http://example.com/externalDocs"" - } -}"; + var expected = + """ + { + "title": "title1", + "properties": { + "property1": { + "properties": { + "property2": { + "type": "integer" + }, + "property3": { + "maxLength": 15, + "type": "string" + } + } + }, + "property4": { + "properties": { + "property5": { + "properties": { + "property6": { + "type": "boolean" + } + } + }, + "property7": { + "minLength": 2, + "type": "string" + } + } + } + }, + "nullable": true, + "externalDocs": { + "url": "http://example.com/externalDocs" + } + } + """; // Act var actual = AdvancedSchemaObject.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -321,44 +327,47 @@ public void SerializeAdvancedSchemaObjectAsV3JsonWorks() public void SerializeAdvancedSchemaWithAllOfAsV3JsonWorks() { // Arrange - var expected = @"{ - ""title"": ""title1"", - ""allOf"": [ - { - ""title"": ""title2"", - ""properties"": { - ""property1"": { - ""type"": ""integer"" - }, - ""property2"": { - ""maxLength"": 15, - ""type"": ""string"" - } - } - }, - { - ""title"": ""title3"", - ""properties"": { - ""property3"": { - ""properties"": { - ""property4"": { - ""type"": ""boolean"" - } - } - }, - ""property5"": { - ""minLength"": 2, - ""type"": ""string"" - } - }, - ""nullable"": true - } - ], - ""nullable"": true, - ""externalDocs"": { - ""url"": ""http://example.com/externalDocs"" - } -}"; + var expected = + """ + { + "title": "title1", + "allOf": [ + { + "title": "title2", + "properties": { + "property1": { + "type": "integer" + }, + "property2": { + "maxLength": 15, + "type": "string" + } + } + }, + { + "title": "title3", + "properties": { + "property3": { + "properties": { + "property4": { + "type": "boolean" + } + } + }, + "property5": { + "minLength": 2, + "type": "string" + } + }, + "nullable": true + } + ], + "nullable": true, + "externalDocs": { + "url": "http://example.com/externalDocs" + } + } + """; // Act var actual = AdvancedSchemaWithAllOf.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -448,15 +457,18 @@ public void SerializeAsV2ShouldSetFormatPropertyInParentSchemaIfPresentInChildre var v2Schema = outputStringWriter.GetStringBuilder().ToString().MakeLineBreaksEnvironmentNeutral(); - var expectedV2Schema = @"{ - ""format"": ""decimal"", - ""allOf"": [ - { - ""format"": ""decimal"", - ""type"": ""number"" - } - ] -}".MakeLineBreaksEnvironmentNeutral(); + var expectedV2Schema = + """ + { + "format": "decimal", + "allOf": [ + { + "format": "decimal", + "type": "number" + } + ] + } + """.MakeLineBreaksEnvironmentNeutral(); // Assert Assert.Equal(expectedV2Schema, v2Schema); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs index 7d630c5f6..220837531 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs @@ -100,18 +100,20 @@ public void SerializeSecurityRequirementWithReferencedSecuritySchemeAsV3JsonWork { // Arrange var expected = - @"{ - ""scheme1"": [ - ""scope1"", - ""scope2"", - ""scope3"" - ], - ""scheme2"": [ - ""scope4"", - ""scope5"" - ], - ""scheme3"": [ ] -}"; + """ + { + "scheme1": [ + "scope1", + "scope2", + "scope3" + ], + "scheme2": [ + "scope4", + "scope5" + ], + "scheme3": [ ] + } + """; // Act var actual = @@ -128,18 +130,20 @@ public void SerializeSecurityRequirementWithReferencedSecuritySchemeAsV2JsonWork { // Arrange var expected = - @"{ - ""scheme1"": [ - ""scope1"", - ""scope2"", - ""scope3"" - ], - ""scheme2"": [ - ""scope4"", - ""scope5"" - ], - ""scheme3"": [ ] -}"; + """ + { + "scheme1": [ + "scope1", + "scope2", + "scope3" + ], + "scheme2": [ + "scope4", + "scope5" + ], + "scheme3": [ ] + } + """; // Act var actual = SecurityRequirementWithReferencedSecurityScheme.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0); @@ -156,14 +160,16 @@ public void { // Arrange var expected = - @"{ - ""scheme1"": [ - ""scope1"", - ""scope2"", - ""scope3"" - ], - ""scheme3"": [ ] -}"; + """ + { + "scheme1": [ + "scope1", + "scope2", + "scope3" + ], + "scheme3": [ ] + } + """; // Act var actual = @@ -181,14 +187,16 @@ public void { // Arrange var expected = - @"{ - ""scheme1"": [ - ""scope1"", - ""scope2"", - ""scope3"" - ], - ""scheme3"": [ ] -}"; + """ + { + "scheme1": [ + "scope1", + "scope2", + "scope3" + ], + "scheme3": [ ] + } + """; // Act var actual = diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs index 44a388d90..acb4323f1 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs @@ -133,12 +133,14 @@ public void SerializeApiKeySecuritySchemeAsV3JsonWorks() { // Arrange var expected = - @"{ - ""type"": ""apiKey"", - ""description"": ""description1"", - ""name"": ""parameterName"", - ""in"": ""query"" -}"; + """ + { + "type": "apiKey", + "description": "description1", + "name": "parameterName", + "in": "query" + } + """; // Act var actual = ApiKeySecurityScheme.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -154,10 +156,12 @@ public void SerializeApiKeySecuritySchemeAsV3YamlWorks() { // Arrange var expected = - @"type: apiKey -description: description1 -name: parameterName -in: query"; + """ + type: apiKey + description: description1 + name: parameterName + in: query + """; // Act var actual = ApiKeySecurityScheme.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); @@ -173,11 +177,13 @@ public void SerializeHttpBasicSecuritySchemeAsV3JsonWorks() { // Arrange var expected = - @"{ - ""type"": ""http"", - ""description"": ""description1"", - ""scheme"": ""basic"" -}"; + """ + { + "type": "http", + "description": "description1", + "scheme": "basic" + } + """; // Act var actual = HttpBasicSecurityScheme.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -193,12 +199,14 @@ public void SerializeHttpBearerSecuritySchemeAsV3JsonWorks() { // Arrange var expected = - @"{ - ""type"": ""http"", - ""description"": ""description1"", - ""scheme"": ""bearer"", - ""bearerFormat"": ""JWT"" -}"; + """ + { + "type": "http", + "description": "description1", + "scheme": "bearer", + "bearerFormat": "JWT" + } + """; // Act var actual = HttpBearerSecurityScheme.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -214,19 +222,21 @@ public void SerializeOAuthSingleFlowSecuritySchemeAsV3JsonWorks() { // Arrange var expected = - @"{ - ""type"": ""oauth2"", - ""description"": ""description1"", - ""flows"": { - ""implicit"": { - ""authorizationUrl"": ""https://example.com/api/oauth"", - ""scopes"": { - ""operation1:object1"": ""operation 1 on object 1"", - ""operation2:object2"": ""operation 2 on object 2"" - } - } - } -}"; + """ + { + "type": "oauth2", + "description": "description1", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth", + "scopes": { + "operation1:object1": "operation 1 on object 1", + "operation2:object2": "operation 2 on object 2" + } + } + } + } + """; // Act var actual = OAuth2SingleFlowSecurityScheme.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -242,35 +252,37 @@ public void SerializeOAuthMultipleFlowSecuritySchemeAsV3JsonWorks() { // Arrange var expected = - @"{ - ""type"": ""oauth2"", - ""description"": ""description1"", - ""flows"": { - ""implicit"": { - ""authorizationUrl"": ""https://example.com/api/oauth"", - ""scopes"": { - ""operation1:object1"": ""operation 1 on object 1"", - ""operation2:object2"": ""operation 2 on object 2"" - } - }, - ""clientCredentials"": { - ""tokenUrl"": ""https://example.com/api/token"", - ""refreshUrl"": ""https://example.com/api/refresh"", - ""scopes"": { - ""operation1:object1"": ""operation 1 on object 1"", - ""operation2:object2"": ""operation 2 on object 2"" - } - }, - ""authorizationCode"": { - ""authorizationUrl"": ""https://example.com/api/oauth"", - ""tokenUrl"": ""https://example.com/api/token"", - ""scopes"": { - ""operation1:object1"": ""operation 1 on object 1"", - ""operation2:object2"": ""operation 2 on object 2"" - } - } - } -}"; + """ + { + "type": "oauth2", + "description": "description1", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth", + "scopes": { + "operation1:object1": "operation 1 on object 1", + "operation2:object2": "operation 2 on object 2" + } + }, + "clientCredentials": { + "tokenUrl": "https://example.com/api/token", + "refreshUrl": "https://example.com/api/refresh", + "scopes": { + "operation1:object1": "operation 1 on object 1", + "operation2:object2": "operation 2 on object 2" + } + }, + "authorizationCode": { + "authorizationUrl": "https://example.com/api/oauth", + "tokenUrl": "https://example.com/api/token", + "scopes": { + "operation1:object1": "operation 1 on object 1", + "operation2:object2": "operation 2 on object 2" + } + } + } + } + """; // Act var actual = OAuth2MultipleFlowSecurityScheme.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -286,11 +298,13 @@ public void SerializeOpenIdConnectSecuritySchemeAsV3JsonWorks() { // Arrange var expected = - @"{ - ""type"": ""openIdConnect"", - ""description"": ""description1"", - ""openIdConnectUrl"": ""https://example.com/openIdConnect"" -}"; + """ + { + "type": "openIdConnect", + "description": "description1", + "openIdConnectUrl": "https://example.com/openIdConnect" + } + """; // Act var actual = OpenIdConnectSecurityScheme.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs index e4d4f36fb..a249591ab 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs @@ -51,10 +51,12 @@ public void SerializeBasicServerAsV3JsonWorks() { // Arrange var expected = - @"{ - ""url"": ""https://example.com/server1"", - ""description"": ""description1"" -}"; + """ + { + "url": "https://example.com/server1", + "description": "description1" + } + """; // Act var actual = BasicServer.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -70,27 +72,29 @@ public void SerializeAdvancedServerAsV3JsonWorks() { // Arrange var expected = - @"{ - ""url"": ""https://{username}.example.com:{port}/{basePath}"", - ""description"": ""description1"", - ""variables"": { - ""username"": { - ""default"": ""unknown"", - ""description"": ""variableDescription1"" - }, - ""port"": { - ""default"": ""8443"", - ""description"": ""variableDescription2"", - ""enum"": [ - ""443"", - ""8443"" - ] - }, - ""basePath"": { - ""default"": ""v1"" - } - } -}"; + """ + { + "url": "https://{username}.example.com:{port}/{basePath}", + "description": "description1", + "variables": { + "username": { + "default": "unknown", + "description": "variableDescription1" + }, + "port": { + "default": "8443", + "description": "variableDescription2", + "enum": [ + "443", + "8443" + ] + }, + "basePath": { + "default": "v1" + } + } + } + """; // Act var actual = AdvancedServer.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs index 9d50f76f6..89e341aac 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs @@ -44,14 +44,16 @@ public void SerializeAdvancedServerVariableAsV3JsonWorks() { // Arrange var expected = - @"{ - ""default"": ""8443"", - ""description"": ""test description"", - ""enum"": [ - ""8443"", - ""443"" - ] -}"; + """ + { + "default": "8443", + "description": "test description", + "enum": [ + "8443", + "443" + ] + } + """; // Act var actual = AdvancedServerVariable.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); @@ -67,11 +69,13 @@ public void SerializeAdvancedServerVariableAsV3YamlWorks() { // Arrange var expected = - @"default: '8443' -description: test description -enum: - - '8443' - - '443'"; + """ + default: '8443' + description: test description + enum: + - '8443' + - '443' + """; // Act var actual = AdvancedServerVariable.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs index 66c0dfd70..ceb8620e8 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs @@ -160,12 +160,14 @@ public void SerializeAdvancedTagAsV3YamlWithoutReferenceWorks() var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = - @"name: pet -description: Pets operations -externalDocs: - description: Find more info here - url: https://example.com -x-tag-extension: "; + """ + name: pet + description: Pets operations + externalDocs: + description: Find more info here + url: https://example.com + x-tag-extension: + """; // Act AdvancedTag.SerializeAsV3WithoutReference(writer); @@ -185,12 +187,14 @@ public void SerializeAdvancedTagAsV2YamlWithoutReferenceWorks() var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = - @"name: pet -description: Pets operations -externalDocs: - description: Find more info here - url: https://example.com -x-tag-extension: "; + """ + name: pet + description: Pets operations + externalDocs: + description: Find more info here + url: https://example.com + x-tag-extension: + """; // Act AdvancedTag.SerializeAsV2WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs index 9e79c5211..ebc303fb9 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs @@ -54,14 +54,16 @@ public void SerializeAdvancedXmlAsJsonWorks(OpenApiSpecVersion version) { // Arrange var expected = - @"{ - ""name"": ""animal"", - ""namespace"": ""http://swagger.io/schema/sample"", - ""prefix"": ""sample"", - ""attribute"": true, - ""wrapped"": true, - ""x-xml-extension"": 7 -}"; + """ + { + "name": "animal", + "namespace": "http://swagger.io/schema/sample", + "prefix": "sample", + "attribute": true, + "wrapped": true, + "x-xml-extension": 7 + } + """; // Act var actual = AdvancedXml.SerializeAsJson(version); @@ -79,12 +81,14 @@ public void SerializeAdvancedXmlAsYamlWorks(OpenApiSpecVersion version) { // Arrange var expected = - @"name: animal -namespace: http://swagger.io/schema/sample -prefix: sample -attribute: true -wrapped: true -x-xml-extension: 7"; + """ + name: animal + namespace: http://swagger.io/schema/sample + prefix: sample + attribute: true + wrapped: true + x-xml-extension: 7 + """; // Act var actual = AdvancedXml.SerializeAsYaml(version); diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs index 1a15ea3b4..3992315e8 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs @@ -39,23 +39,27 @@ public static IEnumerable WriteStringListAsYamlShouldMatchExpectedTest "string7", "string8" }, - @"- string1 -- string2 -- string3 -- string4 -- string5 -- string6 -- string7 -- string8" + """ + - string1 + - string2 + - string3 + - string4 + - string5 + - string6 + - string7 + - string8 + """ }; yield return new object[] { new[] {"string1", "string1", "string1", "string1"}, - @"- string1 -- string1 -- string1 -- string1" + """ + - string1 + - string1 + - string1 + - string1 + """ }; } @@ -99,10 +103,12 @@ public static IEnumerable WriteMapAsYamlShouldMatchExpectedTestCasesSi ["property3"] = "value3", ["property4"] = "value4" }, - @"property1: value1 -property2: value2 -property3: value3 -property4: value4" + """ + property1: value1 + property2: value2 + property3: value3 + property4: value4 + """ }; // Simple map with duplicate value @@ -115,10 +121,12 @@ public static IEnumerable WriteMapAsYamlShouldMatchExpectedTestCasesSi ["property3"] = "value1", ["property4"] = "value1" }, - @"property1: value1 -property2: value1 -property3: value1 -property4: value1" + """ + property1: value1 + property2: value1 + property3: value1 + property4: value1 + """ }; } @@ -137,11 +145,13 @@ public static IEnumerable WriteMapAsYamlShouldMatchExpectedTestCasesCo }, ["property4"] = "value4" }, - @"property1: { } -property2: [ ] -property3: - - { } -property4: value4" + """ + property1: { } + property2: [ ] + property3: + - { } + property4: value4 + """ }; // Number, boolean, and null handling @@ -161,17 +171,19 @@ public static IEnumerable WriteMapAsYamlShouldMatchExpectedTestCasesCo ["property10"] = "null", ["property11"] = "", }, - @"property1: '10.0' -property2: '10' -property3: '-5' -property4: 10.0 -property5: 10 -property6: -5 -property7: true -property8: 'true' -property9: -property10: 'null' -property11: ''" + """ + property1: '10.0' + property2: '10' + property3: '-5' + property4: 10.0 + property5: 10 + property6: -5 + property7: true + property8: 'true' + property9: + property10: 'null' + property11: '' + """ }; // DateTime @@ -183,9 +195,11 @@ public static IEnumerable WriteMapAsYamlShouldMatchExpectedTestCasesCo ["property2"] = new DateTimeOffset(new DateTime(1970, 01, 01), TimeSpan.FromHours(3)), ["property3"] = new DateTime(2018, 04, 03), }, - @"property1: '1970-01-01T00:00:00.0000000' -property2: '1970-01-01T00:00:00.0000000+03:00' -property3: '2018-04-03T00:00:00.0000000'" + """ + property1: '1970-01-01T00:00:00.0000000' + property2: '1970-01-01T00:00:00.0000000+03:00' + property3: '2018-04-03T00:00:00.0000000' + """ }; // Nested map @@ -204,12 +218,14 @@ public static IEnumerable WriteMapAsYamlShouldMatchExpectedTestCasesCo }, ["property4"] = "value4" }, - @"property1: - innerProperty1: innerValue1 -property2: value2 -property3: - innerProperty3: innerValue3 -property4: value4" + """ + property1: + innerProperty1: innerValue1 + property2: value2 + property3: + innerProperty3: innerValue3 + property4: value4 + """ }; // Nested map and list @@ -238,17 +254,19 @@ public static IEnumerable WriteMapAsYamlShouldMatchExpectedTestCasesCo }, ["property4"] = "value4" }, - @"property1: { } -property2: [ ] -property3: - - { } - - string1 - - innerProperty1: [ ] - innerProperty2: string2 - innerProperty3: - - - - string3 -property4: value4" + """ + property1: { } + property2: [ ] + property3: + - { } + - string1 + - innerProperty1: [ ] + innerProperty2: string2 + innerProperty3: + - + - string3 + property4: value4 + """ }; } @@ -356,21 +374,23 @@ public void WriteInlineSchema() var doc = CreateDocWithSimpleSchemaToInline(); var expected = -@"openapi: 3.0.1 -info: - title: Demo - version: 1.0.0 -paths: - /: - get: - responses: - '200': - description: OK - content: - application/json: - schema: - type: object -components: { }"; + """ + openapi: 3.0.1 + info: + title: Demo + version: 1.0.0 + paths: + /: + get: + responses: + '200': + description: OK + content: + application/json: + schema: + type: object + components: { } + """; var outputString = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true } ); @@ -393,20 +413,22 @@ public void WriteInlineSchemaV2() var doc = CreateDocWithSimpleSchemaToInline(); var expected = -@"swagger: '2.0' -info: - title: Demo - version: 1.0.0 -paths: - /: - get: - produces: - - application/json - responses: - '200': - description: OK - schema: - type: object"; + """ + swagger: '2.0' + info: + title: Demo + version: 1.0.0 + paths: + /: + get: + produces: + - application/json + responses: + '200': + description: OK + schema: + type: object + """; var outputString = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true }); @@ -481,39 +503,41 @@ public void WriteInlineRecursiveSchema() var doc = CreateDocWithRecursiveSchemaReference(); var expected = -@"openapi: 3.0.1 -info: - title: Demo - version: 1.0.0 -paths: - /: - get: - responses: - '200': - description: OK - content: - application/json: - schema: - type: object - properties: - children: - $ref: '#/components/schemas/thing' - related: - type: integer -components: - schemas: - thing: - type: object - properties: - children: - type: object - properties: - children: - $ref: '#/components/schemas/thing' - related: - type: integer - related: - type: integer"; + """ + openapi: 3.0.1 + info: + title: Demo + version: 1.0.0 + paths: + /: + get: + responses: + '200': + description: OK + content: + application/json: + schema: + type: object + properties: + children: + $ref: '#/components/schemas/thing' + related: + type: integer + components: + schemas: + thing: + type: object + properties: + children: + type: object + properties: + children: + $ref: '#/components/schemas/thing' + related: + type: integer + related: + type: integer + """; // Component schemas that are there due to cycles are still inlined because the items they reference may not exist in the components because they don't have cycles. var outputString = new StringWriter(CultureInfo.InvariantCulture); @@ -594,38 +618,40 @@ public void WriteInlineRecursiveSchemav2() var doc = CreateDocWithRecursiveSchemaReference(); var expected = -@"swagger: '2.0' -info: - title: Demo - version: 1.0.0 -paths: - /: - get: - produces: - - application/json - responses: - '200': - description: OK - schema: - type: object - properties: - children: - $ref: '#/definitions/thing' - related: - type: integer -definitions: - thing: - type: object - properties: - children: - type: object - properties: - children: - $ref: '#/definitions/thing' - related: - type: integer - related: - type: integer"; + """ + swagger: '2.0' + info: + title: Demo + version: 1.0.0 + paths: + /: + get: + produces: + - application/json + responses: + '200': + description: OK + schema: + type: object + properties: + children: + $ref: '#/definitions/thing' + related: + type: integer + definitions: + thing: + type: object + properties: + children: + type: object + properties: + children: + $ref: '#/definitions/thing' + related: + type: integer + related: + type: integer + """; // Component schemas that are there due to cycles are still inlined because the items they reference may not exist in the components because they don't have cycles. var outputString = new StringWriter(CultureInfo.InvariantCulture); From 9aa78970d208b2c6c5221ae8dffb56e06c8a835c Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:49:56 +1100 Subject: [PATCH 644/855] inline some out variables --- .../ParseNodes/MapNode.cs | 7 ++----- .../ParseNodes/PropertyNode.cs | 3 +-- src/Microsoft.OpenApi.Readers/ParsingContext.cs | 3 +-- src/Microsoft.OpenApi/Services/LoopDetector.cs | 3 +-- .../Validations/ValidationRuleSet.cs | 3 +-- .../V2Tests/OpenApiContactTests.cs | 3 +-- .../V3Tests/OpenApiContactTests.cs | 3 +-- .../V3Tests/OpenApiSchemaTests.cs | 15 +++++---------- 8 files changed, 13 insertions(+), 27 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs index 0ee5934ce..c822e05dd 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs @@ -47,8 +47,7 @@ public PropertyNode this[string key] { get { - YamlNode node; - if (this._node.Children.TryGetValue(new YamlScalarNode(key), out node)) + if (this._node.Children.TryGetValue(new YamlScalarNode(key), out var node)) { return new PropertyNode(Context, key, node); } @@ -193,9 +192,7 @@ public T GetReferencedObject(ReferenceType referenceType, string referenceId) public string GetReferencePointer() { - YamlNode refNode; - - if (!_node.Children.TryGetValue(new YamlScalarNode("$ref"), out refNode)) + if (!_node.Children.TryGetValue(new YamlScalarNode("$ref"), out var refNode)) { return null; } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs index 2dd2c7e8a..0bd42e25f 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs @@ -30,8 +30,7 @@ public void ParseField( IDictionary> fixedFields, IDictionary, Action> patternFields) { - Action fixedFieldMap; - var found = fixedFields.TryGetValue(Name, out fixedFieldMap); + var found = fixedFields.TryGetValue(Name, out var fixedFieldMap); if (fixedFieldMap != null) { diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index 0cd98c67e..ccf97117d 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -206,8 +206,7 @@ public void StartObject(string objectName) /// If method returns false a loop was detected and the key is not added. public bool PushLoop(string loopId, string key) { - Stack stack; - if (!_loopStacks.TryGetValue(loopId, out stack)) + if (!_loopStacks.TryGetValue(loopId, out var stack)) { stack = new Stack(); _loopStacks.Add(loopId, stack); diff --git a/src/Microsoft.OpenApi/Services/LoopDetector.cs b/src/Microsoft.OpenApi/Services/LoopDetector.cs index 249cab51d..4fb1b8b4e 100644 --- a/src/Microsoft.OpenApi/Services/LoopDetector.cs +++ b/src/Microsoft.OpenApi/Services/LoopDetector.cs @@ -17,8 +17,7 @@ internal class LoopDetector /// If method returns false a loop was detected and the key is not added. public bool PushLoop(T key) { - Stack stack; - if (!_loopStacks.TryGetValue(typeof(T), out stack)) + if (!_loopStacks.TryGetValue(typeof(T), out var stack)) { stack = new Stack(); _loopStacks.Add(typeof(T), stack); diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index eca7bc8de..3d469d3c2 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -30,8 +30,7 @@ public sealed class ValidationRuleSet : IEnumerable /// Either the rules related to the type, or an empty list. public IList FindRules(Type type) { - IList results = null; - _rules.TryGetValue(type, out results); + _rules.TryGetValue(type, out var results); return results ?? _emptyRules; } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs index 71489d39f..6e0ae0472 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs @@ -21,10 +21,9 @@ public void ParseStringContactFragmentShouldSucceed() } "; var reader = new OpenApiStringReader(); - var diagnostic = new OpenApiDiagnostic(); // Act - var contact = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi2_0, out diagnostic); + var contact = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi2_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs index be78f942b..1e8cd0934 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs @@ -21,10 +21,9 @@ public void ParseStringContactFragmentShouldSucceed() } "; var reader = new OpenApiStringReader(); - var diagnostic = new OpenApiDiagnostic(); // Act - var contact = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + var contact = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index 0101d9c6e..bcb088c3f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -54,10 +54,9 @@ public void ParsePrimitiveSchemaFragmentShouldSucceed() using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "primitiveSchema.yaml"))) { var reader = new OpenApiStreamReader(); - var diagnostic = new OpenApiDiagnostic(); // Act - var schema = reader.ReadFragment(stream, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + var schema = reader.ReadFragment(stream, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); @@ -81,10 +80,9 @@ public void ParsePrimitiveStringSchemaFragmentShouldSucceed() } "; var reader = new OpenApiStringReader(); - var diagnostic = new OpenApiDiagnostic(); // Act - var schema = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + var schema = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); @@ -107,10 +105,9 @@ public void ParseExampleStringFragmentShouldSucceed() ""baz"": [ 1,2] }"; var reader = new OpenApiStringReader(); - var diagnostic = new OpenApiDiagnostic(); // Act - var openApiAny = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + var openApiAny = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); @@ -135,10 +132,9 @@ public void ParseEnumFragmentShouldSucceed() ""baz"" ]"; var reader = new OpenApiStringReader(); - var diagnostic = new OpenApiDiagnostic(); // Act - var openApiAny = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + var openApiAny = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); @@ -212,10 +208,9 @@ public void ParsePathFragmentShouldSucceed() description: Ok "; var reader = new OpenApiStringReader(); - var diagnostic = new OpenApiDiagnostic(); // Act - var openApiAny = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + var openApiAny = reader.ReadFragment(input, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); From aa80139f16a435291e118b4ae827e3ad90ede762 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:51:11 +1100 Subject: [PATCH 645/855] use negation pattern --- .../ParseNodes/MapNode.cs | 2 +- .../ParseNodes/OpenApiAnyConverter.cs | 2 +- .../ParseNodes/ParseNode.cs | 2 +- .../ParseNodes/ValueNode.cs | 2 +- .../Validations/Rules/RuleHelpers.cs | 30 +++++++++---------- .../Validations/ValidationRule.cs | 2 +- test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs | 2 +- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs index 0ee5934ce..2ce5e3431 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs @@ -30,7 +30,7 @@ public MapNode(ParsingContext context, string yamlString) : public MapNode(ParsingContext context, YamlNode node) : base( context) { - if (!(node is YamlMappingNode mapNode)) + if (node is not YamlMappingNode mapNode) { throw new OpenApiReaderException("Expected map.", Context); } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs index ae9254fe8..a12142075 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs @@ -50,7 +50,7 @@ public static IOpenApiAny GetSpecificOpenApiAny(IOpenApiAny openApiAny, OpenApiS return newObject; } - if (!(openApiAny is OpenApiString)) + if (openApiAny is not OpenApiString) { return openApiAny; } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs index 295b02bf3..24a49f6cc 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs @@ -24,7 +24,7 @@ protected ParseNode(ParsingContext parsingContext) public MapNode CheckMapNode(string nodeName) { - if (!(this is MapNode mapNode)) + if (this is not MapNode mapNode) { throw new OpenApiReaderException($"{nodeName} must be a map/object", Context); } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs index 68f4bd7ea..6efdcf04d 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs @@ -15,7 +15,7 @@ internal class ValueNode : ParseNode public ValueNode(ParsingContext context, YamlNode node) : base( context) { - if (!(node is YamlScalarNode scalarNode)) + if (node is not YamlScalarNode scalarNode) { throw new OpenApiReaderException("Expected a value.", node); } diff --git a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs index 630dc8e65..731bd8693 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs @@ -75,7 +75,7 @@ public static void ValidateDataTypeMismatch( } // If value is not a string and also not an object, there is a data mismatch. - if (!(value is OpenApiObject)) + if (value is not OpenApiObject) { context.CreateWarning( ruleName, @@ -115,7 +115,7 @@ public static void ValidateDataTypeMismatch( } // If value is not a string and also not an array, there is a data mismatch. - if (!(value is OpenApiArray)) + if (value is not OpenApiArray) { context.CreateWarning( ruleName, @@ -139,7 +139,7 @@ public static void ValidateDataTypeMismatch( if (type == "integer" && format == "int32") { - if (!(value is OpenApiInteger)) + if (value is not OpenApiInteger) { context.CreateWarning( ruleName, @@ -151,7 +151,7 @@ public static void ValidateDataTypeMismatch( if (type == "integer" && format == "int64") { - if (!(value is OpenApiLong)) + if (value is not OpenApiLong) { context.CreateWarning( ruleName, @@ -161,9 +161,9 @@ public static void ValidateDataTypeMismatch( return; } - if (type == "integer" && !(value is OpenApiInteger)) + if (type == "integer" && value is not OpenApiInteger) { - if (!(value is OpenApiInteger)) + if (value is not OpenApiInteger) { context.CreateWarning( ruleName, @@ -175,7 +175,7 @@ public static void ValidateDataTypeMismatch( if (type == "number" && format == "float") { - if (!(value is OpenApiFloat)) + if (value is not OpenApiFloat) { context.CreateWarning( ruleName, @@ -187,7 +187,7 @@ public static void ValidateDataTypeMismatch( if (type == "number" && format == "double") { - if (!(value is OpenApiDouble)) + if (value is not OpenApiDouble) { context.CreateWarning( ruleName, @@ -199,7 +199,7 @@ public static void ValidateDataTypeMismatch( if (type == "number") { - if (!(value is OpenApiDouble)) + if (value is not OpenApiDouble) { context.CreateWarning( ruleName, @@ -211,7 +211,7 @@ public static void ValidateDataTypeMismatch( if (type == "string" && format == "byte") { - if (!(value is OpenApiByte)) + if (value is not OpenApiByte) { context.CreateWarning( ruleName, @@ -223,7 +223,7 @@ public static void ValidateDataTypeMismatch( if (type == "string" && format == "date") { - if (!(value is OpenApiDate)) + if (value is not OpenApiDate) { context.CreateWarning( ruleName, @@ -235,7 +235,7 @@ public static void ValidateDataTypeMismatch( if (type == "string" && format == "date-time") { - if (!(value is OpenApiDateTime)) + if (value is not OpenApiDateTime) { context.CreateWarning( ruleName, @@ -247,7 +247,7 @@ public static void ValidateDataTypeMismatch( if (type == "string" && format == "password") { - if (!(value is OpenApiPassword)) + if (value is not OpenApiPassword) { context.CreateWarning( ruleName, @@ -259,7 +259,7 @@ public static void ValidateDataTypeMismatch( if (type == "string") { - if (!(value is OpenApiString)) + if (value is not OpenApiString) { context.CreateWarning( ruleName, @@ -271,7 +271,7 @@ public static void ValidateDataTypeMismatch( if (type == "boolean") { - if (!(value is OpenApiBoolean)) + if (value is not OpenApiBoolean) { context.CreateWarning( ruleName, diff --git a/src/Microsoft.OpenApi/Validations/ValidationRule.cs b/src/Microsoft.OpenApi/Validations/ValidationRule.cs index fdbf5c330..97a66034d 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRule.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRule.cs @@ -59,7 +59,7 @@ internal override void Evaluate(IValidationContext context, object item) return; } - if (!(item is T)) + if (item is not T) { throw Error.Argument(string.Format(SRResource.InputItemShouldBeType, typeof(T).FullName)); } diff --git a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs index 6d2eafc01..e11be6225 100644 --- a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs +++ b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs @@ -62,7 +62,7 @@ public static IEnumerable GetSchemas() JToken GetProp(JToken obj, string prop) { - if (!(obj is JObject jObj)) + if (obj is not JObject jObj) return null; if (!jObj.TryGetValue(prop, out var jToken)) return null; From c4f02dae769e315e8e22b19cc2710a4299a455b0 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 19:57:00 +1100 Subject: [PATCH 646/855] use pattern matching in casts --- .../ParseNodes/JsonPointerExtensions.cs | 7 ++----- src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs | 6 ++---- src/Microsoft.OpenApi.Readers/YamlHelper.cs | 3 +-- src/Microsoft.OpenApi/Validations/OpenApiValidator.cs | 3 +-- src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs | 3 +-- src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs | 3 +-- test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs | 3 +-- 7 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/JsonPointerExtensions.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/JsonPointerExtensions.cs index d30863955..b8db0fad0 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/JsonPointerExtensions.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/JsonPointerExtensions.cs @@ -26,16 +26,13 @@ public static YamlNode Find(this JsonPointer currentPointer, YamlNode baseYamlNo var pointer = baseYamlNode; foreach (var token in currentPointer.Tokens) { - var sequence = pointer as YamlSequenceNode; - - if (sequence != null) + if (pointer is YamlSequenceNode sequence) { pointer = sequence.Children[Convert.ToInt32(token)]; } else { - var map = pointer as YamlMappingNode; - if (map != null) + if (pointer is YamlMappingNode map) { if (!map.Children.TryGetValue(new YamlScalarNode(token), out pointer)) { diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs index 0ee5934ce..61a833143 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs @@ -152,8 +152,7 @@ public override Dictionary CreateSimpleMap(Func map) try { Context.StartObject(key); - YamlScalarNode scalarNode = n.Value as YamlScalarNode; - if (scalarNode == null) + if (n.Value is not YamlScalarNode scalarNode) { throw new OpenApiReaderException($"Expected scalar while parsing {typeof(T).Name}", Context); } @@ -205,8 +204,7 @@ public string GetReferencePointer() public string GetScalarValue(ValueNode key) { - var scalarNode = _node.Children[new YamlScalarNode(key.GetScalarValue())] as YamlScalarNode; - if (scalarNode == null) + if (_node.Children[new YamlScalarNode(key.GetScalarValue())] is not YamlScalarNode scalarNode) { throw new OpenApiReaderException($"Expected scalar at line {_node.Start.Line} for key {key.GetScalarValue()}", Context); } diff --git a/src/Microsoft.OpenApi.Readers/YamlHelper.cs b/src/Microsoft.OpenApi.Readers/YamlHelper.cs index 90794b080..e49f05e7b 100644 --- a/src/Microsoft.OpenApi.Readers/YamlHelper.cs +++ b/src/Microsoft.OpenApi.Readers/YamlHelper.cs @@ -12,8 +12,7 @@ internal static class YamlHelper { public static string GetScalarValue(this YamlNode node) { - var scalarNode = node as YamlScalarNode; - if (scalarNode == null) + if (node is not YamlScalarNode scalarNode) { throw new OpenApiException($"Expected scalar at line {node.Start.Line}"); } diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index a0aee12e7..838450cc0 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -311,8 +311,7 @@ private void Validate(object item, Type type) } // Validate unresolved references as references - var potentialReference = item as IOpenApiReferenceable; - if (potentialReference != null && potentialReference.UnresolvedReference) + if (item is IOpenApiReferenceable potentialReference && potentialReference.UnresolvedReference) { type = typeof(IOpenApiReferenceable); } diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index eca7bc8de..26d9cf0e3 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -176,8 +176,7 @@ private static ValidationRuleSet BuildDefaultRuleSet() foreach (var property in rules) { var propertyValue = property.GetValue(null); // static property - ValidationRule rule = propertyValue as ValidationRule; - if (rule != null) + if (propertyValue is ValidationRule rule) { ruleSet.Add(rule); } diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs index 537273cac..08aeb4efd 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs @@ -142,8 +142,7 @@ public static void WriteOptionalObject( { if (value != null) { - var values = value as IEnumerable; - if (values != null && !values.GetEnumerator().MoveNext()) + if (value is IEnumerable values && !values.GetEnumerator().MoveNext()) { return; // Don't render optional empty collections } diff --git a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs index 6d2eafc01..c268dbaf0 100644 --- a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs +++ b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs @@ -45,8 +45,7 @@ public static IEnumerable GetSchemas() var json = JObject.Parse(listJsonStr); foreach (var item in json.Properties()) { - var versions = GetProp(item.Value, "versions") as JObject; - if (versions == null) + if (GetProp(item.Value, "versions") is not JObject versions) continue; foreach (var prop in versions.Properties()) { From a2f6198dd295fbe950e4f98c6edf7370f578432c Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 20:01:24 +1100 Subject: [PATCH 647/855] remove some trailing whitespace --- .../Extensions/CommandExtensions.cs | 2 +- .../Formatters/PowerShellFormatter.cs | 2 +- src/Microsoft.OpenApi.Hidi/Logger.cs | 2 +- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 6 +++--- .../Options/FilterOptions.cs | 4 ++-- src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs | 2 +- src/Microsoft.OpenApi.Hidi/StatsVisitor.cs | 2 +- .../Utilities/SettingsUtilities.cs | 2 +- .../Exceptions/OpenApiReaderException.cs | 2 +- .../OpenApiUnsupportedSpecVersionException.cs | 2 +- .../Interface/IDiagnostic.cs | 2 +- .../Interface/IOpenApiReader.cs | 2 +- .../Interface/IOpenApiVersionService.cs | 2 +- .../Interface/IStreamLoader.cs | 2 +- src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs | 2 +- .../OpenApiReaderSettings.cs | 14 +++++++------- .../OpenApiStringReader.cs | 2 +- .../OpenApiTextReaderReader.cs | 2 +- .../OpenApiYamlDocumentReader.cs | 2 +- .../ParseNodes/AnyFieldMap.cs | 2 +- .../ParseNodes/AnyFieldMapParameter.cs | 2 +- .../ParseNodes/AnyListFieldMap.cs | 2 +- .../ParseNodes/AnyListFieldMapParameter.cs | 2 +- .../ParseNodes/AnyMapFieldMap.cs | 2 +- .../ParseNodes/AnyMapFieldMapParameter.cs | 2 +- .../ParseNodes/FixedFieldMap.cs | 2 +- .../ParseNodes/JsonPointerExtensions.cs | 2 +- .../ParseNodes/ListNode.cs | 2 +- .../ParseNodes/MapNode.cs | 10 +++++----- .../ParseNodes/OpenApiAnyConverter.cs | 4 ++-- .../ParseNodes/ParseNode.cs | 2 +- .../ParseNodes/PatternFieldMap.cs | 2 +- .../ParseNodes/PropertyNode.cs | 2 +- .../ParseNodes/RootNode.cs | 2 +- .../ParseNodes/ValueNode.cs | 2 +- src/Microsoft.OpenApi.Readers/ParsingContext.cs | 2 +- .../Properties/AssemblyInfo.cs | 2 +- src/Microsoft.OpenApi.Readers/ReadResult.cs | 2 +- .../Services/DefaultStreamLoader.cs | 2 +- .../Services/OpenApiRemoteReferenceCollector.cs | 6 +++--- .../Services/OpenApiWorkspaceLoader.cs | 2 +- .../V2/OpenApiContactDeserializer.cs | 2 +- .../V2/OpenApiDocumentDeserializer.cs | 4 ++-- .../V2/OpenApiExternalDocsDeserializer.cs | 2 +- .../V2/OpenApiHeaderDeserializer.cs | 8 ++++---- .../V2/OpenApiInfoDeserializer.cs | 2 +- .../V2/OpenApiLicenseDeserializer.cs | 2 +- .../V2/OpenApiOperationDeserializer.cs | 2 +- .../V2/OpenApiParameterDeserializer.cs | 2 +- .../V2/OpenApiPathItemDeserializer.cs | 2 +- .../V2/OpenApiPathsDeserializer.cs | 2 +- .../V2/OpenApiResponseDeserializer.cs | 4 ++-- .../V2/OpenApiSchemaDeserializer.cs | 2 +- .../V2/OpenApiSecurityRequirementDeserializer.cs | 2 +- .../V2/OpenApiSecuritySchemeDeserializer.cs | 2 +- .../V2/OpenApiTagDeserializer.cs | 2 +- .../V2/OpenApiV2Deserializer.cs | 2 +- .../V2/OpenApiV2VersionService.cs | 2 +- .../V2/OpenApiXmlDeserializer.cs | 2 +- .../V2/TempStorageKeys.cs | 2 +- .../V3/OpenApiCallbackDeserializer.cs | 2 +- .../V3/OpenApiComponentsDeserializer.cs | 2 +- .../V3/OpenApiContactDeserializer.cs | 2 +- .../V3/OpenApiDiscriminatorDeserializer.cs | 2 +- .../V3/OpenApiDocumentDeserializer.cs | 2 +- .../V3/OpenApiEncodingDeserializer.cs | 2 +- .../V3/OpenApiExampleDeserializer.cs | 2 +- .../V3/OpenApiExternalDocsDeserializer.cs | 2 +- .../V3/OpenApiHeaderDeserializer.cs | 2 +- .../V3/OpenApiInfoDeserializer.cs | 2 +- .../V3/OpenApiLicenseDeserializer.cs | 2 +- .../V3/OpenApiLinkDeserializer.cs | 2 +- .../V3/OpenApiMediaTypeDeserializer.cs | 2 +- .../V3/OpenApiOAuthFlowDeserializer.cs | 2 +- .../V3/OpenApiOAuthFlowsDeserializer.cs | 2 +- .../V3/OpenApiOperationDeserializer.cs | 2 +- .../V3/OpenApiParameterDeserializer.cs | 2 +- .../V3/OpenApiPathItemDeserializer.cs | 6 +++--- .../V3/OpenApiPathsDeserializer.cs | 2 +- .../V3/OpenApiRequestBodyDeserializer.cs | 2 +- .../V3/OpenApiResponseDeserializer.cs | 2 +- .../V3/OpenApiResponsesDeserializer.cs | 2 +- .../V3/OpenApiSchemaDeserializer.cs | 4 ++-- .../V3/OpenApiSecurityRequirementDeserializer.cs | 2 +- .../V3/OpenApiSecuritySchemeDeserializer.cs | 2 +- .../V3/OpenApiServerDeserializer.cs | 2 +- .../V3/OpenApiServerVariableDeserializer.cs | 2 +- .../V3/OpenApiTagDeserializer.cs | 2 +- .../V3/OpenApiV3Deserializer.cs | 2 +- .../V3/OpenApiV3VersionService.cs | 4 ++-- .../V3/OpenApiXmlDeserializer.cs | 2 +- src/Microsoft.OpenApi.Readers/YamlHelper.cs | 2 +- src/Microsoft.OpenApi.Workbench/App.xaml.cs | 2 +- src/Microsoft.OpenApi.Workbench/MainModel.cs | 6 +++--- src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs | 2 +- .../Properties/AssemblyInfo.cs | 2 +- src/Microsoft.OpenApi.Workbench/StatsVisitor.cs | 2 +- src/Microsoft.OpenApi/Any/AnyType.cs | 2 +- src/Microsoft.OpenApi/Any/IOpenApiAny.cs | 2 +- src/Microsoft.OpenApi/Any/IOpenApiPrimitive.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiArray.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiBinary.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiBoolean.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiByte.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiDate.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiDateTime.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiDouble.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiFloat.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiInteger.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiLong.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiNull.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiObject.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiPassword.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiString.cs | 4 ++-- .../Attributes/DisplayAttribute.cs | 2 +- src/Microsoft.OpenApi/Error.cs | 2 +- .../Exceptions/OpenApiException.cs | 6 +++--- .../Exceptions/OpenApiWriterException.cs | 2 +- .../Expressions/BodyExpression.cs | 2 +- .../Expressions/CompositeExpression.cs | 2 +- .../Expressions/HeaderExpression.cs | 2 +- .../Expressions/MethodExpression.cs | 2 +- .../Expressions/PathExpression.cs | 2 +- .../Expressions/QueryExpression.cs | 2 +- .../Expressions/RequestExpression.cs | 2 +- .../Expressions/ResponseExpression.cs | 2 +- .../Expressions/RuntimeExpression.cs | 2 +- .../Expressions/SourceExpression.cs | 2 +- .../Expressions/StatusCodeExpression.cs | 2 +- src/Microsoft.OpenApi/Expressions/UrlExpression.cs | 2 +- src/Microsoft.OpenApi/Extensions/EnumExtensions.cs | 2 +- .../Extensions/OpenAPIWriterExtensions.cs | 2 +- .../Extensions/OpenApiElementExtensions.cs | 2 +- .../Extensions/OpenApiExtensibleExtensions.cs | 2 +- .../Extensions/OpenApiReferencableExtensions.cs | 2 +- .../Extensions/OpenApiSerializableExtensions.cs | 4 ++-- .../Extensions/OpenApiTypeMapper.cs | 6 +++--- src/Microsoft.OpenApi/Interfaces/IEffective.cs | 6 +++--- .../Interfaces/IOpenApiElement.cs | 2 +- .../Interfaces/IOpenApiExtensible.cs | 2 +- .../Interfaces/IOpenApiExtension.cs | 2 +- .../Interfaces/IOpenApiReferenceable.cs | 2 +- .../Interfaces/IOpenApiSerializable.cs | 2 +- src/Microsoft.OpenApi/JsonPointer.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiCallback.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiComponents.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiConstants.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiContact.cs | 2 +- .../Models/OpenApiDiscriminator.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 14 +++++++------- src/Microsoft.OpenApi/Models/OpenApiEncoding.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiError.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiExample.cs | 4 ++-- .../Models/OpenApiExtensibleDictionary.cs | 4 ++-- .../Models/OpenApiExternalDocs.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiLicense.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiMediaType.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiOperation.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 10 +++++----- src/Microsoft.OpenApi/Models/OpenApiPathItem.cs | 8 ++++---- src/Microsoft.OpenApi/Models/OpenApiPaths.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiReference.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs | 6 +++--- src/Microsoft.OpenApi/Models/OpenApiResponse.cs | 4 ++-- src/Microsoft.OpenApi/Models/OpenApiResponses.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 8 ++++---- .../Models/OpenApiSecurityRequirement.cs | 2 +- .../Models/OpenApiSecurityScheme.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 2 +- .../Models/OpenApiServerVariable.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiTag.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiXml.cs | 2 +- src/Microsoft.OpenApi/Models/OperationType.cs | 2 +- src/Microsoft.OpenApi/Models/ParameterLocation.cs | 2 +- src/Microsoft.OpenApi/Models/ParameterStyle.cs | 2 +- src/Microsoft.OpenApi/Models/ReferenceType.cs | 2 +- .../Models/RuntimeExpressionAnyWrapper.cs | 2 +- src/Microsoft.OpenApi/Models/SecuritySchemeType.cs | 2 +- src/Microsoft.OpenApi/OpenApiFormat.cs | 2 +- src/Microsoft.OpenApi/OpenApiSpecVersion.cs | 4 ++-- src/Microsoft.OpenApi/Properties/AssemblyInfo.cs | 2 +- .../Services/OpenApiReferenceError.cs | 2 +- .../Services/OpenApiReferenceResolver.cs | 2 +- .../Services/OpenApiUrlTreeNode.cs | 4 ++-- .../Services/OpenApiVisitorBase.cs | 4 ++-- src/Microsoft.OpenApi/Services/OpenApiWalker.cs | 4 ++-- src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs | 8 ++++---- .../Validations/IValidationContext.cs | 4 ++-- .../Validations/OpenApiValidatiorWarning.cs | 2 +- .../Validations/OpenApiValidator.cs | 4 ++-- .../Validations/OpenApiValidatorError.cs | 2 +- .../Validations/Rules/OpenApiComponentsRules.cs | 2 +- .../Validations/Rules/OpenApiContactRules.cs | 2 +- .../Validations/Rules/OpenApiDocumentRules.cs | 2 +- .../Validations/Rules/OpenApiExtensionRules.cs | 2 +- .../Validations/Rules/OpenApiExternalDocsRules.cs | 2 +- .../Validations/Rules/OpenApiHeaderRules.cs | 2 +- .../Validations/Rules/OpenApiInfoRules.cs | 2 +- .../Validations/Rules/OpenApiLicenseRules.cs | 2 +- .../Validations/Rules/OpenApiMediaTypeRules.cs | 2 +- .../Validations/Rules/OpenApiOAuthFlowRules.cs | 2 +- .../Validations/Rules/OpenApiParameterRules.cs | 6 +++--- .../Validations/Rules/OpenApiPathsRules.cs | 2 +- .../Validations/Rules/OpenApiResponseRules.cs | 2 +- .../Validations/Rules/OpenApiResponsesRules.cs | 2 +- .../Validations/Rules/OpenApiSchemaRules.cs | 2 +- .../Validations/Rules/OpenApiServerRules.cs | 2 +- .../Validations/Rules/OpenApiTagRules.cs | 2 +- .../Validations/Rules/RuleHelpers.cs | 2 +- .../Validations/ValidationExtensions.cs | 2 +- .../Validations/ValidationRule.cs | 2 +- .../Validations/ValidationRuleSet.cs | 2 +- .../Writers/FormattingStreamWriter.cs | 2 +- src/Microsoft.OpenApi/Writers/IOpenApiWriter.cs | 2 +- src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs | 2 +- .../Writers/OpenApiWriterAnyExtensions.cs | 2 +- src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs | 6 +++--- .../Writers/OpenApiWriterExtensions.cs | 2 +- .../Writers/OpenApiWriterSettings.cs | 4 ++-- src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs | 8 ++++---- src/Microsoft.OpenApi/Writers/Scope.cs | 2 +- .../Writers/SpecialCharacterStringExtensions.cs | 8 ++++---- src/Microsoft.OpenApi/Writers/WriterConstants.cs | 2 +- .../UtilityFiles/OpenApiDocumentMock.cs | 2 +- .../DefaultSettingsFixture.cs | 2 +- .../DefaultSettingsFixtureCollection.cs | 2 +- .../OpenApiReaderTests/OpenApiDiagnosticTests.cs | 2 +- .../UnsupportedSpecVersionTests.cs | 2 +- .../OpenApiWorkspaceStreamTests.cs | 2 +- .../ParseNodeTests.cs | 2 +- .../ParseNodes/OpenApiAnyConverterTests.cs | 2 +- .../ParseNodes/OpenApiAnyTests.cs | 2 +- .../Properties/AssemblyInfo.cs | 2 +- .../ConvertToOpenApiReferenceV2Tests.cs | 2 +- .../ConvertToOpenApiReferenceV3Tests.cs | 2 +- .../ReferenceService/TryLoadReferenceV2Tests.cs | 2 +- .../TestCustomExtension.cs | 2 +- test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs | 2 +- .../V2Tests/ComparisonTests.cs | 2 +- .../V2Tests/OpenApiContactTests.cs | 2 +- .../V2Tests/OpenApiDocumentTests.cs | 2 +- .../V2Tests/OpenApiHeaderTests.cs | 2 +- .../V2Tests/OpenApiOperationTests.cs | 2 +- .../V2Tests/OpenApiParameterTests.cs | 2 +- .../V2Tests/OpenApiPathItemTests.cs | 2 +- .../V2Tests/OpenApiSchemaTests.cs | 2 +- .../V2Tests/OpenApiSecuritySchemeTests.cs | 2 +- .../V3Tests/OpenApiCallbackTests.cs | 2 +- .../V3Tests/OpenApiContactTests.cs | 2 +- .../V3Tests/OpenApiDiscriminatorTests.cs | 2 +- .../V3Tests/OpenApiDocumentTests.cs | 2 +- .../V3Tests/OpenApiEncodingTests.cs | 2 +- .../V3Tests/OpenApiExampleTests.cs | 2 +- .../V3Tests/OpenApiInfoTests.cs | 2 +- .../V3Tests/OpenApiMediaTypeTests.cs | 2 +- .../V3Tests/OpenApiOperationTests.cs | 2 +- .../V3Tests/OpenApiParameterTests.cs | 2 +- .../V3Tests/OpenApiSchemaTests.cs | 2 +- .../V3Tests/OpenApiSecuritySchemeTests.cs | 2 +- .../V3Tests/OpenApiXmlTests.cs | 2 +- test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs | 2 +- .../DefaultSettingsFixture.cs | 2 +- .../DefaultSettingsFixtureCollection.cs | 2 +- .../Extensions/OpenApiTypeMapperTests.cs | 4 ++-- .../Models/OpenApiCallbackTests.cs | 2 +- .../Models/OpenApiComponentsTests.cs | 2 +- .../Models/OpenApiContactTests.cs | 2 +- .../Models/OpenApiDocumentTests.cs | 10 +++++----- .../Models/OpenApiEncodingTests.cs | 2 +- .../Models/OpenApiExampleTests.cs | 2 +- .../Models/OpenApiExternalDocsTests.cs | 2 +- .../Models/OpenApiHeaderTests.cs | 2 +- .../Models/OpenApiInfoTests.cs | 2 +- .../Models/OpenApiLicenseTests.cs | 2 +- .../Models/OpenApiLinkTests.cs | 2 +- .../Models/OpenApiMediaTypeTests.cs | 2 +- .../Models/OpenApiOAuthFlowTests.cs | 2 +- .../Models/OpenApiOAuthFlowsTests.cs | 2 +- .../Models/OpenApiOperationTests.cs | 2 +- .../Models/OpenApiParameterTests.cs | 4 ++-- .../Models/OpenApiReferenceTests.cs | 2 +- .../Models/OpenApiRequestBodyTests.cs | 2 +- .../Models/OpenApiResponseTests.cs | 2 +- .../Models/OpenApiSchemaTests.cs | 4 ++-- .../Models/OpenApiSecurityRequirementTests.cs | 2 +- .../Models/OpenApiSecuritySchemeTests.cs | 6 +++--- .../Models/OpenApiServerTests.cs | 2 +- .../Models/OpenApiServerVariableTests.cs | 2 +- .../Models/OpenApiTagTests.cs | 2 +- .../Models/OpenApiXmlTests.cs | 2 +- .../Properties/AssemblyInfo.cs | 2 +- .../Services/OpenApiValidatorTests.cs | 2 +- test/Microsoft.OpenApi.Tests/StringExtensions.cs | 2 +- .../OpenApiComponentsValidationTests.cs | 2 +- .../Validations/OpenApiContactValidationTests.cs | 2 +- .../OpenApiExternalDocsValidationTests.cs | 2 +- .../Validations/OpenApiHeaderValidationTests.cs | 2 +- .../Validations/OpenApiInfoValidationTests.cs | 2 +- .../Validations/OpenApiLicenseValidationTests.cs | 2 +- .../Validations/OpenApiMediaTypeValidationTests.cs | 2 +- .../Validations/OpenApiOAuthFlowValidationTests.cs | 2 +- .../Validations/OpenApiParameterValidationTests.cs | 2 +- .../Validations/OpenApiReferenceValidationTests.cs | 2 +- .../Validations/OpenApiResponseValidationTests.cs | 2 +- .../Validations/OpenApiSchemaValidationTests.cs | 6 +++--- .../Validations/OpenApiServerValidationTests.cs | 2 +- .../Validations/OpenApiTagValidationTests.cs | 2 +- .../Walkers/WalkerLocationTests.cs | 2 +- .../Workspaces/OpenApiReferencableTests.cs | 2 +- .../Writers/OpenApiJsonWriterTests.cs | 2 +- .../Writers/OpenApiWriterAnyExtensionsTests.cs | 4 ++-- .../Writers/OpenApiWriterSpecialCharacterTests.cs | 2 +- .../Writers/OpenApiYamlWriterTests.cs | 2 +- 320 files changed, 415 insertions(+), 415 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Extensions/CommandExtensions.cs b/src/Microsoft.OpenApi.Hidi/Extensions/CommandExtensions.cs index 9d5077432..5b83212d5 100644 --- a/src/Microsoft.OpenApi.Hidi/Extensions/CommandExtensions.cs +++ b/src/Microsoft.OpenApi.Hidi/Extensions/CommandExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.CommandLine; diff --git a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs index 4db55a05e..260119188 100644 --- a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs +++ b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs @@ -24,7 +24,7 @@ static PowerShellFormatter() { // Add singularization exclusions. // Enhancement: Read exclusions from a user provided file. - Vocabularies.Default.AddSingular("(drive)s$", "$1"); // drives does not properly singularize to drive. + Vocabularies.Default.AddSingular("(drive)s$", "$1"); // drives does not properly singularize to drive. Vocabularies.Default.AddSingular("(data)$", "$1"); // exclude the following from singularization. Vocabularies.Default.AddSingular("(delta)$", "$1"); Vocabularies.Default.AddSingular("(quota)$", "$1"); diff --git a/src/Microsoft.OpenApi.Hidi/Logger.cs b/src/Microsoft.OpenApi.Hidi/Logger.cs index 717ca1a41..dec4a5f8e 100644 --- a/src/Microsoft.OpenApi.Hidi/Logger.cs +++ b/src/Microsoft.OpenApi.Hidi/Logger.cs @@ -21,7 +21,7 @@ public static ILoggerFactory ConfigureLogger(LogLevel logLevel) { c.IncludeScopes = true; }) -#if DEBUG +#if DEBUG .AddDebug() #endif .SetMinimumLevel(logLevel); diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index d698bd5b2..fc70d409b 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -154,7 +154,7 @@ private static OpenApiDocument ApplyFilters(HidiOptions options, ILogger logger, requestUrls = EnumerateJsonDocument(postmanCollection.RootElement, new()); logger.LogTrace("Finished fetching the list of paths and Http methods defined in the Postman collection."); } - else + else { requestUrls = new(); logger.LogTrace("No filter options provided."); @@ -211,7 +211,7 @@ private static void WriteOpenApi(HidiOptions options, OpenApiFormat openApiForma } } - // Get OpenAPI document either from OpenAPI or CSDL + // Get OpenAPI document either from OpenAPI or CSDL private static async Task GetOpenApi(HidiOptions options, ILogger logger, CancellationToken cancellationToken, string? metadataVersion = null) { @@ -285,7 +285,7 @@ private static async Task GetOpenApi(HidiOptions options, ILogg private static Dictionary> GetRequestUrlsFromManifest(ApiDependency apiDependency) { - // Get the request URLs from the API Dependencies in the API manifest + // Get the request URLs from the API Dependencies in the API manifest var requests = apiDependency .Requests.Where(static r => !r.Exclude && !string.IsNullOrEmpty(r.UriTemplate) && !string.IsNullOrEmpty(r.Method)) .Select(static r => new { UriTemplate = r.UriTemplate!, Method = r.Method! }) diff --git a/src/Microsoft.OpenApi.Hidi/Options/FilterOptions.cs b/src/Microsoft.OpenApi.Hidi/Options/FilterOptions.cs index d82a064f7..1abf5a6bf 100644 --- a/src/Microsoft.OpenApi.Hidi/Options/FilterOptions.cs +++ b/src/Microsoft.OpenApi.Hidi/Options/FilterOptions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Hidi.Options { @@ -8,6 +8,6 @@ internal class FilterOptions public string? FilterByOperationIds { get; internal set; } public string? FilterByTags { get; internal set; } public string? FilterByCollection { get; internal set; } - public string? FilterByApiManifest { get; internal set; } + public string? FilterByApiManifest { get; internal set; } } } diff --git a/src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs b/src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs index 9f5a109f7..9b12b73f3 100644 --- a/src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs +++ b/src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.CommandLine.Parsing; using System.IO; diff --git a/src/Microsoft.OpenApi.Hidi/StatsVisitor.cs b/src/Microsoft.OpenApi.Hidi/StatsVisitor.cs index 871f88dca..b6af07778 100644 --- a/src/Microsoft.OpenApi.Hidi/StatsVisitor.cs +++ b/src/Microsoft.OpenApi.Hidi/StatsVisitor.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs b/src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs index 6264270a6..6ec32f488 100644 --- a/src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs +++ b/src/Microsoft.OpenApi.Hidi/Utilities/SettingsUtilities.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.Extensions.Configuration; using Microsoft.OpenApi.OData; diff --git a/src/Microsoft.OpenApi.Readers/Exceptions/OpenApiReaderException.cs b/src/Microsoft.OpenApi.Readers/Exceptions/OpenApiReaderException.cs index e90137ad3..36db10127 100644 --- a/src/Microsoft.OpenApi.Readers/Exceptions/OpenApiReaderException.cs +++ b/src/Microsoft.OpenApi.Readers/Exceptions/OpenApiReaderException.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Exceptions; diff --git a/src/Microsoft.OpenApi.Readers/Exceptions/OpenApiUnsupportedSpecVersionException.cs b/src/Microsoft.OpenApi.Readers/Exceptions/OpenApiUnsupportedSpecVersionException.cs index 705b212d0..2d125c259 100644 --- a/src/Microsoft.OpenApi.Readers/Exceptions/OpenApiUnsupportedSpecVersionException.cs +++ b/src/Microsoft.OpenApi.Readers/Exceptions/OpenApiUnsupportedSpecVersionException.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Globalization; diff --git a/src/Microsoft.OpenApi.Readers/Interface/IDiagnostic.cs b/src/Microsoft.OpenApi.Readers/Interface/IDiagnostic.cs index da3381f7e..65511ce11 100644 --- a/src/Microsoft.OpenApi.Readers/Interface/IDiagnostic.cs +++ b/src/Microsoft.OpenApi.Readers/Interface/IDiagnostic.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Readers.Interface { diff --git a/src/Microsoft.OpenApi.Readers/Interface/IOpenApiReader.cs b/src/Microsoft.OpenApi.Readers/Interface/IOpenApiReader.cs index 39724b3c6..8991c9b59 100644 --- a/src/Microsoft.OpenApi.Readers/Interface/IOpenApiReader.cs +++ b/src/Microsoft.OpenApi.Readers/Interface/IOpenApiReader.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/Interface/IOpenApiVersionService.cs b/src/Microsoft.OpenApi.Readers/Interface/IOpenApiVersionService.cs index a7a98d781..a3b3c7fa5 100644 --- a/src/Microsoft.OpenApi.Readers/Interface/IOpenApiVersionService.cs +++ b/src/Microsoft.OpenApi.Readers/Interface/IOpenApiVersionService.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs b/src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs index b93c69f39..b3c0c4613 100644 --- a/src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.IO; diff --git a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs index 0ffac77e7..1c70db887 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs index 25bcbca6f..71a18e137 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs @@ -80,7 +80,7 @@ public class OpenApiReaderSettings /// from an object. /// public bool LeaveStreamOpen { get; set; } - + /// /// Adds parsers for Microsoft OpenAPI extensions: /// - @@ -93,17 +93,17 @@ public class OpenApiReaderSettings /// public void AddMicrosoftExtensionParsers() { - if (!ExtensionParsers.ContainsKey(OpenApiPagingExtension.Name)) + if (!ExtensionParsers.ContainsKey(OpenApiPagingExtension.Name)) ExtensionParsers.Add(OpenApiPagingExtension.Name, static (i, _) => OpenApiPagingExtension.Parse(i)); - if (!ExtensionParsers.ContainsKey(OpenApiEnumValuesDescriptionExtension.Name)) + if (!ExtensionParsers.ContainsKey(OpenApiEnumValuesDescriptionExtension.Name)) ExtensionParsers.Add(OpenApiEnumValuesDescriptionExtension.Name, static (i, _ ) => OpenApiEnumValuesDescriptionExtension.Parse(i)); - if (!ExtensionParsers.ContainsKey(OpenApiPrimaryErrorMessageExtension.Name)) + if (!ExtensionParsers.ContainsKey(OpenApiPrimaryErrorMessageExtension.Name)) ExtensionParsers.Add(OpenApiPrimaryErrorMessageExtension.Name, static (i, _ ) => OpenApiPrimaryErrorMessageExtension.Parse(i)); - if (!ExtensionParsers.ContainsKey(OpenApiDeprecationExtension.Name)) + if (!ExtensionParsers.ContainsKey(OpenApiDeprecationExtension.Name)) ExtensionParsers.Add(OpenApiDeprecationExtension.Name, static (i, _ ) => OpenApiDeprecationExtension.Parse(i)); - if (!ExtensionParsers.ContainsKey(OpenApiReservedParameterExtension.Name)) + if (!ExtensionParsers.ContainsKey(OpenApiReservedParameterExtension.Name)) ExtensionParsers.Add(OpenApiReservedParameterExtension.Name, static (i, _ ) => OpenApiReservedParameterExtension.Parse(i)); - if (!ExtensionParsers.ContainsKey(OpenApiEnumFlagsExtension.Name)) + if (!ExtensionParsers.ContainsKey(OpenApiEnumFlagsExtension.Name)) ExtensionParsers.Add(OpenApiEnumFlagsExtension.Name, static (i, _ ) => OpenApiEnumFlagsExtension.Parse(i)); } } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs index 0cb9605dd..0d2dbd241 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs index d6722d440..74566fd58 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 5537366d0..4f9dee12c 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyFieldMap.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyFieldMap.cs index a135f7f02..479417bdb 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyFieldMap.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyFieldMap.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyFieldMapParameter.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyFieldMapParameter.cs index 30aa0dbca..515a6e174 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyFieldMapParameter.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyFieldMapParameter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyListFieldMap.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyListFieldMap.cs index dbc9eabeb..dcec81bb6 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyListFieldMap.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyListFieldMap.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyListFieldMapParameter.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyListFieldMapParameter.cs index cfa1c3702..aed34cf60 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyListFieldMapParameter.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyListFieldMapParameter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMap.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMap.cs index abd4f4466..e6b2a7b08 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMap.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMap.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMapParameter.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMapParameter.cs index 1aa899978..49fc65dcb 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMapParameter.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/AnyMapFieldMapParameter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/FixedFieldMap.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/FixedFieldMap.cs index 50cc5e4b7..4364cf1df 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/FixedFieldMap.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/FixedFieldMap.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/JsonPointerExtensions.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/JsonPointerExtensions.cs index d30863955..39e53933a 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/JsonPointerExtensions.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/JsonPointerExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using SharpYaml.Serialization; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs index d11ff4c04..bbc9e30b8 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs index 92c49726b..ee92938c4 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections; @@ -67,7 +67,7 @@ public override Dictionary CreateMap(Func map) var nodes = yamlMap.Select( n => { - + var key = n.Key.GetScalarValue(); T value; try @@ -76,7 +76,7 @@ public override Dictionary CreateMap(Func map) value = n.Value as YamlMappingNode == null ? default(T) : map(new MapNode(Context, n.Value as YamlMappingNode)); - } + } finally { Context.EndObject(); @@ -93,7 +93,7 @@ public override Dictionary CreateMap(Func map) public override Dictionary CreateMapWithReference( ReferenceType referenceType, - Func map) + Func map) { var yamlMap = _node; if (yamlMap == null) @@ -141,7 +141,7 @@ public override Dictionary CreateSimpleMap(Func map) { var yamlMap = _node; if (yamlMap == null) - { + { throw new OpenApiReaderException($"Expected map while parsing {typeof(T).Name}", Context); } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs index 01aef7652..f17cf251c 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/OpenApiAnyConverter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Globalization; @@ -260,7 +260,7 @@ public static IOpenApiAny GetSpecificOpenApiAny(IOpenApiAny openApiAny, OpenApiS } // If data conflicts with the given type, return a string. - // This converter is used in the parser, so it does not perform any validations, + // This converter is used in the parser, so it does not perform any validations, // but the validator can be used to validate whether the data and given type conflicts. return openApiAny; } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs index 295b02bf3..174f5a2cf 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ParseNode.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/PatternFieldMap.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/PatternFieldMap.cs index bbd153688..8fb28bc5e 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/PatternFieldMap.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/PatternFieldMap.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs index 2dd2c7e8a..b53c1d405 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/RootNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/RootNode.cs index 42909bee6..d9f18603f 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/RootNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/RootNode.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using SharpYaml.Serialization; diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs index bbce7a7d3..8b4de6c1a 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ValueNode.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Readers.Exceptions; diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index afc76bcf5..ffef15904 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/Properties/AssemblyInfo.cs b/src/Microsoft.OpenApi.Readers/Properties/AssemblyInfo.cs index b42e91bd1..554e1aad8 100644 --- a/src/Microsoft.OpenApi.Readers/Properties/AssemblyInfo.cs +++ b/src/Microsoft.OpenApi.Readers/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Runtime.CompilerServices; diff --git a/src/Microsoft.OpenApi.Readers/ReadResult.cs b/src/Microsoft.OpenApi.Readers/ReadResult.cs index 7479d345f..b1ddcb712 100644 --- a/src/Microsoft.OpenApi.Readers/ReadResult.cs +++ b/src/Microsoft.OpenApi.Readers/ReadResult.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs b/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs index 09f16632b..10d8d1d93 100644 --- a/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.IO; diff --git a/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs b/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs index 9a5ba9213..d7ee0ca13 100644 --- a/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs +++ b/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Interfaces; @@ -31,7 +31,7 @@ public IEnumerable References } /// - /// Collect reference for each reference + /// Collect reference for each reference /// /// public override void Visit(IOpenApiReferenceable referenceable) @@ -54,6 +54,6 @@ private void AddReference(OpenApiReference reference) } } } - } + } } } diff --git a/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs b/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs index 79f6206d0..b98982f8c 100644 --- a/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Readers.Services { - internal class OpenApiWorkspaceLoader + internal class OpenApiWorkspaceLoader { private OpenApiWorkspace _workspace; private IStreamLoader _loader; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs index 99bc4451a..c25f5d0c8 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 806c96877..4e4f000d6 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -300,7 +300,7 @@ private static void FixRequestBodyReferences(OpenApiDocument doc) private static bool IsHostValid(string host) { - //Check if the host contains :// + //Check if the host contains :// if (host.Contains(Uri.SchemeDelimiter)) { return false; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs index eea726777..b773fd784 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs index 5d6cc2ff3..821e08a26 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Globalization; @@ -140,10 +140,10 @@ internal static partial class OpenApiV2Deserializer OpenApiConstants.Default, new AnyFieldMapParameter( p => p.Schema?.Default, - (p, v) => + (p, v) => { if(p.Schema == null) return; - p.Schema.Default = v; + p.Schema.Default = v; }, p => p.Schema) } @@ -159,7 +159,7 @@ internal static partial class OpenApiV2Deserializer (p, v) => { if(p.Schema == null) return; - p.Schema.Enum = v; + p.Schema.Enum = v; }, p => p.Schema) }, diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs index 5854672d3..0da2034ec 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs index 4c4009f57..6a7445e73 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index cf54df8c3..e2be3ea6a 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs index 5be08c71e..aea3b62df 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index d9db5a8d8..5b6222e27 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathsDeserializer.cs index 2aa5de979..611eee485 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathsDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs index 182def419..0f340c947 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Extensions; @@ -81,7 +81,7 @@ private static void ProcessProduces(MapNode mapNode, OpenApiResponse response, P foreach (var produce in produces) { - if (response.Content.TryGetValue(produce, out var produceValue)) + if (response.Content.TryGetValue(produce, out var produceValue)) { if (schema != null) { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs index 0878eda9a..2a0c71a72 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Globalization; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs index c8384fb05..5197b6e1e 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs index b2aab773c..20de9c880 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs index 12fae8660..ecd6c96c3 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2Deserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2Deserializer.cs index c3f26b896..6b7aea308 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2Deserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2Deserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index 54b0a3776..cc59aebcb 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs index ac7db2db6..47a321dbe 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Exceptions; diff --git a/src/Microsoft.OpenApi.Readers/V2/TempStorageKeys.cs b/src/Microsoft.OpenApi.Readers/V2/TempStorageKeys.cs index 5a216e086..c7b96f6ce 100644 --- a/src/Microsoft.OpenApi.Readers/V2/TempStorageKeys.cs +++ b/src/Microsoft.OpenApi.Readers/V2/TempStorageKeys.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Readers.V2 { diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiCallbackDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiCallbackDeserializer.cs index af1376580..c400e8b5b 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiCallbackDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiCallbackDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Expressions; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs index 30d711d33..91ad2bcd8 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs index 151a12354..2dfddfb3b 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs index 867057d32..ec3267883 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs index d5c437148..b010f1e41 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs index fc2f990e7..d6d7a8844 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs index 1e114ad73..264a1f8cc 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs index 920b84192..1ea16f616 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs index 1616d67f0..f7cd90aca 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs index d5de92852..8ccbf6d69 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs index 3c38d8b9a..6a27b1286 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs index 7bf4c650b..9eae96b72 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs index c8bd3d240..68b6a4895 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs index 2653ce631..1679cdf75 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs index bd19f2716..9269048aa 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs index d6cd2e387..dee61cef6 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs index e8fad07a5..c291132ca 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Linq; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs index 698fe64cc..8e97e1377 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; @@ -15,12 +15,12 @@ internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _pathItemFixedFields = new FixedFieldMap { - + { "$ref", (o,n) => { o.Reference = new OpenApiReference { ExternalResource = n.GetScalarValue() }; o.UnresolvedReference =true; - } + } }, { "summary", (o, n) => diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathsDeserializer.cs index fcfad096c..5b0b9485b 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathsDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs index a2633028e..c5c2fab91 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs index 70ea0c9bf..73f20791a 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponsesDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponsesDeserializer.cs index 9fe4d075f..597e8a4b6 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponsesDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponsesDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs index e5482e22f..993195709 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; @@ -27,7 +27,7 @@ internal static partial class OpenApiV3Deserializer { "multipleOf", (o, n) => { - o.MultipleOf = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture); + o.MultipleOf = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture); } }, { diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs index ed8322622..4a609125e 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs index dd6ad4751..a5f50eb3f 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs index e278abc90..81e92b979 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs index 9b6acbc8d..fa4d07d72 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs index 6a987969b..9de8bf610 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3Deserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3Deserializer.cs index 9689c8fe1..ac3463167 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3Deserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3Deserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 60ce71c8a..a6cb41970 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -121,7 +121,7 @@ public OpenApiReference ConvertToOpenApiReference( if (type == null) { type = referencedType; - } + } else { if (type != referencedType) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs index dc05da1c2..95cc2a585 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi.Readers/YamlHelper.cs b/src/Microsoft.OpenApi.Readers/YamlHelper.cs index 90794b080..7b78e968e 100644 --- a/src/Microsoft.OpenApi.Readers/YamlHelper.cs +++ b/src/Microsoft.OpenApi.Readers/YamlHelper.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/src/Microsoft.OpenApi.Workbench/App.xaml.cs b/src/Microsoft.OpenApi.Workbench/App.xaml.cs index d3fc6dcb7..de1f426f5 100644 --- a/src/Microsoft.OpenApi.Workbench/App.xaml.cs +++ b/src/Microsoft.OpenApi.Workbench/App.xaml.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Windows; diff --git a/src/Microsoft.OpenApi.Workbench/MainModel.cs b/src/Microsoft.OpenApi.Workbench/MainModel.cs index 0d0d689ec..cd1461462 100644 --- a/src/Microsoft.OpenApi.Workbench/MainModel.cs +++ b/src/Microsoft.OpenApi.Workbench/MainModel.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.ComponentModel; @@ -40,7 +40,7 @@ public class MainModel : INotifyPropertyChanged private string _renderTime; - + /// /// Default format. /// @@ -215,7 +215,7 @@ internal async Task ParseDocument() if (_inputFile.StartsWith("http")) { stream = await _httpClient.GetStreamAsync(_inputFile); - } + } else { stream = new FileStream(_inputFile, FileMode.Open); diff --git a/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs b/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs index 08bbb177d..0d2f74582 100644 --- a/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs +++ b/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Windows; diff --git a/src/Microsoft.OpenApi.Workbench/Properties/AssemblyInfo.cs b/src/Microsoft.OpenApi.Workbench/Properties/AssemblyInfo.cs index b9a41106f..0add485f6 100644 --- a/src/Microsoft.OpenApi.Workbench/Properties/AssemblyInfo.cs +++ b/src/Microsoft.OpenApi.Workbench/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Reflection; using System.Runtime.InteropServices; diff --git a/src/Microsoft.OpenApi.Workbench/StatsVisitor.cs b/src/Microsoft.OpenApi.Workbench/StatsVisitor.cs index 85faef630..226b873d3 100644 --- a/src/Microsoft.OpenApi.Workbench/StatsVisitor.cs +++ b/src/Microsoft.OpenApi.Workbench/StatsVisitor.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Any/AnyType.cs b/src/Microsoft.OpenApi/Any/AnyType.cs index d0addd808..3ac617e8a 100644 --- a/src/Microsoft.OpenApi/Any/AnyType.cs +++ b/src/Microsoft.OpenApi/Any/AnyType.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/IOpenApiAny.cs b/src/Microsoft.OpenApi/Any/IOpenApiAny.cs index 26c5f4d87..ece675508 100644 --- a/src/Microsoft.OpenApi/Any/IOpenApiAny.cs +++ b/src/Microsoft.OpenApi/Any/IOpenApiAny.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi/Any/IOpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/IOpenApiPrimitive.cs index 0e286d1a4..039782852 100644 --- a/src/Microsoft.OpenApi/Any/IOpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/IOpenApiPrimitive.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs index e34fb8cbf..5cfded2b6 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs @@ -27,7 +27,7 @@ public static IOpenApiAny CloneFromCopyConstructor(IOpenApiAny obj) { return (IOpenApiAny)ci.Invoke(new object[] { obj }); } - } + } } return obj; diff --git a/src/Microsoft.OpenApi/Any/OpenApiArray.cs b/src/Microsoft.OpenApi/Any/OpenApiArray.cs index 2c877d631..1a4edf3bb 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiArray.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiArray.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Writers; using System; diff --git a/src/Microsoft.OpenApi/Any/OpenApiBinary.cs b/src/Microsoft.OpenApi/Any/OpenApiBinary.cs index da1bedad8..9933159a1 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiBinary.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiBinary.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiBoolean.cs b/src/Microsoft.OpenApi/Any/OpenApiBoolean.cs index f531e0135..10595f606 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiBoolean.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiBoolean.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiByte.cs b/src/Microsoft.OpenApi/Any/OpenApiByte.cs index 5e91b888e..48e9708d8 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiByte.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiByte.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiDate.cs b/src/Microsoft.OpenApi/Any/OpenApiDate.cs index c285799b6..485029133 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiDate.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiDate.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; diff --git a/src/Microsoft.OpenApi/Any/OpenApiDateTime.cs b/src/Microsoft.OpenApi/Any/OpenApiDateTime.cs index 81b647288..5fdaacf7c 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiDateTime.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiDateTime.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; diff --git a/src/Microsoft.OpenApi/Any/OpenApiDouble.cs b/src/Microsoft.OpenApi/Any/OpenApiDouble.cs index 35711a191..f1adb6799 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiDouble.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiDouble.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiFloat.cs b/src/Microsoft.OpenApi/Any/OpenApiFloat.cs index 3a64fb04c..e9b810331 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiFloat.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiFloat.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiInteger.cs b/src/Microsoft.OpenApi/Any/OpenApiInteger.cs index a0aa88fe8..7f7a32253 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiInteger.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiInteger.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiLong.cs b/src/Microsoft.OpenApi/Any/OpenApiLong.cs index 30b42fbf3..4168b91bd 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiLong.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiLong.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiNull.cs b/src/Microsoft.OpenApi/Any/OpenApiNull.cs index f1772c3e4..b606d98e1 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiNull.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiNull.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Any/OpenApiObject.cs b/src/Microsoft.OpenApi/Any/OpenApiObject.cs index d7e56e341..c33cbb1c0 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiObject.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiObject.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Any/OpenApiPassword.cs b/src/Microsoft.OpenApi/Any/OpenApiPassword.cs index aaa56e72b..dab7e7979 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPassword.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPassword.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { diff --git a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs index b8dcf097d..11c92ce96 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Text; diff --git a/src/Microsoft.OpenApi/Any/OpenApiString.cs b/src/Microsoft.OpenApi/Any/OpenApiString.cs index a899bd301..c71cbb840 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiString.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiString.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Any { @@ -19,7 +19,7 @@ public OpenApiString(string value) : this(value, false) { } - + /// /// Initializes the class. /// diff --git a/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs b/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs index db60448ea..a77b914cf 100644 --- a/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs +++ b/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; diff --git a/src/Microsoft.OpenApi/Error.cs b/src/Microsoft.OpenApi/Error.cs index d0c41780d..9ad76ce54 100644 --- a/src/Microsoft.OpenApi/Error.cs +++ b/src/Microsoft.OpenApi/Error.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Globalization; diff --git a/src/Microsoft.OpenApi/Exceptions/OpenApiException.cs b/src/Microsoft.OpenApi/Exceptions/OpenApiException.cs index cc6fc9d46..71404d1e0 100644 --- a/src/Microsoft.OpenApi/Exceptions/OpenApiException.cs +++ b/src/Microsoft.OpenApi/Exceptions/OpenApiException.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Properties; @@ -40,10 +40,10 @@ public OpenApiException(string message, Exception innerException) /// /// The reference pointer. This is a fragment identifier used to point to where the error occurred in the document. - /// If the document has been parsed as JSON/YAML then the identifier will be a + /// If the document has been parsed as JSON/YAML then the identifier will be a /// JSON Pointer as per https://tools.ietf.org/html/rfc6901 /// If the document fails to parse as JSON/YAML then the fragment will be based on - /// a text/plain pointer as defined in https://tools.ietf.org/html/rfc5147 + /// a text/plain pointer as defined in https://tools.ietf.org/html/rfc5147 /// Currently only line= is provided because using char= causes tests to break due to CR/LF and LF differences /// public string Pointer { get; set; } diff --git a/src/Microsoft.OpenApi/Exceptions/OpenApiWriterException.cs b/src/Microsoft.OpenApi/Exceptions/OpenApiWriterException.cs index 494608b1f..9e0540c53 100644 --- a/src/Microsoft.OpenApi/Exceptions/OpenApiWriterException.cs +++ b/src/Microsoft.OpenApi/Exceptions/OpenApiWriterException.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Properties; diff --git a/src/Microsoft.OpenApi/Expressions/BodyExpression.cs b/src/Microsoft.OpenApi/Expressions/BodyExpression.cs index cd5c86bd9..92344dbf7 100644 --- a/src/Microsoft.OpenApi/Expressions/BodyExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/BodyExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs b/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs index 7d5e32c7d..98c5e069c 100644 --- a/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs b/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs index f6642cb08..4bb53f94c 100644 --- a/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Expressions/MethodExpression.cs b/src/Microsoft.OpenApi/Expressions/MethodExpression.cs index 865d9c7ff..13173f7e2 100644 --- a/src/Microsoft.OpenApi/Expressions/MethodExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/MethodExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Expressions/PathExpression.cs b/src/Microsoft.OpenApi/Expressions/PathExpression.cs index a92c8a569..85ec5baac 100644 --- a/src/Microsoft.OpenApi/Expressions/PathExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/PathExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Expressions/QueryExpression.cs b/src/Microsoft.OpenApi/Expressions/QueryExpression.cs index 3277233b3..53e86d4ba 100644 --- a/src/Microsoft.OpenApi/Expressions/QueryExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/QueryExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Expressions/RequestExpression.cs b/src/Microsoft.OpenApi/Expressions/RequestExpression.cs index 7ebf77471..4aa923b8c 100644 --- a/src/Microsoft.OpenApi/Expressions/RequestExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/RequestExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Expressions/ResponseExpression.cs b/src/Microsoft.OpenApi/Expressions/ResponseExpression.cs index b91370297..212282f2d 100644 --- a/src/Microsoft.OpenApi/Expressions/ResponseExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/ResponseExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Expressions/RuntimeExpression.cs b/src/Microsoft.OpenApi/Expressions/RuntimeExpression.cs index 965572dfd..d4a116943 100644 --- a/src/Microsoft.OpenApi/Expressions/RuntimeExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/RuntimeExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Exceptions; diff --git a/src/Microsoft.OpenApi/Expressions/SourceExpression.cs b/src/Microsoft.OpenApi/Expressions/SourceExpression.cs index 3bc642473..2e55ece90 100644 --- a/src/Microsoft.OpenApi/Expressions/SourceExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/SourceExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Properties; diff --git a/src/Microsoft.OpenApi/Expressions/StatusCodeExpression.cs b/src/Microsoft.OpenApi/Expressions/StatusCodeExpression.cs index 88a384781..d077c82ad 100644 --- a/src/Microsoft.OpenApi/Expressions/StatusCodeExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/StatusCodeExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Expressions/UrlExpression.cs b/src/Microsoft.OpenApi/Expressions/UrlExpression.cs index 4dc10bb77..e8da5710f 100644 --- a/src/Microsoft.OpenApi/Expressions/UrlExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/UrlExpression.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Expressions { diff --git a/src/Microsoft.OpenApi/Extensions/EnumExtensions.cs b/src/Microsoft.OpenApi/Extensions/EnumExtensions.cs index d7c778c19..4e2e795d3 100644 --- a/src/Microsoft.OpenApi/Extensions/EnumExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/EnumExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Linq; diff --git a/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs index a32807ab6..672730339 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs @@ -14,7 +14,7 @@ internal static class OpenAPIWriterExtensions /// /// /// - internal static OpenApiWriterSettings GetSettings(this IOpenApiWriter openApiWriter) + internal static OpenApiWriterSettings GetSettings(this IOpenApiWriter openApiWriter) { if (openApiWriter is OpenApiWriterBase) { diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiElementExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiElementExtensions.cs index a047c066d..38a53ecec 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiElementExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiElementExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs index 7656aad89..9cb3f21ed 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiReferencableExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiReferencableExtensions.cs index 11fcd7e9e..defe95636 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiReferencableExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiReferencableExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs index f60c5483b..c39e378f6 100755 --- a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Globalization; using System.IO; @@ -74,7 +74,7 @@ public static void Serialize( this T element, Stream stream, OpenApiSpecVersion specVersion, - OpenApiFormat format, + OpenApiFormat format, OpenApiWriterSettings settings) where T : IOpenApiSerializable { diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs index 970b3a976..176762dc6 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -27,7 +27,7 @@ public static class OpenApiTypeMapper [typeof(DateTimeOffset)] = () => new OpenApiSchema { Type = "string", Format = "date-time" }, [typeof(Guid)] = () => new OpenApiSchema { Type = "string", Format = "uuid" }, [typeof(char)] = () => new OpenApiSchema { Type = "string" }, - + // Nullable types [typeof(bool?)] = () => new OpenApiSchema { Type = "boolean", Nullable = true }, [typeof(byte?)] = () => new OpenApiSchema { Type = "string", Format = "byte", Nullable = true }, @@ -123,7 +123,7 @@ public static Type MapOpenApiPrimitiveTypeToSimpleType(this OpenApiSchema schema ("boolean", null, true) => typeof(bool?), _ => typeof(string), }; - + return type; } } diff --git a/src/Microsoft.OpenApi/Interfaces/IEffective.cs b/src/Microsoft.OpenApi/Interfaces/IEffective.cs index b62ec12ab..b3ac0a37b 100644 --- a/src/Microsoft.OpenApi/Interfaces/IEffective.cs +++ b/src/Microsoft.OpenApi/Interfaces/IEffective.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; @@ -9,8 +9,8 @@ namespace Microsoft.OpenApi.Interfaces /// OpenApiElements that implement IEffective indicate that their description is not self-contained. /// External elements affect the effective description. /// - /// Currently this will only be used for accessing external references. - /// In the next major version, this will be the approach accessing all referenced elements. + /// Currently this will only be used for accessing external references. + /// In the next major version, this will be the approach accessing all referenced elements. /// This will enable us to support merging properties that are peers of the $ref /// Type of OpenApi Element that is being referenced. public interface IEffective where T : class,IOpenApiElement diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiElement.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiElement.cs index 45f7bad11..d66939532 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiElement.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiElement.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Interfaces { diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs index 7abd1bfdd..8fc4e8051 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs index a9ea04a39..ad6f2c0e5 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs index c790e1fda..e5d0b73b4 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs index 582bd49cd..6f5b1bd09 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Writers; diff --git a/src/Microsoft.OpenApi/JsonPointer.cs b/src/Microsoft.OpenApi/JsonPointer.cs index c2aec5097..1ff843031 100644 --- a/src/Microsoft.OpenApi/JsonPointer.cs +++ b/src/Microsoft.OpenApi/JsonPointer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Linq; diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index e6aa5d075..62c8f560f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Expressions; @@ -103,7 +103,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } /// - /// Returns an effective OpenApiCallback object based on the presence of a $ref + /// Returns an effective OpenApiCallback object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiCallback diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index a6bfef594..5a653aa2a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; @@ -117,7 +117,7 @@ public void SerializeAsV3(IOpenApiWriter writer) }); } writer.WriteEndObject(); - return; + return; } writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiConstants.cs b/src/Microsoft.OpenApi/Models/OpenApiConstants.cs index 553844764..eccf3a616 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiConstants.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiConstants.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 93cb11bca..2550f866b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs index 9ae7f0e6a..c1b4d913c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index d2d9cf893..c19de5e84 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -187,7 +187,7 @@ public void SerializeAsV2(IOpenApiWriter writer) } else { - // Serialize each referenceable object as full object without reference if the reference in the object points to itself. + // Serialize each referenceable object as full object without reference if the reference in the object points to itself. // If the reference exists but points to other objects, the object is serialized to just that reference. // definitions writer.WriteOptionalMap( @@ -208,8 +208,8 @@ public void SerializeAsV2(IOpenApiWriter writer) }); } // parameters - var parameters = Components?.Parameters != null - ? new Dictionary(Components.Parameters) + var parameters = Components?.Parameters != null + ? new Dictionary(Components.Parameters) : new Dictionary(); if (Components?.RequestBodies != null) @@ -309,7 +309,7 @@ private static void WriteHostInfoV2(IOpenApiWriter writer, IList return; } - // Arbitrarily choose the first server given that V2 only allows + // Arbitrarily choose the first server given that V2 only allows // one host, port, and base path. var serverUrl = ParseServerUrl(servers.First()); @@ -323,7 +323,7 @@ private static void WriteHostInfoV2(IOpenApiWriter writer, IList writer.WriteProperty( OpenApiConstants.Host, firstServerUrl.GetComponents(UriComponents.Host | UriComponents.Port, UriFormat.SafeUnescaped)); - + // basePath if (firstServerUrl.AbsolutePath != "/") { @@ -407,7 +407,7 @@ public IOpenApiReferenceable ResolveReference(OpenApiReference reference) } /// - /// Takes in an OpenApi document instance and generates its hash value + /// Takes in an OpenApi document instance and generates its hash value /// /// The OpenAPI description to hash. /// The hash value. diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index 13b6e3a0a..d5b0a2057 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Extensions; diff --git a/src/Microsoft.OpenApi/Models/OpenApiError.cs b/src/Microsoft.OpenApi/Models/OpenApiError.cs index 82f2a14df..54b98a067 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiError.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiError.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Exceptions; diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 4d091a361..018a46729 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; @@ -101,7 +101,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } /// - /// Returns an effective OpenApiExample object based on the presence of a $ref + /// Returns an effective OpenApiExample object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiExample diff --git a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs index 40c26d429..02945e0f9 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Interfaces; @@ -31,7 +31,7 @@ protected OpenApiExtensibleDictionary( IDictionary extensions = null) : base (dictionary) { Extensions = extensions != null ? new Dictionary(extensions) : null; - } + } /// /// This object MAY be extended with Specification Extensions. diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 345f07d59..3bcdbc07b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index fb4411478..ad6b3d91f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; @@ -141,7 +141,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } /// - /// Returns an effective OpenApiHeader object based on the presence of a $ref + /// Returns an effective OpenApiHeader object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiHeader diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index df0aa0a49..ecba7a6d7 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index 866515835..a02b50756 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index b682744e9..54713c242 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; @@ -111,7 +111,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } /// - /// Returns an effective OpenApiLink object based on the presence of a $ref + /// Returns an effective OpenApiLink object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiLink diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 63a58cd02..cebfa995c 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index 9c12fb5a9..fc92f7bac 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index 8443e6730..c7b73f22d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 9336662d8..808e50aa0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -314,7 +314,7 @@ public void SerializeAsV2(IOpenApiWriter writer) // schemes // All schemes in the Servers are extracted, regardless of whether the host matches - // the host defined in the outermost Swagger object. This is due to the + // the host defined in the outermost Swagger object. This is due to the // inaccessibility of information for that host in the context of an inner object like this Operation. if (Servers != null) { diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 06e5749e6..ace76ae4b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -78,7 +78,7 @@ public class OpenApiParameter : IOpenApiSerializable, IOpenApiReferenceable, IEf /// for cookie - form. /// public ParameterStyle? Style - { + { get => _style ?? SetDefaultStyleValue(); set => _style = value; } @@ -190,7 +190,7 @@ public void SerializeAsV3(IOpenApiWriter writer) { Reference.SerializeAsV3(writer); return; - } + } else { target = this.GetEffective(Reference.HostDocument); @@ -201,7 +201,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } /// - /// Returns an effective OpenApiParameter object based on the presence of a $ref + /// Returns an effective OpenApiParameter object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiParameter @@ -289,7 +289,7 @@ public void SerializeAsV2(IOpenApiWriter writer) { Reference.SerializeAsV2(writer); return; - } + } else { target = this.GetEffective(Reference.HostDocument); diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index ddd358dc2..2f4568e7d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Extensions; @@ -102,7 +102,7 @@ public void SerializeAsV3(IOpenApiWriter writer) { Reference.SerializeAsV3(writer); return; - } + } else { target = GetEffective(Reference.HostDocument); @@ -112,7 +112,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } /// - /// Returns an effective OpenApiPathItem object based on the presence of a $ref + /// Returns an effective OpenApiPathItem object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiPathItem @@ -146,7 +146,7 @@ public void SerializeAsV2(IOpenApiWriter writer) { Reference.SerializeAsV2(writer); return; - } + } else { target = this.GetEffective(Reference.HostDocument); diff --git a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs index 8aae74883..014b37a1a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPaths.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPaths.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Models { @@ -17,6 +17,6 @@ public OpenApiPaths() {} /// Initializes a copy of object /// /// The . - public OpenApiPaths(OpenApiPaths paths) : base(dictionary: paths) { } + public OpenApiPaths(OpenApiPaths paths) : base(dictionary: paths) { } } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index e8798cc64..17055a93e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; @@ -205,7 +205,7 @@ private string GetExternalReferenceV3() { return ExternalResource + "#" + Id; } - + return ExternalResource + "#/components/" + Type.GetDisplayName() + "/"+ Id; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 70f1f742a..27b48909a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -93,7 +93,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } /// - /// Returns an effective OpenApiRequestBody object based on the presence of a $ref + /// Returns an effective OpenApiRequestBody object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiRequestBody @@ -187,7 +187,7 @@ internal IEnumerable ConvertToFormDataParameters() Description = property.Value.Description, Name = property.Key, Schema = property.Value, - Required = Content.First().Value.Schema.Required.Contains(property.Key) + Required = Content.First().Value.Schema.Required.Contains(property.Key) }; } } diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index a173f6c1a..e15e81aaf 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; @@ -98,7 +98,7 @@ public void SerializeAsV3(IOpenApiWriter writer) } /// - /// Returns an effective OpenApiRequestBody object based on the presence of a $ref + /// Returns an effective OpenApiRequestBody object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiResponse diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs index aa7a8c984..483524044 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponses.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponses.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Models { diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index b0ac2dbac..303f3ee31 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; @@ -487,7 +487,7 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) } /// - /// Serialize to Open Api v2.0 and handles not marking the provided property + /// Serialize to Open Api v2.0 and handles not marking the provided property /// as readonly if its included in the provided list of required properties of parent schema. /// /// The open api writer. @@ -545,7 +545,7 @@ internal void SerializeAsV2( } /// - /// Serialize to OpenAPI V2 document without using reference and handles not marking the provided property + /// Serialize to OpenAPI V2 document without using reference and handles not marking the provided property /// as readonly if its included in the provided list of required properties of parent schema. /// /// The open api writer. @@ -771,7 +771,7 @@ internal void WriteAsSchemaProperties( } /// - /// Returns an effective OpenApiSchema object based on the presence of a $ref + /// Returns an effective OpenApiSchema object based on the presence of a $ref /// /// The host OpenApiDocument that contains the reference. /// OpenApiSchema diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs index d2564daf2..2ccb58a52 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 616a6a022..20676ded6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index a13a6fb2d..dcb2382a1 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index 70164bc59..92265a386 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index ba4129142..2794fda8e 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index c6719d85e..0a594c773 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Models/OperationType.cs b/src/Microsoft.OpenApi/Models/OperationType.cs index a85933d9b..ed3457353 100644 --- a/src/Microsoft.OpenApi/Models/OperationType.cs +++ b/src/Microsoft.OpenApi/Models/OperationType.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Attributes; diff --git a/src/Microsoft.OpenApi/Models/ParameterLocation.cs b/src/Microsoft.OpenApi/Models/ParameterLocation.cs index a729f314e..d223cad87 100644 --- a/src/Microsoft.OpenApi/Models/ParameterLocation.cs +++ b/src/Microsoft.OpenApi/Models/ParameterLocation.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Attributes; diff --git a/src/Microsoft.OpenApi/Models/ParameterStyle.cs b/src/Microsoft.OpenApi/Models/ParameterStyle.cs index a1df27962..2534b2859 100644 --- a/src/Microsoft.OpenApi/Models/ParameterStyle.cs +++ b/src/Microsoft.OpenApi/Models/ParameterStyle.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Attributes; diff --git a/src/Microsoft.OpenApi/Models/ReferenceType.cs b/src/Microsoft.OpenApi/Models/ReferenceType.cs index 9d8984c96..acbb22a9a 100644 --- a/src/Microsoft.OpenApi/Models/ReferenceType.cs +++ b/src/Microsoft.OpenApi/Models/ReferenceType.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Attributes; diff --git a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs index 1a1f12a18..43af59f5b 100644 --- a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs +++ b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Expressions; diff --git a/src/Microsoft.OpenApi/Models/SecuritySchemeType.cs b/src/Microsoft.OpenApi/Models/SecuritySchemeType.cs index d75524bd6..f5136ab19 100644 --- a/src/Microsoft.OpenApi/Models/SecuritySchemeType.cs +++ b/src/Microsoft.OpenApi/Models/SecuritySchemeType.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Attributes; diff --git a/src/Microsoft.OpenApi/OpenApiFormat.cs b/src/Microsoft.OpenApi/OpenApiFormat.cs index 8f4c55b68..8005d7d62 100644 --- a/src/Microsoft.OpenApi/OpenApiFormat.cs +++ b/src/Microsoft.OpenApi/OpenApiFormat.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi { diff --git a/src/Microsoft.OpenApi/OpenApiSpecVersion.cs b/src/Microsoft.OpenApi/OpenApiSpecVersion.cs index 20e49af80..48666ab79 100644 --- a/src/Microsoft.OpenApi/OpenApiSpecVersion.cs +++ b/src/Microsoft.OpenApi/OpenApiSpecVersion.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi { @@ -15,7 +15,7 @@ public enum OpenApiSpecVersion /// /// Represents all patches of OpenAPI V3.0 spec (e.g. 3.0.0, 3.0.1) - /// + /// OpenApi3_0 } } diff --git a/src/Microsoft.OpenApi/Properties/AssemblyInfo.cs b/src/Microsoft.OpenApi/Properties/AssemblyInfo.cs index 159c979dd..559c86738 100644 --- a/src/Microsoft.OpenApi/Properties/AssemblyInfo.cs +++ b/src/Microsoft.OpenApi/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Runtime.CompilerServices; diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs index 7e2ebdcac..7984b6c58 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceError.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index dc0fb1c8d..88621a382 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 9f4ccb8be..d43e728fd 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -268,7 +268,7 @@ public void WriteMermaid(TextWriter writer) { "DELETE", new MermaidNodeStyle("Tomato", MermaidNodeShape.Rhombus) }, { "OTHER", new MermaidNodeStyle("White", MermaidNodeShape.SquareCornerRectangle) }, }; - + private static void ProcessNode(OpenApiUrlTreeNode node, TextWriter writer) { var path = string.IsNullOrEmpty(node.Path) ? "/" : SanitizeMermaidNode(node.Path); @@ -329,7 +329,7 @@ private static string SanitizeMermaidNode(string token) .Replace(".", "_") .Replace("(", "_") .Replace(")", "_") - .Replace(";", "_") + .Replace(";", "_") .Replace("-", "_") .Replace("graph", "gra_ph") // graph is a reserved word .Replace("default", "def_ault"); // default is a reserved word for classes diff --git a/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs b/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs index c9679381a..1628ccd00 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -22,7 +22,7 @@ public abstract class OpenApiVisitorBase public CurrentKeys CurrentKeys { get; } = new CurrentKeys(); /// - /// Allow Rule to indicate validation error occured at a deeper context level. + /// Allow Rule to indicate validation error occured at a deeper context level. /// /// Identifier for context public virtual void Enter(string segment) diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index 1da6cc9cf..87db2b844 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -297,7 +297,7 @@ internal void Walk(IOpenApiExtensible openApiExtensible) } /// - /// Visits + /// Visits /// internal void Walk(IOpenApiExtension extension) { diff --git a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs index 7827a50c1..f8920efd4 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -29,7 +29,7 @@ public IEnumerable Documents { get { return _documents.Values; } - } + } /// /// A list of document fragments that are contained in the workspace @@ -69,7 +69,7 @@ public OpenApiWorkspace() public OpenApiWorkspace(OpenApiWorkspace workspace){} /// - /// Verify if workspace contains a document based on its URL. + /// Verify if workspace contains a document based on its URL. /// /// A relative or absolute URL of the file. Use file:// for folder locations. /// Returns true if a matching document is found. @@ -95,7 +95,7 @@ public void AddDocument(string location, OpenApiDocument document) /// /// /// - /// Not sure how this is going to work. Does the reference just point to the fragment as a whole, or do we need to + /// Not sure how this is going to work. Does the reference just point to the fragment as a whole, or do we need to /// to be able to point into the fragment. Keeping it private until we figure it out. /// public void AddFragment(string location, IOpenApiReferenceable fragment) diff --git a/src/Microsoft.OpenApi/Validations/IValidationContext.cs b/src/Microsoft.OpenApi/Validations/IValidationContext.cs index 7ab4d08e7..2858a239a 100644 --- a/src/Microsoft.OpenApi/Validations/IValidationContext.cs +++ b/src/Microsoft.OpenApi/Validations/IValidationContext.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Validations { @@ -21,7 +21,7 @@ public interface IValidationContext void AddWarning(OpenApiValidatorWarning warning); /// - /// Allow Rule to indicate validation error occured at a deeper context level. + /// Allow Rule to indicate validation error occured at a deeper context level. /// /// Identifier for context void Enter(string segment); diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs index 77480584d..33e088b09 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidatiorWarning.cs @@ -5,7 +5,7 @@ using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.Validations -{ +{ /// /// Warnings detected when validating an OpenAPI Element /// diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index a0aee12e7..5fb37ad92 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -300,7 +300,7 @@ private void Validate(T item) } /// - /// This overload allows applying rules based on actual object type, rather than matched interface. This is + /// This overload allows applying rules based on actual object type, rather than matched interface. This is /// needed for validating extensions. /// private void Validate(object item, Type type) diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidatorError.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidatorError.cs index c24d48fe3..216b688a5 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidatorError.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidatorError.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiComponentsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiComponentsRules.cs index 60267a26d..468e97447 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiComponentsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiComponentsRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Text.RegularExpressions; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs index f518453f7..d71db1822 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs index e5193b4c2..7d01f1319 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs index c44983ffb..c95477c87 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExternalDocsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExternalDocsRules.cs index a54651073..8556eaa32 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExternalDocsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExternalDocsRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs index 9ffbc38f4..cf9200917 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiInfoRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiInfoRules.cs index e02f019e2..f3ddbfa28 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiInfoRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiInfoRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiLicenseRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiLicenseRules.cs index d854268c6..89b88ca9d 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiLicenseRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiLicenseRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs index 21ad4ef72..f4cc4b2ab 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiOAuthFlowRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiOAuthFlowRules.cs index 7d900e1b4..95444fb9a 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiOAuthFlowRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiOAuthFlowRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiParameterRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiParameterRules.cs index d38bd7f9e..878e2db10 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiParameterRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiParameterRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; @@ -97,13 +97,13 @@ public static class OpenApiParameterRules }); /// - /// Validate that a path parameter should always appear in the path + /// Validate that a path parameter should always appear in the path /// public static ValidationRule PathParameterShouldBeInThePath => new ValidationRule( (context, parameter) => { - if (parameter.In == ParameterLocation.Path && + if (parameter.In == ParameterLocation.Path && !(context.PathString.Contains("{" + parameter.Name + "}") || context.PathString.Contains("#/components"))) { context.Enter("in"); diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs index 7ac374b62..669e27bb0 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponseRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponseRules.cs index 6aae427d1..11b228e74 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponseRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponseRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponsesRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponsesRules.cs index d05a1229c..5df74c2e9 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponsesRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponsesRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Linq; using System.Text.RegularExpressions; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index a8ed2e93c..6753a3e65 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiServerRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiServerRules.cs index 93f0f581f..67fc5eef2 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiServerRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiServerRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiTagRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiTagRules.cs index cc4d1f97f..9dac45966 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiTagRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiTagRules.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Models; diff --git a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs index 630dc8e65..25372d575 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs b/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs index 195df89cd..ed889febd 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/src/Microsoft.OpenApi/Validations/ValidationRule.cs b/src/Microsoft.OpenApi/Validations/ValidationRule.cs index fdbf5c330..5b79a9be2 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRule.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRule.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using Microsoft.OpenApi.Interfaces; diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index eca7bc8de..a01c4a4bc 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Linq; diff --git a/src/Microsoft.OpenApi/Writers/FormattingStreamWriter.cs b/src/Microsoft.OpenApi/Writers/FormattingStreamWriter.cs index b6db3d1e0..ea4f33f63 100644 --- a/src/Microsoft.OpenApi/Writers/FormattingStreamWriter.cs +++ b/src/Microsoft.OpenApi/Writers/FormattingStreamWriter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.IO; diff --git a/src/Microsoft.OpenApi/Writers/IOpenApiWriter.cs b/src/Microsoft.OpenApi/Writers/IOpenApiWriter.cs index 8fcbf10ed..9ea04b400 100644 --- a/src/Microsoft.OpenApi/Writers/IOpenApiWriter.cs +++ b/src/Microsoft.OpenApi/Writers/IOpenApiWriter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Writers { diff --git a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs index 10049974b..86bacb558 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs index 361da3b2a..2c8fc7d68 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using Microsoft.OpenApi.Any; diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs index 4d7f11032..cc88b0582 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Writers /// public abstract class OpenApiWriterBase : IOpenApiWriter { - + /// /// Settings for controlling how the OpenAPI document will be written out. /// @@ -49,7 +49,7 @@ public OpenApiWriterBase(TextWriter textWriter) : this(textWriter, null) /// /// /// - public OpenApiWriterBase(TextWriter textWriter, OpenApiWriterSettings settings) + public OpenApiWriterBase(TextWriter textWriter, OpenApiWriterSettings settings) { Writer = textWriter; Writer.NewLine = "\n"; diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs index 537273cac..518936b11 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections; diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs index 06fcd0246..6e503f5d6 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs @@ -39,8 +39,8 @@ public class OpenApiWriterSettings /// Indicates how references in the source document should be handled. /// [Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] - public ReferenceInlineSetting ReferenceInline { - get { return referenceInline; } + public ReferenceInlineSetting ReferenceInline { + get { return referenceInline; } set { referenceInline = value; switch(referenceInline) diff --git a/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs b/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs index 47afdcc31..be8794941 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; @@ -185,7 +185,7 @@ public override void WriteValue(string value) } Writer.Write("|"); - + WriteChompingIndicator(value); // Write indentation indicator when it starts with spaces @@ -193,7 +193,7 @@ public override void WriteValue(string value) { Writer.Write(IndentationString.Length); } - + Writer.WriteLine(); IncreaseIndentation(); @@ -207,7 +207,7 @@ public override void WriteValue(string value) firstLine = false; else Writer.WriteLine(); - + // Indentations for empty lines aren't needed. if (line.Length > 0) { diff --git a/src/Microsoft.OpenApi/Writers/Scope.cs b/src/Microsoft.OpenApi/Writers/Scope.cs index 37093cffc..3bfdb5ef8 100644 --- a/src/Microsoft.OpenApi/Writers/Scope.cs +++ b/src/Microsoft.OpenApi/Writers/Scope.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Writers { diff --git a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs index 6e1ea2beb..02d30ec08 100644 --- a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Globalization; @@ -12,7 +12,7 @@ namespace Microsoft.OpenApi.Writers /// public static class SpecialCharacterStringExtensions { - // Plain style strings cannot start with indicators. + // Plain style strings cannot start with indicators. // http://www.yaml.org/spec/1.2/spec.html#indicator// private static readonly char[] _yamlIndicators = { @@ -170,9 +170,9 @@ internal static string GetYamlCompatibleString(this string input) return $"\"{input}\""; } - // If string + // If string // 1) includes a character forbidden in plain string, - // 2) starts with an indicator, OR + // 2) starts with an indicator, OR // 3) has trailing/leading white spaces, // wrap the string in single quote. // http://www.yaml.org/spec/1.2/spec.html#style/flow/plain diff --git a/src/Microsoft.OpenApi/Writers/WriterConstants.cs b/src/Microsoft.OpenApi/Writers/WriterConstants.cs index 5b4f2da91..13e6deabd 100644 --- a/src/Microsoft.OpenApi/Writers/WriterConstants.cs +++ b/src/Microsoft.OpenApi/Writers/WriterConstants.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. namespace Microsoft.OpenApi.Writers { diff --git a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs index 3fc77fc01..c6f33d6f5 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs @@ -203,7 +203,7 @@ public static OpenApiDocument CreateOpenApiDocument() Type = "string" } } - } + } }, ["/users"] = new OpenApiPathItem { diff --git a/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs b/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs index 64e25fcfb..a694d17b0 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixtureCollection.cs b/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixtureCollection.cs index 1b9bd1107..d17520848 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixtureCollection.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixtureCollection.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Xunit; diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs index 5b01e0444..0ab0f9bc7 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Threading.Tasks; diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs index cd60aa630..44b5163e3 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; using Microsoft.OpenApi.Readers.Exceptions; diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs index 869d43fab..7c3607a33 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs @@ -99,7 +99,7 @@ public Task LoadAsync(Uri uri) return null; } } - + public class ResourceLoader : IStreamLoader { diff --git a/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs index 2ece19537..7a4090c03 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs index 3875b77b0..ab61456ac 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Globalization; diff --git a/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyTests.cs b/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyTests.cs index 263c28fec..d089ccf24 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/test/Microsoft.OpenApi.Readers.Tests/Properties/AssemblyInfo.cs b/test/Microsoft.OpenApi.Readers.Tests/Properties/AssemblyInfo.cs index c8a317893..62f4c0e52 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Properties/AssemblyInfo.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/Properties/AssemblyInfo.cs @@ -1,3 +1,3 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs index bd9600e4f..9bd42a0e3 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; using Microsoft.OpenApi.Models; diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs index 6b94a161b..40d92075a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; using Microsoft.OpenApi.Models; diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs index 9469de370..ff8285159 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs b/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs index 89468229a..5ab83606e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; using Microsoft.OpenApi.Any; diff --git a/test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs b/test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs index c97e35e9b..654be0858 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs index 1ae3678d6..0d91716a3 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs index 71489d39f..853c1efcb 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; using Microsoft.OpenApi.Models; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index 4acdb583f..7926a062b 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Globalization; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs index eb3bb066c..ee9ad85c6 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs index 76da8a763..30a32ed13 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs index 3f46f5a2b..7239139c1 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs index c32c15ff4..88179b160 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSchemaTests.cs index 9a75e5c8d..59ee452fb 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSchemaTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs index 22f7d1633..e54dbaab3 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs index 1a45006db..d396c471b 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs index be78f942b..5ce74bc3e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; using Microsoft.OpenApi.Models; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs index 0768592b3..32160bcd9 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 85a686e49..c7684f8ce 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs index 7f33491ff..ac6750901 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs index ead84f201..4ff4b0d42 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs index 29b23cb31..5bdad67a9 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs index 47983a9a1..f9835bfbb 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs index 37053c2a4..b81e8d970 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using System.Linq; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs index 3234195e5..13188dba1 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.IO; using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index 54553d5a5..1f5483162 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs index 9d7a27d72..e5f8e155e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.IO; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs index a10d674a9..c9033832e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.IO; diff --git a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs index efba7b9b0..5466586d0 100644 --- a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs +++ b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs b/test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs index 9bb685ddc..3a0b8aabe 100644 --- a/test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs +++ b/test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Tests/DefaultSettingsFixtureCollection.cs b/test/Microsoft.OpenApi.Tests/DefaultSettingsFixtureCollection.cs index 4fdfe0b16..22f562c4d 100644 --- a/test/Microsoft.OpenApi.Tests/DefaultSettingsFixtureCollection.cs +++ b/test/Microsoft.OpenApi.Tests/DefaultSettingsFixtureCollection.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using Xunit; diff --git a/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs b/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs index c2b6d9597..a0fcb133a 100644 --- a/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs +++ b/test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -29,7 +29,7 @@ public class OpenApiTypeMapperTests new object[] { new OpenApiSchema { Type = "number", Format = "float", Nullable = true }, typeof(float?) }, new object[] { new OpenApiSchema { Type = "string", Format = "date-time" }, typeof(DateTimeOffset) } }; - + [Theory] [MemberData(nameof(PrimitiveTypeData))] public void MapTypeToOpenApiPrimitiveTypeShouldSucceed(Type type, OpenApiSchema expected) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs index 93b78e71b..5aabd5ef4 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Globalization; using System.IO; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs index 46a6bb772..d6222f2a7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs index 1a99241d1..0e4531551 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index becc91d97..f19895569 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -1697,10 +1697,10 @@ public void SerializeV2DocumentWithNonArraySchemaTypeDoesNotWriteOutCollectionFo { Info = new OpenApiInfo(), Paths = new OpenApiPaths - { + { ["/foo"] = new OpenApiPathItem { - Operations = new Dictionary + Operations = new Dictionary { [OperationType.Get] = new OpenApiOperation { @@ -1730,7 +1730,7 @@ public void SerializeV2DocumentWithNonArraySchemaTypeDoesNotWriteOutCollectionFo expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } - + [Fact] public void SerializeV2DocumentWithStyleAsNullDoesNotWriteOutStyleValue() { @@ -1818,6 +1818,6 @@ public void SerializeV2DocumentWithStyleAsNullDoesNotWriteOutStyleValue() actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); - } + } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs index 24bfca242..7a4b9de50 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; using Microsoft.OpenApi.Extensions; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs index e12a7d100..6d756fec5 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Globalization; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs index 7d37fc9a4..ab013e9a2 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs index d45bd0038..15f081c90 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Globalization; using System.IO; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs index b2395a9ed..052c3264b 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs index 46717ecec..87937072e 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs index 4a10be0ae..6f06c947d 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Globalization; using System.IO; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs index c59da1e86..600958b97 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs index 80040f566..c16eccbef 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs index 7d4882bbb..4135e3e50 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index 11d8dc517..b0394ccab 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index 2a2c65202..a0214fdcd 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Globalization; @@ -54,7 +54,7 @@ public class OpenApiParameterTests OneOf = new List { new OpenApiSchema { Type = "number", Format = "double" }, - new OpenApiSchema { Type = "string" } + new OpenApiSchema { Type = "string" } } }, Examples = new Dictionary diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs index b9edd2a32..e4f1e8582 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiReferenceTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using FluentAssertions; using Microsoft.OpenApi.Extensions; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs index 78fcd0d07..6b62e9fe8 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Globalization; using System.IO; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs index 0010e8cb6..235da9955 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Globalization; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index d59c026e3..82b65f015 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -430,7 +430,7 @@ public void SerializeAsV2ShouldSetFormatPropertyInParentSchemaIfPresentInChildre OneOf = new List { new OpenApiSchema - { + { Type = "number", Format = "decimal" }, diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs index 7d630c5f6..5087f71dc 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs index 44a388d90..91085e791 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -32,7 +32,7 @@ public class OpenApiSecuritySchemeTests { Description = "description1", Type = SecuritySchemeType.Http, - Scheme = OpenApiConstants.Basic + Scheme = OpenApiConstants.Basic }; @@ -311,7 +311,7 @@ public async Task SerializeReferencedSecuritySchemeAsV3JsonWorksAsync(bool produ var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); // Act - // Add dummy start object, value, and end object to allow SerializeAsV3 to output security scheme + // Add dummy start object, value, and end object to allow SerializeAsV3 to output security scheme // as property name. writer.WriteStartObject(); ReferencedSecurityScheme.SerializeAsV3(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs index e4d4f36fb..23e7fcc00 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs index 9d50f76f6..74f837aca 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using FluentAssertions; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs index 66c0dfd70..a2b49fe18 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Globalization; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs index 9e79c5211..a9744b668 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Properties/AssemblyInfo.cs b/test/Microsoft.OpenApi.Tests/Properties/AssemblyInfo.cs index c8a317893..62f4c0e52 100644 --- a/test/Microsoft.OpenApi.Tests/Properties/AssemblyInfo.cs +++ b/test/Microsoft.OpenApi.Tests/Properties/AssemblyInfo.cs @@ -1,3 +1,3 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs index 813cb9517..3d488c7db 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/StringExtensions.cs b/test/Microsoft.OpenApi.Tests/StringExtensions.cs index 5b01c97ac..b3b458683 100644 --- a/test/Microsoft.OpenApi.Tests/StringExtensions.cs +++ b/test/Microsoft.OpenApi.Tests/StringExtensions.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs index 8188d6334..b6e187360 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs index 221c245a5..7d371c12a 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs index fee728f76..ab25b7c28 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs index 429c460a4..aa7afe477 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs index 1a58fff04..7793de94e 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiLicenseValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiLicenseValidationTests.cs index 8efb8715c..45bab5671 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiLicenseValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiLicenseValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs index a68d91578..733a468bb 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiOAuthFlowValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiOAuthFlowValidationTests.cs index 02ab469ae..329727b2b 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiOAuthFlowValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiOAuthFlowValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs index 24f28e4eb..1a3b5442b 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs index 57f9f2cae..0c150cd5c 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiResponseValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiResponseValidationTests.cs index 5f4c29173..a3a84af95 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiResponseValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiResponseValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs index 3ea545af9..1760b000f 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -275,7 +275,7 @@ public void ValidateOneOfSchemaPropertyNameContainsPropertySpecifiedInTheDiscrim // Arrange var components = new OpenApiComponents { - Schemas = + Schemas = { { "Person", @@ -309,7 +309,7 @@ public void ValidateOneOfSchemaPropertyNameContainsPropertySpecifiedInTheDiscrim }, Reference = new OpenApiReference { Id = "Person" } } - } + } } }; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs index bbc4c7e10..22b3d706f 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs index a039b39c2..c917592c4 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs b/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs index 58d4d3d4c..5898c1aff 100644 --- a/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs index d3c44c29b..a9d2c6694 100644 --- a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs +++ b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs index 44d1be55b..e7980d1c2 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections; diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs index d1839015d..6e6ab8ba3 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections.Generic; @@ -152,7 +152,7 @@ public static IEnumerable StringifiedDateTimes get { return - from input in new [] { + from input in new [] { "2017-1-2", "1999-01-02T12:10:22", "1999-01-03", diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs index 6ac47d6c3..05bb6e909 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System.Collections.Generic; using System.Globalization; diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs index 13f70f1e9..16395fd2b 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. +// Licensed under the MIT license. using System; using System.Collections; From eecda3493b6d6e3132c43ae46438c9196645ac16 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Oct 2023 20:09:00 +1100 Subject: [PATCH 648/855] . --- .../Options/CommandOptions.cs | 2 +- .../Exceptions/OpenApiReaderException.cs | 1 - .../OpenApiTextReaderReader.cs | 1 - .../ParsingContext.cs | 1 - .../Services/DefaultStreamLoader.cs | 1 - .../V2/OpenApiDocumentDeserializer.cs | 2 - .../V2/OpenApiV2VersionService.cs | 2 - .../V3/OpenApiComponentsDeserializer.cs | 1 - .../V3/OpenApiMediaTypeDeserializer.cs | 1 - src/Microsoft.OpenApi.Workbench/MainModel.cs | 7 +- .../Exceptions/OpenApiException.cs | 1 - .../OpenApiSerializableExtensions.cs | 1 - .../Models/OpenApiCallback.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiLink.cs | 1 - .../Models/OpenApiParameter.cs | 4 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 6 +- .../Models/OpenApiSecurityScheme.cs | 1 - .../Services/OpenApiReferenceResolver.cs | 1 - .../Services/OpenApiVisitorBase.cs | 3 - .../Services/OpenApiWalker.cs | 5 +- .../Services/SearchResult.cs | 1 - .../Validations/IValidationContext.cs | 1 - .../Rules/OpenApiMediaTypeRules.cs | 1 - .../Validations/ValidationExtensions.cs | 1 - .../Writers/OpenApiWriterSettings.cs | 4 +- .../Services/OpenApiFilterServiceTests.cs | 1 - .../Services/OpenApiServiceTests.cs | 9 +- .../OpenApiWorkspaceStreamTests.cs | 5 - .../ParseNodes/OpenApiAnyConverterTests.cs | 2 - .../ConvertToOpenApiReferenceV3Tests.cs | 2 - .../V2Tests/OpenApiDocumentTests.cs | 6 - .../V2Tests/OpenApiPathItemTests.cs | 1 - .../V2Tests/OpenApiServerTests.cs | 1 - .../V3Tests/OpenApiDocumentTests.cs | 2 - .../V3Tests/OpenApiSchemaTests.cs | 1 - .../GraphTests.cs | 2 - .../Expressions/RuntimeExpressionTests.cs | 3 - .../OpenApiDeprecationExtensionTests.cs | 1 - .../Models/OpenApiDocumentTests.cs | 1 - .../Models/OpenApiReferenceTests.cs | 1 - .../Models/OpenApiSchemaTests.cs | 1 - .../Services/OpenApiValidatorTests.cs | 2 - .../OpenApiComponentsValidationTests.cs | 1 - .../OpenApiReferenceValidationTests.cs | 1 - .../Workspaces/OpenApiWorkspaceTests.cs | 186 +++++------------- .../Writers/OpenApiYamlWriterTests.cs | 3 - 47 files changed, 62 insertions(+), 222 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Options/CommandOptions.cs b/src/Microsoft.OpenApi.Hidi/Options/CommandOptions.cs index 735644970..6fee866cb 100644 --- a/src/Microsoft.OpenApi.Hidi/Options/CommandOptions.cs +++ b/src/Microsoft.OpenApi.Hidi/Options/CommandOptions.cs @@ -104,6 +104,6 @@ public IReadOnlyList