From a648591c6dc75f111218d8ec46d8e52812bc0017 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Mon, 25 Nov 2024 23:42:06 -0500 Subject: [PATCH 01/50] Refactor readers to reduce surface area --- .../OpenApiYamlReader.cs | 33 +++-- .../Interfaces/IOpenApiReader.cs | 19 ++- .../Models/OpenApiDocument.cs | 27 +--- .../Reader/OpenApiJsonReader.cs | 77 +++++++---- .../Reader/OpenApiModelFactory.cs | 124 +++++++----------- .../V31Tests/OpenApiSchemaTests.cs | 9 ++ .../V3Tests/OpenApiDiscriminatorTests.cs | 8 +- 7 files changed, 154 insertions(+), 143 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index cff6dd1da..1a85e6a27 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -19,17 +19,34 @@ namespace Microsoft.OpenApi.Readers /// public class OpenApiYamlReader : IOpenApiReader { + private const int copyBufferSize = 4096; + /// - public async Task ReadAsync(TextReader input, + public async Task ReadAsync(Stream input, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) + { + if (input is MemoryStream memoryStream) + { + return Read(memoryStream, settings); + } else { + using var preparedStream = new MemoryStream(); + await input.CopyToAsync(preparedStream, copyBufferSize, cancellationToken); + preparedStream.Position = 0; + return Read(preparedStream, settings); + } + } + + /// + public ReadResult Read(MemoryStream input, + OpenApiReaderSettings settings = null) { JsonNode jsonNode; // Parse the YAML text in the TextReader into a sequence of JsonNodes try { - jsonNode = LoadJsonNodesFromYamlDocument(input); + jsonNode = LoadJsonNodesFromYamlDocument(new StreamReader(input)); // Should we leave the stream open? } catch (JsonException ex) { @@ -42,11 +59,11 @@ public async Task ReadAsync(TextReader input, }; } - return await ReadAsync(jsonNode, settings, cancellationToken: cancellationToken); + return Read(jsonNode, settings); } /// - public T ReadFragment(TextReader input, + public T ReadFragment(MemoryStream input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement @@ -56,7 +73,7 @@ public T ReadFragment(TextReader input, // Parse the YAML try { - jsonNode = LoadJsonNodesFromYamlDocument(input); + jsonNode = LoadJsonNodesFromYamlDocument(new StreamReader(input)); } catch (JsonException ex) { @@ -81,10 +98,10 @@ static JsonNode LoadJsonNodesFromYamlDocument(TextReader input) return yamlDocument.ToJsonNode(); } - /// - public async Task ReadAsync(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null, CancellationToken cancellationToken = default) + /// + public ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null) { - return await OpenApiReaderRegistry.DefaultReader.ReadAsync(jsonNode, settings, OpenApiConstants.Yaml, cancellationToken); + return OpenApiReaderRegistry.DefaultReader.Read(jsonNode, settings, OpenApiConstants.Yaml); } /// diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs index 5f8b1cb22..b746b857b 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs @@ -15,33 +15,40 @@ namespace Microsoft.OpenApi.Interfaces public interface IOpenApiReader { /// - /// Reads the TextReader input and parses it into an Open API document. + /// Async method to reads the stream and parse it into an Open API document. /// /// The TextReader input. /// The OpenApi reader settings. /// Propagates notification that an operation should be cancelled. /// - Task ReadAsync(TextReader input, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default); + Task ReadAsync(Stream input, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default); + + /// + /// Provides a synchronous method to read the input memory stream and parse it into an Open API document. + /// + /// + /// + /// + ReadResult Read(MemoryStream input, OpenApiReaderSettings settings = null); /// /// Parses the JsonNode input into an Open API document. /// /// The JsonNode input. /// The Reader settings to be used during parsing. - /// Propagates notifications that operations should be cancelled. /// The OpenAPI format. /// - Task ReadAsync(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null, CancellationToken cancellationToken = default); + ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null); /// - /// Reads the TextReader input and parses the fragment of an OpenAPI description into an Open API Element. + /// Reads the MemoryStream and parses the fragment of an OpenAPI description into an Open API Element. /// /// TextReader containing OpenAPI description to parse. /// Version of the OpenAPI specification that the fragment conforms to. /// Returns diagnostic object containing errors detected during parsing. /// The OpenApiReader settings. /// Instance of newly created IOpenApiElement. - T ReadFragment(TextReader input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement; + T ReadFragment(MemoryStream input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement; /// /// Reads the JsonNode input and parses the fragment of an OpenAPI description into an Open API Element. diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index bf8458f2c..a41e7ca6b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -553,27 +553,13 @@ public static ReadResult Load(string url, OpenApiReaderSettings? settings = null /// The OpenAPI format to use during parsing. /// The OpenApi reader settings. /// - public static ReadResult Load(Stream stream, + public static ReadResult Load(MemoryStream stream, string format, OpenApiReaderSettings? settings = null) { return OpenApiModelFactory.Load(stream, format, settings); } - /// - /// Reads the text reader content and parses it into an Open API document. - /// - /// TextReader containing OpenAPI description to parse. - /// The OpenAPI format to use during parsing. - /// The OpenApi reader settings. - /// - public static ReadResult Load(TextReader input, - string format, - OpenApiReaderSettings? settings = null) - { - return OpenApiModelFactory.Load(input, format, settings); - } - /// /// Parses a local file path or Url into an Open API document. /// @@ -598,17 +584,6 @@ public static async Task LoadAsync(Stream stream, string format, Ope return await OpenApiModelFactory.LoadAsync(stream, format, settings, cancellationToken); } - /// - /// Reads the text reader content and parses it into an Open API document. - /// - /// TextReader containing OpenAPI description to parse. - /// The OpenAPI format to use during parsing. - /// The OpenApi reader settings. - /// - public static async Task LoadAsync(TextReader input, string format, OpenApiReaderSettings? settings = null) - { - return await OpenApiModelFactory.LoadAsync(input, format, settings); - } /// /// Parses a string into a object. diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index 27aad722e..568c94832 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -24,14 +24,47 @@ namespace Microsoft.OpenApi.Reader /// public class OpenApiJsonReader : IOpenApiReader { + /// - /// Reads the stream input and parses it into an Open API document. + /// Reads the memory stream input and parses it into an Open API document. + /// + /// TextReader containing OpenAPI description to parse. + /// The Reader settings to be used during parsing. + /// + public ReadResult Read(MemoryStream input, + OpenApiReaderSettings settings = null) + { + JsonNode jsonNode; + var diagnostic = new OpenApiDiagnostic(); + settings ??= new OpenApiReaderSettings(); + + // Parse the JSON text in the TextReader into JsonNodes + try + { + jsonNode = JsonNode.Parse(input); + } + catch (JsonException ex) + { + diagnostic.Errors.Add(new OpenApiError($"#line={ex.LineNumber}", $"Please provide the correct format, {ex.Message}")); + return new ReadResult + { + OpenApiDocument = null, + OpenApiDiagnostic = diagnostic + }; + } + + return Read(jsonNode, settings); + } + + + /// + /// Reads the stream input asynchronously and parses it into an Open API document. /// /// TextReader containing OpenAPI description to parse. /// The Reader settings to be used during parsing. /// Propagates notifications that operations should be cancelled. /// - public async Task ReadAsync(TextReader input, + public async Task ReadAsync(Stream input, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) { @@ -42,7 +75,7 @@ public async Task ReadAsync(TextReader input, // Parse the JSON text in the TextReader into JsonNodes try { - jsonNode = LoadJsonNodes(input); + jsonNode = await JsonNode.ParseAsync(input);; } catch (JsonException ex) { @@ -54,7 +87,7 @@ public async Task ReadAsync(TextReader input, }; } - return await ReadAsync(jsonNode, settings, cancellationToken: cancellationToken); + return Read(jsonNode, settings); } /// @@ -63,12 +96,10 @@ public async Task ReadAsync(TextReader input, /// The JsonNode input. /// The Reader settings to be used during parsing. /// The OpenAPI format. - /// Propagates notifications that operations should be cancelled. /// - public async Task ReadAsync(JsonNode jsonNode, + public ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, - string format = null, - CancellationToken cancellationToken = default) + string format = null) { var diagnostic = new OpenApiDiagnostic(); var context = new ParsingContext(diagnostic) @@ -84,16 +115,16 @@ public async Task ReadAsync(JsonNode jsonNode, // Parse the OpenAPI Document document = context.Parse(jsonNode); - if (settings.LoadExternalRefs) - { - var diagnosticExternalRefs = await LoadExternalRefsAsync(document, cancellationToken, settings, format); - // Merge diagnostics of external reference - if (diagnosticExternalRefs != null) - { - diagnostic.Errors.AddRange(diagnosticExternalRefs.Errors); - diagnostic.Warnings.AddRange(diagnosticExternalRefs.Warnings); - } - } + // if (settings.LoadExternalRefs) + // { + // var diagnosticExternalRefs = await LoadExternalRefsAsync(document, cancellationToken, settings, format); + // // Merge diagnostics of external reference + // if (diagnosticExternalRefs != null) + // { + // diagnostic.Errors.AddRange(diagnosticExternalRefs.Errors); + // diagnostic.Warnings.AddRange(diagnosticExternalRefs.Warnings); + // } + // } document.SetReferenceHostDocument(); } @@ -124,7 +155,7 @@ public async Task ReadAsync(JsonNode jsonNode, } /// - public T ReadFragment(TextReader input, + public T ReadFragment(MemoryStream input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement @@ -134,7 +165,7 @@ public T ReadFragment(TextReader input, // Parse the JSON try { - jsonNode = LoadJsonNodes(input); + jsonNode = JsonNode.Parse(input); } catch (JsonException ex) { @@ -183,12 +214,6 @@ public T ReadFragment(JsonNode input, return (T)element; } - private JsonNode LoadJsonNodes(TextReader input) - { - var nodes = JsonNode.Parse(input.ReadToEnd()); - return nodes; - } - private async Task LoadExternalRefsAsync(OpenApiDocument document, CancellationToken cancellationToken, OpenApiReaderSettings settings, string format = null) { // Create workspace for all documents to live in. diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index ddabdc6be..ad5d09968 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -2,10 +2,12 @@ // Licensed under the MIT license. using System; +using System.Buffers.Text; using System.IO; using System.Linq; using System.Net.Http; using System.Security; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.OpenApi.Interfaces; @@ -45,15 +47,13 @@ public static ReadResult Load(string url, OpenApiReaderSettings settings = null) /// The OpenApi reader settings. /// The OpenAPI format. /// An OpenAPI document instance. - public static ReadResult Load(Stream stream, + public static ReadResult Load(MemoryStream stream, string format, OpenApiReaderSettings settings = null) { settings ??= new OpenApiReaderSettings(); -#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits - var result = LoadAsync(stream, format, settings).GetAwaiter().GetResult(); -#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits + var result = InternalLoad(stream, format, settings); if (!settings.LeaveStreamOpen) { @@ -63,22 +63,6 @@ public static ReadResult Load(Stream stream, return result; } - /// - /// Loads the TextReader input and parses it into an Open API document. - /// - /// The TextReader input. - /// The OpenApi reader settings. - /// The Open API format - /// An OpenAPI document instance. - public static ReadResult Load(TextReader input, - string format, - OpenApiReaderSettings settings = null) - { -#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits - var result = LoadAsync(input, format, settings).GetAwaiter().GetResult(); -#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits - return result; - } /// /// Loads the input URL and parses it into an Open API document. @@ -89,12 +73,12 @@ public static ReadResult Load(TextReader input, public static async Task LoadAsync(string url, OpenApiReaderSettings settings = null) { var format = GetFormat(url); - var stream = await GetStreamAsync(url); + var stream = await GetStreamAsync(url); // Get response back and then get Content return await LoadAsync(stream, format, settings); } /// - /// Loads the input stream and parses it into an Open API document. + /// Loads the input stream and parses it into an Open API document. If the stream is not buffered and it contains yaml, it will be buffered before parsing. /// /// The input stream. /// The OpenApi reader settings. @@ -122,24 +106,7 @@ public static async Task LoadAsync(Stream input, string format, Open } // Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON) - using var reader = new StreamReader(preparedStream, default, true, -1, settings.LeaveStreamOpen); - return await LoadAsync(reader, format, settings, cancellationToken); - } - - - /// - /// Loads the TextReader input and parses it into an Open API document. - /// - /// The TextReader input. - /// The Open API format - /// The OpenApi reader settings. - /// Propagates notification that operations should be cancelled. - /// - public static async Task LoadAsync(TextReader input, string format, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) - { - Utils.CheckArgumentNull(format, nameof(format)); - var reader = OpenApiReaderRegistry.GetReader(format); - return await reader.ReadAsync(input, settings, cancellationToken); + return await InternalLoadAsync(preparedStream, format, settings, cancellationToken); } /// @@ -155,29 +122,30 @@ public static ReadResult Parse(string input, { format ??= OpenApiConstants.Json; settings ??= new OpenApiReaderSettings(); - using var reader = new StringReader(input); -#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits - return ParseAsync(input, reader, format, settings).GetAwaiter().GetResult(); -#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits + // Copy string into MemoryStream + var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); + + return InternalLoad(stream, format, settings); } - /// - /// An Async method to prevent synchornously blocking the calling thread. - /// - /// - /// - /// - /// - /// - public static async Task ParseAsync(string input, - StringReader reader, - string format = null, - OpenApiReaderSettings settings = null) + private static async Task InternalLoadAsync(Stream input, string format, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) { - return await LoadAsync(reader, format, settings); + Utils.CheckArgumentNull(format, nameof(format)); + var reader = OpenApiReaderRegistry.GetReader(format); + var readResult = await reader.ReadAsync(input, settings, cancellationToken); + return readResult; } + private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings = null) + { + Utils.CheckArgumentNull(format, nameof(format)); + var reader = OpenApiReaderRegistry.GetReader(format); + var readResult = reader.Read(input, settings); + return readResult; + } + + /// /// Reads the input string and parses it into an Open API document. /// @@ -195,8 +163,8 @@ public static T Parse(string input, { format ??= OpenApiConstants.Json; settings ??= new OpenApiReaderSettings(); - using var reader = new StringReader(input); - return Load(reader, version, out diagnostic, format, settings); + var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); + return Load(stream, version, format, out diagnostic, settings); } /// @@ -218,45 +186,51 @@ public static T Load(string url, OpenApiSpecVersion version, out OpenApiDiagn var stream = GetStreamAsync(url).GetAwaiter().GetResult(); #pragma warning restore VSTHRD002 // Avoid problematic synchronous waits - return Load(stream, version, format, out diagnostic, settings); + return Load(stream as MemoryStream, version, format, out diagnostic, settings); } + /// - /// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element. + /// Reads the stream input and ensures it is buffered before passing it to the Load method. /// /// - /// Stream containing OpenAPI description to parse. - /// Version of the OpenAPI specification that the fragment conforms to. + /// + /// /// - /// Returns diagnostic object containing errors detected during parsing. - /// The OpenApiReader settings. - /// Instance of newly created IOpenApiElement. - /// The OpenAPI element. + /// + /// + /// public static T Load(Stream input, OpenApiSpecVersion version, string format, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement { - format ??= OpenApiConstants.Json; - using var reader = new StreamReader(input); - return Load(reader, version, out diagnostic, format, settings); + if (input is MemoryStream memoryStream) + { + return Load(memoryStream, version, format, out diagnostic, settings); + } else { + memoryStream = new MemoryStream(); + input.CopyTo(memoryStream); + memoryStream.Position = 0; + return Load(memoryStream, version, format, out diagnostic, settings); + } } + /// - /// Reads the TextReader input and parses the fragment of an OpenAPI description into an Open API Element. + /// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element. /// /// - /// TextReader containing OpenAPI description to parse. + /// Stream containing OpenAPI description to parse. /// Version of the OpenAPI specification that the fragment conforms to. - /// The OpenAPI format. + /// /// Returns diagnostic object containing errors detected during parsing. /// The OpenApiReader settings. /// Instance of newly created IOpenApiElement. /// The OpenAPI element. - public static T Load(TextReader input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, string format, OpenApiReaderSettings settings = null) where T : IOpenApiElement + public static T Load(MemoryStream input, OpenApiSpecVersion version, string format, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement { format ??= OpenApiConstants.Json; return OpenApiReaderRegistry.GetReader(format).ReadFragment(input, version, out diagnostic, settings); } - private static string GetContentType(string url) { if (!string.IsNullOrEmpty(url)) diff --git a/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiSchemaTests.cs index 967bb0f3e..e591ad6e4 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiSchemaTests.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.IO; using System.Text.Json.Nodes; @@ -18,6 +19,14 @@ public class OpenApiSchemaTests { private const string SampleFolderPath = "V31Tests/Samples/OpenApiSchema/"; + + public MemoryStream GetMemoryStream(string fileName) + { + var filePath = Path.Combine(SampleFolderPath, fileName); + var fileBytes = File.ReadAllBytes(filePath); + return new MemoryStream(fileBytes); + } + public OpenApiSchemaTests() { OpenApiReaderRegistry.RegisterReader("yaml", new OpenApiYamlReader()); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs index 6556ade48..bcbc6a02a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.IO; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Reader; @@ -20,13 +21,16 @@ public OpenApiDiscriminatorTests() } [Fact] - public void ParseBasicDiscriminatorShouldSucceed() + public async Task ParseBasicDiscriminatorShouldSucceed() { // Arrange using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicDiscriminator.yaml")); + // Copy stream to MemoryStream + using var memoryStream = new MemoryStream(); + await stream.CopyToAsync(memoryStream); // Act - var discriminator = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, OpenApiConstants.Yaml, out var diagnostic); + var discriminator = OpenApiModelFactory.Load(memoryStream, OpenApiSpecVersion.OpenApi3_0, OpenApiConstants.Yaml, out var diagnostic); // Assert discriminator.Should().BeEquivalentTo( From c9b01cbec2ecb367c4f64dc7c49cc782ec463d09 Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Tue, 26 Nov 2024 09:39:31 -0500 Subject: [PATCH 02/50] Moved load external references --- .../Reader/OpenApiJsonReader.cs | 12 +---- .../Reader/OpenApiModelFactory.cs | 44 ++++++++++++++++++- 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index 568c94832..d24d31b9d 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -214,16 +214,6 @@ public T ReadFragment(JsonNode input, return (T)element; } - private async Task LoadExternalRefsAsync(OpenApiDocument document, CancellationToken cancellationToken, OpenApiReaderSettings settings, string format = null) - { - // Create workspace for all documents to live in. - var baseUrl = settings.BaseUrl ?? new Uri(OpenApiConstants.BaseRegistryUri); - var openApiWorkSpace = new OpenApiWorkspace(baseUrl); - - // 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, format ?? OpenApiConstants.Json, null, cancellationToken); - } + } } diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index ad5d09968..2554c48a5 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -12,6 +12,8 @@ using System.Threading.Tasks; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Reader.Services; +using Microsoft.OpenApi.Services; namespace Microsoft.OpenApi.Reader { @@ -71,7 +73,16 @@ public static ReadResult Load(MemoryStream stream, /// The OpenApi reader settings. /// public static async Task LoadAsync(string url, OpenApiReaderSettings settings = null) - { + { + // If url is HTTP + // Get the response object. + // Select format based on MediaType + // Get the stream from the response object. + // Load the stream. + // Else + // Determine the format from the file extension. + // Load the file from the local file system. + var format = GetFormat(url); var stream = await GetStreamAsync(url); // Get response back and then get Content return await LoadAsync(stream, format, settings); @@ -134,14 +145,45 @@ private static async Task InternalLoadAsync(Stream input, string for Utils.CheckArgumentNull(format, nameof(format)); var reader = OpenApiReaderRegistry.GetReader(format); var readResult = await reader.ReadAsync(input, settings, cancellationToken); + + if (settings.LoadExternalRefs) + { + var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.OpenApiDocument, cancellationToken, settings, format); + // Merge diagnostics of external reference + if (diagnosticExternalRefs != null) + { + readResult.OpenApiDiagnostic.Errors.AddRange(diagnosticExternalRefs.Errors); + readResult.OpenApiDiagnostic.Warnings.AddRange(diagnosticExternalRefs.Warnings); + } + } + + return readResult; } + private static async Task LoadExternalRefsAsync(OpenApiDocument document, CancellationToken cancellationToken, OpenApiReaderSettings settings, string format = null) + { + // Create workspace for all documents to live in. + var baseUrl = settings.BaseUrl ?? new Uri(OpenApiConstants.BaseRegistryUri); + var openApiWorkSpace = new OpenApiWorkspace(baseUrl); + + // 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, format ?? OpenApiConstants.Json, null, cancellationToken); + } + private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings = null) { Utils.CheckArgumentNull(format, nameof(format)); + if (settings.LoadExternalRefs) + { + throw new InvalidOperationException("Loading external references are not supported when using synchronous methods."); + } + var reader = OpenApiReaderRegistry.GetReader(format); var readResult = reader.Read(input, settings); + return readResult; } From 1464e2cbde5a8db4372c267632f3b7c90f9fdf35 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Wed, 27 Nov 2024 17:28:17 +0300 Subject: [PATCH 03/50] Move load methods to be adjacent --- .../Reader/OpenApiModelFactory.cs | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 2554c48a5..0b7fadb7f 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.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,47 @@ public static ReadResult Load(MemoryStream stream, return result; } + /// + /// Reads the stream input and ensures it is buffered before passing it to the Load method. + /// + /// + /// + /// + /// + /// + /// + /// + public static T Load(Stream input, OpenApiSpecVersion version, string format, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement + { + if (input is MemoryStream memoryStream) + { + return Load(memoryStream, version, format, out diagnostic, settings); + } + else + { + memoryStream = new MemoryStream(); + input.CopyTo(memoryStream); + memoryStream.Position = 0; + return Load(memoryStream, version, format, out diagnostic, settings); + } + } + + /// + /// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element. + /// + /// + /// Stream containing OpenAPI description to parse. + /// Version of the OpenAPI specification that the fragment conforms to. + /// + /// Returns diagnostic object containing errors detected during parsing. + /// The OpenApiReader settings. + /// Instance of newly created IOpenApiElement. + /// The OpenAPI element. + public static T Load(MemoryStream input, OpenApiSpecVersion version, string format, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement + { + format ??= OpenApiConstants.Json; + return OpenApiReaderRegistry.GetReader(format).ReadFragment(input, version, out diagnostic, settings); + } /// /// Loads the input URL and parses it into an Open API document. From e5883775c5898005b82a057a19dae2e71c359d18 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Wed, 27 Nov 2024 17:29:06 +0300 Subject: [PATCH 04/50] Async over sync --- .../Reader/OpenApiModelFactory.cs | 42 ++++++++----------- 1 file changed, 17 insertions(+), 25 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 0b7fadb7f..9ffa9be2d 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -29,19 +29,6 @@ static OpenApiModelFactory() OpenApiReaderRegistry.RegisterReader(OpenApiConstants.Json, new OpenApiJsonReader()); } - /// - /// Loads the input URL and parses it into an Open API document. - /// - /// The path to the OpenAPI file. - /// The OpenApi reader settings. - /// An OpenAPI document instance. - public static ReadResult Load(string url, OpenApiReaderSettings settings = null) - { -#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits - return LoadAsync(url, settings).GetAwaiter().GetResult(); -#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits - } - /// /// Loads the input stream and parses it into an Open API document. /// @@ -114,19 +101,24 @@ public static T Load(MemoryStream input, OpenApiSpecVersion version, string f /// The OpenApi reader settings. /// public static async Task LoadAsync(string url, OpenApiReaderSettings settings = null) - { - // If url is HTTP - // Get the response object. - // Select format based on MediaType - // Get the stream from the response object. - // Load the stream. - // Else - // Determine the format from the file extension. - // Load the file from the local file system. + { + var result = await RetrieveStreamAndFormatAsync(url); + return await LoadAsync(result.Item1, result.Item2, settings); + } - var format = GetFormat(url); - var stream = await GetStreamAsync(url); // Get response back and then get Content - return await LoadAsync(stream, format, settings); + /// + /// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element. + /// + /// + /// The path to the OpenAPI file + /// Version of the OpenAPI specification that the fragment conforms to. + /// The OpenApiReader settings. + /// Instance of newly created IOpenApiElement. + /// The OpenAPI element. + public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null) where T : IOpenApiElement + { + var result = await RetrieveStreamAndFormatAsync(url); + return Load(result.Item1 as MemoryStream, version, result.Item2, out var diagnostic, settings); } /// From 47e3e253ec99d5d1f6eb87d1d2e2d940717beb13 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Wed, 27 Nov 2024 17:30:09 +0300 Subject: [PATCH 05/50] refactor code --- .../Reader/OpenApiModelFactory.cs | 211 +++++------------- 1 file changed, 56 insertions(+), 155 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 9ffa9be2d..65268394a 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.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; @@ -129,7 +129,7 @@ public static async Task LoadAsync(string url, OpenApiSpecVersion version, /// Propagates notification that operations should be cancelled. /// The Open API format /// - public static async Task LoadAsync(Stream input, string format, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) + public static async Task LoadAsync(Stream input, string format = null, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) { Utils.CheckArgumentNull(format, nameof(format)); settings ??= new OpenApiReaderSettings(); @@ -173,6 +173,27 @@ public static ReadResult Parse(string input, return InternalLoad(stream, format, settings); } + /// + /// Reads the input string and parses it into an Open API document. + /// + /// The input string. + /// + /// The diagnostic entity containing information from the reading process. + /// The Open API format + /// The OpenApi reader settings. + /// An OpenAPI document instance. + public static T Parse(string input, + OpenApiSpecVersion version, + out OpenApiDiagnostic diagnostic, + string format = null, + OpenApiReaderSettings settings = null) where T : IOpenApiElement + { + format ??= OpenApiConstants.Json; + settings ??= new OpenApiReaderSettings(); + var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); + return Load(stream, version, format, out diagnostic, settings); + } + private static async Task InternalLoadAsync(Stream input, string format, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) { Utils.CheckArgumentNull(format, nameof(format)); @@ -190,7 +211,6 @@ private static async Task InternalLoadAsync(Stream input, string for } } - return readResult; } @@ -220,168 +240,49 @@ private static ReadResult InternalLoad(MemoryStream input, string format, OpenAp return readResult; } - - /// - /// Reads the input string and parses it into an Open API document. - /// - /// The input string. - /// - /// The diagnostic entity containing information from the reading process. - /// The Open API format - /// The OpenApi reader settings. - /// An OpenAPI document instance. - public static T Parse(string input, - OpenApiSpecVersion version, - out OpenApiDiagnostic diagnostic, - string format = null, - OpenApiReaderSettings settings = null) where T : IOpenApiElement - { - format ??= OpenApiConstants.Json; - settings ??= new OpenApiReaderSettings(); - var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); - return Load(stream, version, format, out diagnostic, settings); - } - - /// - /// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element. - /// - /// - /// The path to the OpenAPI file - /// Version of the OpenAPI specification that the fragment conforms to. - /// Returns diagnostic object containing errors detected during parsing. - /// The OpenApiReader settings. - /// Instance of newly created IOpenApiElement. - /// The OpenAPI element. - public static T Load(string url, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement - { - var format = GetFormat(url); - settings ??= new OpenApiReaderSettings(); - -#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits - var stream = GetStreamAsync(url).GetAwaiter().GetResult(); -#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits - - return Load(stream as MemoryStream, version, format, out diagnostic, settings); - } - - - /// - /// Reads the stream input and ensures it is buffered before passing it to the Load method. - /// - /// - /// - /// - /// - /// - /// - /// - public static T Load(Stream input, OpenApiSpecVersion version, string format, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement - { - if (input is MemoryStream memoryStream) - { - return Load(memoryStream, version, format, out diagnostic, settings); - } else { - memoryStream = new MemoryStream(); - input.CopyTo(memoryStream); - memoryStream.Position = 0; - return Load(memoryStream, version, format, out diagnostic, settings); - } - } - - - /// - /// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element. - /// - /// - /// Stream containing OpenAPI description to parse. - /// Version of the OpenAPI specification that the fragment conforms to. - /// - /// Returns diagnostic object containing errors detected during parsing. - /// The OpenApiReader settings. - /// Instance of newly created IOpenApiElement. - /// The OpenAPI element. - public static T Load(MemoryStream input, OpenApiSpecVersion version, string format, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement - { - format ??= OpenApiConstants.Json; - return OpenApiReaderRegistry.GetReader(format).ReadFragment(input, version, out diagnostic, settings); - } - - private static string GetContentType(string url) + private static async Task<(Stream, string)> RetrieveStreamAndFormatAsync(string url) { if (!string.IsNullOrEmpty(url)) { -#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits - var response = _httpClient.GetAsync(url).GetAwaiter().GetResult(); -#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits - - var mediaType = response.Content.Headers.ContentType.MediaType; - return mediaType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First(); - } - - return null; - } + Stream stream; + string format; - /// - /// Infers the OpenAPI format from the input URL. - /// - /// The input URL. - /// The OpenAPI format. - public static string GetFormat(string url) - { - if (!string.IsNullOrEmpty(url)) - { - if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase) + || url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { - // URL examples ---> https://example.com/path/to/file.json, https://example.com/path/to/file.yaml - var path = new Uri(url); - var urlSuffix = path.Segments[path.Segments.Length - 1].Split('.').LastOrDefault(); - - return !string.IsNullOrEmpty(urlSuffix) ? urlSuffix : GetContentType(url).Split('/').LastOrDefault(); + var response = await _httpClient.GetAsync(url); + var mediaType = response.Content.Headers.ContentType.MediaType; + var contentType = mediaType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0]; + format = contentType.Split('/').LastOrDefault(); + stream = await response.Content.ReadAsStreamAsync(); + return (stream, format); } else { - return Path.GetExtension(url).Split('.').LastOrDefault(); + format = Path.GetExtension(url).Split('.').LastOrDefault(); + + try + { + var fileInput = new FileInfo(url); + stream = fileInput.OpenRead(); + } + 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 {url}", ex); + } + + return (stream, format); } } - return null; - } - - private static async Task GetStreamAsync(string url) - { - Stream stream; - if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - try - { - stream = await _httpClient.GetStreamAsync(new Uri(url)); - } - catch (HttpRequestException ex) - { - throw new InvalidOperationException($"Could not download the file at {url}", ex); - } - } - else - { - try - { - var fileInput = new FileInfo(url); - stream = fileInput.OpenRead(); - } - 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 {url}", ex); - } - } - - return stream; + return (null, null); } } } From 85210821e1d6a24d04e322597ad5497fbd3673ea Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 28 Nov 2024 12:16:06 +0300 Subject: [PATCH 06/50] Use the provided format in hidi options --- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 24 ++++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 7dfb5d797..b100eafb1 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -66,7 +66,7 @@ public static async Task TransformOpenApiDocumentAsync(HidiOptions options, ILog #pragma warning restore CA1308 // Normalize strings to uppercase options.Output = new($"./output{inputExtension}"); - }; + } if (options.CleanOutput && options.Output.Exists) { @@ -97,8 +97,7 @@ public static async Task TransformOpenApiDocumentAsync(HidiOptions options, ILog } // Load OpenAPI document - var format = OpenApiModelFactory.GetFormat(options.OpenApi); - var document = await GetOpenApiAsync(options, format, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false); + var document = await GetOpenApiAsync(options, openApiFormat.GetDisplayName(), logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false); if (options.FilterOptions != null) { @@ -254,7 +253,7 @@ private static async Task GetOpenApiAsync(HidiOptions options, else if (!string.IsNullOrEmpty(options.OpenApi)) { stream = await GetStreamAsync(options.OpenApi, logger, cancellationToken).ConfigureAwait(false); - var result = await ParseOpenApiAsync(options.OpenApi, options.InlineExternal, logger, stream, cancellationToken).ConfigureAwait(false); + var result = await ParseOpenApiAsync(options.OpenApi, format, options.InlineExternal, logger, stream, cancellationToken).ConfigureAwait(false); document = result.OpenApiDocument; } else throw new InvalidOperationException("No input file path or URL provided"); @@ -351,8 +350,8 @@ private static MemoryStream ApplyFilterToCsdl(Stream csdlStream, string entitySe try { using var stream = await GetStreamAsync(openApi, logger, cancellationToken).ConfigureAwait(false); - - result = await ParseOpenApiAsync(openApi, false, logger, stream, cancellationToken).ConfigureAwait(false); + var openApiFormat = !string.IsNullOrEmpty(openApi) ? GetOpenApiFormat(openApi, logger) : OpenApiFormat.Yaml; + result = await ParseOpenApiAsync(openApi, openApiFormat.GetDisplayName(),false, logger, stream, cancellationToken).ConfigureAwait(false); using (logger.BeginScope("Calculating statistics")) { @@ -380,7 +379,7 @@ private static MemoryStream ApplyFilterToCsdl(Stream csdlStream, string entitySe return result.OpenApiDiagnostic.Errors.Count == 0; } - private static async Task ParseOpenApiAsync(string openApiFile, bool inlineExternal, ILogger logger, Stream stream, CancellationToken cancellationToken = default) + private static async Task ParseOpenApiAsync(string openApiFile, string format, bool inlineExternal, ILogger logger, Stream stream, CancellationToken cancellationToken = default) { ReadResult result; var stopwatch = Stopwatch.StartNew(); @@ -396,7 +395,6 @@ private static async Task ParseOpenApiAsync(string openApiFile, bool new Uri("file://" + new FileInfo(openApiFile).DirectoryName + Path.DirectorySeparatorChar) }; - var format = OpenApiModelFactory.GetFormat(openApiFile); result = await OpenApiDocument.LoadAsync(stream, format, settings, cancellationToken).ConfigureAwait(false); logger.LogTrace("{Timestamp}ms: Completed parsing.", stopwatch.ElapsedMilliseconds); @@ -587,8 +585,8 @@ private static string GetInputPathExtension(string? openapi = null, string? csdl throw new ArgumentException("Please input a file path or URL"); } - var format = OpenApiModelFactory.GetFormat(options.OpenApi); - var document = await GetOpenApiAsync(options, format, logger, null, cancellationToken).ConfigureAwait(false); + var openApiFormat = options.OpenApiFormat ?? (!string.IsNullOrEmpty(options.OpenApi) ? GetOpenApiFormat(options.OpenApi, logger) : OpenApiFormat.Yaml); + var document = await GetOpenApiAsync(options, openApiFormat.GetDisplayName(), logger, null, cancellationToken).ConfigureAwait(false); using (logger.BeginScope("Creating diagram")) { @@ -748,9 +746,11 @@ internal static async Task PluginManifestAsync(HidiOptions options, ILogger logg options.OpenApi = apiDependency.ApiDescripionUrl; } + var openApiFormat = options.OpenApiFormat ?? (!string.IsNullOrEmpty(options.OpenApi) + ? GetOpenApiFormat(options.OpenApi, logger) : OpenApiFormat.Yaml); + // Load OpenAPI document - var format = OpenApiModelFactory.GetFormat(options.OpenApi); - var document = await GetOpenApiAsync(options, format, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false); + var document = await GetOpenApiAsync(options, openApiFormat.GetDisplayName(), logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); From 99a80b986c8e76a41a496f9d4b4f9bac378dd607 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 28 Nov 2024 12:18:28 +0300 Subject: [PATCH 07/50] Clean up tests; refactor to use async --- .../Models/OpenApiDocument.cs | 13 +---- .../Services/OpenApiFilterServiceTests.cs | 4 +- .../OpenApiDiagnosticTests.cs | 8 +-- .../OpenApiStreamReaderTests.cs | 12 ++-- .../UnsupportedSpecVersionTests.cs | 5 +- .../TryLoadReferenceV2Tests.cs | 17 +++--- .../V2Tests/ComparisonTests.cs | 9 +-- .../V2Tests/OpenApiDocumentTests.cs | 22 +++---- .../V31Tests/OpenApiDocumentTests.cs | 29 +++++----- .../V31Tests/OpenApiSchemaTests.cs | 45 +++++++------- .../V3Tests/OpenApiCallbackTests.cs | 15 +++-- .../V3Tests/OpenApiDocumentTests.cs | 58 +++++++++---------- .../V3Tests/OpenApiEncodingTests.cs | 5 +- .../V3Tests/OpenApiExampleTests.cs | 14 ++--- .../V3Tests/OpenApiInfoTests.cs | 9 +-- .../V3Tests/OpenApiMediaTypeTests.cs | 9 +-- .../V3Tests/OpenApiOperationTests.cs | 11 ++-- .../V3Tests/OpenApiParameterTests.cs | 25 ++++---- .../V3Tests/OpenApiResponseTests.cs | 5 +- .../V3Tests/OpenApiSchemaTests.cs | 24 ++++---- .../V3Tests/OpenApiSecuritySchemeTests.cs | 21 +++---- .../Models/OpenApiDocumentTests.cs | 26 ++++----- 22 files changed, 186 insertions(+), 200 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index a41e7ca6b..13de5f7f8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -137,7 +137,7 @@ public void SerializeAsV31(IOpenApiWriter writer) writer.WriteStartObject(); - // openApi; + // openApi writer.WriteProperty(OpenApiConstants.OpenApi, "3.1.1"); // jsonSchemaDialect @@ -535,17 +535,6 @@ private static string ConvertByteArrayToString(byte[] hash) return Workspace?.ResolveReference(uriLocation); } - /// - /// Parses a local file path or Url into an Open API document. - /// - /// The path to the OpenAPI file. - /// - /// - public static ReadResult Load(string url, OpenApiReaderSettings? settings = null) - { - return OpenApiModelFactory.Load(url, settings); - } - /// /// Reads the stream input and parses it into an Open API document. /// diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs index 3bd9efd2a..602a69021 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs @@ -224,7 +224,7 @@ public void ThrowsInvalidOperationExceptionInCreatePredicateWhenInvalidArguments } [Fact] - public void CopiesOverAllReferencedComponentsToTheSubsetDocumentCorrectly() + public async Task CopiesOverAllReferencedComponentsToTheSubsetDocumentCorrectly() { // Arrange var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UtilityFiles", "docWithReusableHeadersAndExamples.yaml"); @@ -232,7 +232,7 @@ public void CopiesOverAllReferencedComponentsToTheSubsetDocumentCorrectly() // Act using var stream = File.OpenRead(filePath); - var doc = OpenApiDocument.Load(stream, "yaml").OpenApiDocument; + var doc = (await OpenApiDocument.LoadAsync(stream, "yaml")).OpenApiDocument; var predicate = OpenApiFilterService.CreatePredicate(operationIds: operationIds); var subsetOpenApiDocument = OpenApiFilterService.CreateFilteredDocument(doc, predicate); diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs index c99cc6fa9..58e6e7cb0 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs @@ -23,18 +23,18 @@ public OpenApiDiagnosticTests() } [Fact] - public void DetectedSpecificationVersionShouldBeV2_0() + public async Task DetectedSpecificationVersionShouldBeV2_0() { - var actual = OpenApiDocument.Load("V2Tests/Samples/basic.v2.yaml"); + var actual = await OpenApiDocument.LoadAsync("V2Tests/Samples/basic.v2.yaml"); actual.OpenApiDiagnostic.Should().NotBeNull(); actual.OpenApiDiagnostic.SpecificationVersion.Should().Be(OpenApiSpecVersion.OpenApi2_0); } [Fact] - public void DetectedSpecificationVersionShouldBeV3_0() + public async Task DetectedSpecificationVersionShouldBeV3_0() { - var actual = OpenApiDocument.Load("V3Tests/Samples/OpenApiDocument/minimalDocument.yaml"); + var actual = await OpenApiDocument.LoadAsync("V3Tests/Samples/OpenApiDocument/minimalDocument.yaml"); actual.OpenApiDiagnostic.Should().NotBeNull(); actual.OpenApiDiagnostic.SpecificationVersion.Should().Be(OpenApiSpecVersion.OpenApi3_0); diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs index 82a410946..91407f0b7 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs @@ -21,20 +21,20 @@ public OpenApiStreamReaderTests() } [Fact] - public void StreamShouldCloseIfLeaveStreamOpenSettingEqualsFalse() + public async Task StreamShouldCloseIfLeaveStreamOpenSettingEqualsFalse() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml")); var settings = new OpenApiReaderSettings { LeaveStreamOpen = false }; - _ = OpenApiDocument.Load(stream, "yaml", settings); + _ = await OpenApiDocument.LoadAsync(stream, "yaml", settings); Assert.False(stream.CanRead); } [Fact] - public void StreamShouldNotCloseIfLeaveStreamOpenSettingEqualsTrue() + public async Task StreamShouldNotCloseIfLeaveStreamOpenSettingEqualsTrue() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml")); var settings = new OpenApiReaderSettings { LeaveStreamOpen = true }; - _ = OpenApiDocument.Load(stream, "yaml", settings); + _ = await OpenApiDocument.LoadAsync(stream, "yaml", settings); Assert.True(stream.CanRead); } @@ -48,7 +48,7 @@ public async Task StreamShouldNotBeDisposedIfLeaveStreamOpenSettingIsTrueAsync() memoryStream.Position = 0; var stream = memoryStream; - var result = OpenApiDocument.Load(stream, "yaml", new OpenApiReaderSettings { LeaveStreamOpen = true }); + _ = await OpenApiDocument.LoadAsync(stream, "yaml", new OpenApiReaderSettings { LeaveStreamOpen = true }); stream.Seek(0, SeekOrigin.Begin); // does not throw an object disposed exception Assert.True(stream.CanRead); } @@ -64,7 +64,7 @@ public async Task StreamShouldReadWhenInitializedAsync() var stream = await httpClient.GetStreamAsync("20fe7a7b720a0e48e5842d002ac418b12a8201df/tests/v3.0/pass/petstore.yaml"); // Read V3 as YAML - var result = OpenApiDocument.Load(stream, "yaml"); + var result = await OpenApiDocument.LoadAsync(stream, "yaml"); Assert.NotNull(result.OpenApiDocument); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs index 0b044e78b..1f6cbb7e8 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/UnsupportedSpecVersionTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Models; @@ -12,11 +13,11 @@ namespace Microsoft.OpenApi.Readers.Tests.OpenApiReaderTests public class UnsupportedSpecVersionTests { [Fact] - public void ThrowOpenApiUnsupportedSpecVersionException() + public async Task ThrowOpenApiUnsupportedSpecVersionException() { try { - _ = OpenApiDocument.Load("OpenApiReaderTests/Samples/unsupported.v1.yaml"); + _ = await OpenApiDocument.LoadAsync("OpenApiReaderTests/Samples/unsupported.v1.yaml"); } catch (OpenApiUnsupportedSpecVersionException exception) { diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs index d6fb3b8ba..04577149e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.References; @@ -22,10 +23,10 @@ public TryLoadReferenceV2Tests() } [Fact] - public void LoadParameterReference() + public async Task LoadParameterReference() { // Arrange - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")); var reference = new OpenApiParameterReference("skipParam", result.OpenApiDocument); // Assert @@ -47,9 +48,9 @@ public void LoadParameterReference() } [Fact] - public void LoadSecuritySchemeReference() + public async Task LoadSecuritySchemeReference() { - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")); var reference = new OpenApiSecuritySchemeReference("api_key_sample", result.OpenApiDocument); @@ -65,9 +66,9 @@ public void LoadSecuritySchemeReference() } [Fact] - public void LoadResponseReference() + public async Task LoadResponseReference() { - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")); var reference = new OpenApiResponseReference("NotFound", result.OpenApiDocument); @@ -85,9 +86,9 @@ public void LoadResponseReference() } [Fact] - public void LoadResponseAndSchemaReference() + public async Task LoadResponseAndSchemaReference() { - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")); var reference = new OpenApiResponseReference("GeneralError", result.OpenApiDocument); // Assert diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs index b3e30c672..150c4c585 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/ComparisonTests.cs @@ -1,7 +1,8 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System.IO; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Reader; @@ -18,13 +19,13 @@ public class ComparisonTests [InlineData("minimal")] [InlineData("basic")] //[InlineData("definitions")] //Currently broken due to V3 references not behaving the same as V2 - public void EquivalentV2AndV3DocumentsShouldProduceEquivalentObjects(string fileName) + public async Task EquivalentV2AndV3DocumentsShouldProduceEquivalentObjects(string fileName) { OpenApiReaderRegistry.RegisterReader(OpenApiConstants.Yaml, new OpenApiYamlReader()); using var streamV2 = Resources.GetStream(Path.Combine(SampleFolderPath, $"{fileName}.v2.yaml")); using var streamV3 = Resources.GetStream(Path.Combine(SampleFolderPath, $"{fileName}.v3.yaml")); - var result1 = OpenApiDocument.Load(Path.Combine(SampleFolderPath, $"{fileName}.v2.yaml")); - var result2 = OpenApiDocument.Load(Path.Combine(SampleFolderPath, $"{fileName}.v3.yaml")); + var result1 = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, $"{fileName}.v2.yaml")); + var result2 = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, $"{fileName}.v3.yaml")); result2.OpenApiDocument.Should().BeEquivalentTo(result1.OpenApiDocument, options => options.Excluding(x => x.Workspace).Excluding(y => y.BaseUri)); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index c97fd1aee..a4786325e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Equivalency; using Microsoft.OpenApi.Any; @@ -96,13 +97,13 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) .Excluding((IMemberInfo memberInfo) => memberInfo.Path.EndsWith("Parent")) .Excluding((IMemberInfo memberInfo) => - memberInfo.Path.EndsWith("Root")));; + memberInfo.Path.EndsWith("Root"))); } [Fact] - public void ShouldParseProducesInAnyOrder() + public async Task ShouldParseProducesInAnyOrder() { - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "twoResponses.json")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "twoResponses.json")); var okSchema = new OpenApiSchema { @@ -259,10 +260,10 @@ public void ShouldParseProducesInAnyOrder() } [Fact] - public void ShouldAssignSchemaToAllResponses() + public async Task ShouldAssignSchemaToAllResponses() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleProduces.json")); - var result = OpenApiDocument.Load(stream, OpenApiConstants.Json); + var result = await OpenApiDocument.LoadAsync(stream, OpenApiConstants.Json); Assert.Equal(OpenApiSpecVersion.OpenApi2_0, result.OpenApiDiagnostic.SpecificationVersion); @@ -289,10 +290,10 @@ public void ShouldAssignSchemaToAllResponses() } [Fact] - public void ShouldAllowComponentsThatJustContainAReference() + public async Task ShouldAllowComponentsThatJustContainAReference() { // Act - var actual = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "ComponentRootReference.json")).OpenApiDocument; + var actual = (await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "ComponentRootReference.json"))).OpenApiDocument; var schema1 = actual.Components.Schemas["AllPets"]; Assert.False(schema1.UnresolvedReference); var schema2 = actual.ResolveReferenceTo(schema1.Reference); @@ -304,14 +305,14 @@ public void ShouldAllowComponentsThatJustContainAReference() } [Fact] - public void ParseDocumentWithDefaultContentTypeSettingShouldSucceed() + public async Task ParseDocumentWithDefaultContentTypeSettingShouldSucceed() { var settings = new OpenApiReaderSettings { DefaultContentType = ["application/json"] }; - var actual = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "docWithEmptyProduces.yaml"), settings); + var actual = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "docWithEmptyProduces.yaml"), settings); var mediaType = actual.OpenApiDocument.Paths["/example"].Operations[OperationType.Get].Responses["200"].Content; Assert.Contains("application/json", mediaType); } @@ -320,8 +321,7 @@ public void ParseDocumentWithDefaultContentTypeSettingShouldSucceed() public void testContentType() { var contentType = "application/json; charset = utf-8"; - var res = contentType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First(); - var expected = res.Split('/').LastOrDefault(); + var res = contentType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0]; Assert.Equal("application/json", res); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiDocumentTests.cs index 638d69667..4a0bdb607 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiDocumentTests.cs @@ -26,10 +26,10 @@ public OpenApiDocumentTests() } [Fact] - public void ParseDocumentWithWebhooksShouldSucceed() + public async Task ParseDocumentWithWebhooksShouldSucceed() { // Arrange and Act - var actual = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "documentWithWebhooks.yaml")); + var actual = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "documentWithWebhooks.yaml")); var petSchema = new OpenApiSchemaReference("petSchema", actual.OpenApiDocument); var newPetSchema = new OpenApiSchemaReference("newPetSchema", actual.OpenApiDocument); @@ -205,10 +205,10 @@ public void ParseDocumentWithWebhooksShouldSucceed() } [Fact] - public void ParseDocumentsWithReusablePathItemInWebhooksSucceeds() + public async Task ParseDocumentsWithReusablePathItemInWebhooksSucceeds() { // Arrange && Act - var actual = OpenApiDocument.Load("V31Tests/Samples/OpenApiDocument/documentWithReusablePaths.yaml"); + var actual = await OpenApiDocument.LoadAsync("V31Tests/Samples/OpenApiDocument/documentWithReusablePaths.yaml"); var components = new OpenApiComponents { @@ -397,18 +397,17 @@ public void ParseDocumentsWithReusablePathItemInWebhooksSucceeds() var outputWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputWriter, new() { InlineLocalReferences = true }); actual.OpenApiDocument.SerializeAsV31(writer); - var serialized = outputWriter.ToString(); } [Fact] - public void ParseDocumentWithExampleInSchemaShouldSucceed() + public async Task ParseDocumentWithExampleInSchemaShouldSucceed() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = false }); // Act - var actual = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "docWithExample.yaml")); + var actual = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "docWithExample.yaml")); actual.OpenApiDocument.SerializeAsV31(writer); // Assert @@ -416,10 +415,10 @@ public void ParseDocumentWithExampleInSchemaShouldSucceed() } [Fact] - public void ParseDocumentWithPatternPropertiesInSchemaWorks() + public async Task ParseDocumentWithPatternPropertiesInSchemaWorks() { // Arrange and Act - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "docWithPatternPropertiesInSchema.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "docWithPatternPropertiesInSchema.yaml")); var actualSchema = result.OpenApiDocument.Paths["/example"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema; var expectedSchema = new OpenApiSchema @@ -473,10 +472,10 @@ public void ParseDocumentWithPatternPropertiesInSchemaWorks() } [Fact] - public void ParseDocumentWithReferenceByIdGetsResolved() + public async Task ParseDocumentWithReferenceByIdGetsResolved() { // Arrange and Act - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "docWithReferenceById.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "docWithReferenceById.yaml")); var responseSchema = result.OpenApiDocument.Paths["/resource"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema; var requestBodySchema = result.OpenApiDocument.Paths["/resource"].Operations[OperationType.Post].RequestBody.Content["application/json"].Schema; @@ -523,9 +522,9 @@ public async Task ParseExternalDocumentDereferenceToOpenApiDocumentByIdWorks() // Act var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "externalRefById.yaml"), settings); - var doc2 = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "externalResource.yaml")).OpenApiDocument; + var doc2 = (await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "externalResource.yaml"))).OpenApiDocument; - var requestBodySchema = result.OpenApiDocument.Paths["/resource"].Operations[OperationType.Get].Parameters.First().Schema; + var requestBodySchema = result.OpenApiDocument.Paths["/resource"].Operations[OperationType.Get].Parameters[0].Schema; result.OpenApiDocument.Workspace.RegisterComponents(doc2); // Assert @@ -536,10 +535,10 @@ public async Task ParseExternalDocumentDereferenceToOpenApiDocumentByIdWorks() public async Task ParseDocumentWith31PropertiesWorks() { var path = Path.Combine(SampleFolderPath, "documentWith31Properties.yaml"); - var doc = OpenApiDocument.Load(path).OpenApiDocument; + var doc = (await OpenApiDocument.LoadAsync(path)).OpenApiDocument; var outputStringWriter = new StringWriter(); doc.SerializeAsV31(new OpenApiYamlWriter(outputStringWriter)); - outputStringWriter.Flush(); + await outputStringWriter.FlushAsync(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert diff --git a/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiSchemaTests.cs index 731c33f2c..b1ab968a1 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiSchemaTests.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Text.Json.Nodes; +using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Equivalency; using Microsoft.OpenApi.Models; @@ -20,7 +21,7 @@ public class OpenApiSchemaTests private const string SampleFolderPath = "V31Tests/Samples/OpenApiSchema/"; - public MemoryStream GetMemoryStream(string fileName) + public static MemoryStream GetMemoryStream(string fileName) { var filePath = Path.Combine(SampleFolderPath, fileName); var fileBytes = File.ReadAllBytes(filePath); @@ -33,7 +34,7 @@ public OpenApiSchemaTests() } [Fact] - public void ParseBasicV31SchemaShouldSucceed() + public async Task ParseBasicV31SchemaShouldSucceed() { var expectedObject = new OpenApiSchema() { @@ -84,8 +85,8 @@ public void ParseBasicV31SchemaShouldSucceed() }; // Act - var schema = OpenApiModelFactory.Load( - System.IO.Path.Combine(SampleFolderPath, "jsonSchema.json"), OpenApiSpecVersion.OpenApi3_1, out _); + var schema = await OpenApiModelFactory.LoadAsync( + System.IO.Path.Combine(SampleFolderPath, "jsonSchema.json"), OpenApiSpecVersion.OpenApi3_1); // Assert schema.Should().BeEquivalentTo(expectedObject); @@ -155,12 +156,12 @@ public void TestSchemaCopyConstructorWithTypeArrayWorks() } [Fact] - public void ParseV31SchemaShouldSucceed() + public async Task ParseV31SchemaShouldSucceed() { var path = Path.Combine(SampleFolderPath, "schema.yaml"); // Act - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi3_1, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi3_1); var expectedSchema = new OpenApiSchema { Type = JsonSchemaType.Object, @@ -179,11 +180,11 @@ public void ParseV31SchemaShouldSucceed() } [Fact] - public void ParseAdvancedV31SchemaShouldSucceed() + public async Task ParseAdvancedV31SchemaShouldSucceed() { // Arrange and Act var path = Path.Combine(SampleFolderPath, "advancedSchema.yaml"); - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi3_1, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi3_1); var expectedSchema = new OpenApiSchema { @@ -304,7 +305,7 @@ public void CloningSchemaWithExamplesAndEnumsShouldSucceed() } [Fact] - public void SerializeV31SchemaWithMultipleTypesAsV3Works() + public async Task SerializeV31SchemaWithMultipleTypesAsV3Works() { // Arrange var expected = @"type: string @@ -313,7 +314,7 @@ public void SerializeV31SchemaWithMultipleTypesAsV3Works() var path = Path.Combine(SampleFolderPath, "schemaWithTypeArray.yaml"); // Act - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi3_1, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi3_1); var writer = new StringWriter(); schema.SerializeAsV3(new OpenApiYamlWriter(writer)); @@ -323,7 +324,7 @@ public void SerializeV31SchemaWithMultipleTypesAsV3Works() } [Fact] - public void SerializeV31SchemaWithMultipleTypesAsV2Works() + public async Task SerializeV31SchemaWithMultipleTypesAsV2Works() { // Arrange var expected = @"type: string @@ -332,7 +333,7 @@ public void SerializeV31SchemaWithMultipleTypesAsV2Works() var path = Path.Combine(SampleFolderPath, "schemaWithTypeArray.yaml"); // Act - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi3_1, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi3_1); var writer = new StringWriter(); schema.SerializeAsV2(new OpenApiYamlWriter(writer)); @@ -342,7 +343,7 @@ public void SerializeV31SchemaWithMultipleTypesAsV2Works() } [Fact] - public void SerializeV3SchemaWithNullableAsV31Works() + public async Task SerializeV3SchemaWithNullableAsV31Works() { // Arrange var expected = @"type: @@ -352,7 +353,7 @@ public void SerializeV3SchemaWithNullableAsV31Works() var path = Path.Combine(SampleFolderPath, "schemaWithNullable.yaml"); // Act - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi3_0, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi3_0); var writer = new StringWriter(); schema.SerializeAsV31(new OpenApiYamlWriter(writer)); @@ -362,7 +363,7 @@ public void SerializeV3SchemaWithNullableAsV31Works() } [Fact] - public void SerializeV2SchemaWithNullableExtensionAsV31Works() + public async Task SerializeV2SchemaWithNullableExtensionAsV31Works() { // Arrange var expected = @"type: @@ -373,7 +374,7 @@ public void SerializeV2SchemaWithNullableExtensionAsV31Works() var path = Path.Combine(SampleFolderPath, "schemaWithNullableExtension.yaml"); // Act - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi2_0, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi2_0); var writer = new StringWriter(); schema.SerializeAsV31(new OpenApiYamlWriter(writer)); @@ -404,20 +405,20 @@ public void SerializeSchemaWithTypeArrayAndNullableDoesntEmitType() [Theory] [InlineData("schemaWithNullable.yaml")] [InlineData("schemaWithNullableExtension.yaml")] - public void LoadSchemaWithNullableExtensionAsV31Works(string filePath) + public async Task LoadSchemaWithNullableExtensionAsV31Works(string filePath) { // Arrange var path = Path.Combine(SampleFolderPath, filePath); // Act - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi3_1, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi3_1); // Assert schema.Type.Should().Be(JsonSchemaType.String | JsonSchemaType.Null); } [Fact] - public void SerializeSchemaWithJsonSchemaKeywordsWorks() + public async Task SerializeSchemaWithJsonSchemaKeywordsWorks() { // Arrange var expected = @"$id: https://example.com/schemas/person.schema.yaml @@ -450,7 +451,7 @@ public void SerializeSchemaWithJsonSchemaKeywordsWorks() var path = Path.Combine(SampleFolderPath, "schemaWithJsonSchemaKeywords.yaml"); // Act - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi3_1, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi3_1); // serialization var writer = new StringWriter(); @@ -463,7 +464,7 @@ public void SerializeSchemaWithJsonSchemaKeywordsWorks() } [Fact] - public void ParseSchemaWithConstWorks() + public async Task ParseSchemaWithConstWorks() { var expected = @"{ ""$schema"": ""https://json-schema.org/draft/2020-12/schema"", @@ -494,7 +495,7 @@ public void ParseSchemaWithConstWorks() var path = Path.Combine(SampleFolderPath, "schemaWithConst.json"); // Act - var schema = OpenApiModelFactory.Load(path, OpenApiSpecVersion.OpenApi3_1, out _); + var schema = await OpenApiModelFactory.LoadAsync(path, OpenApiSpecVersion.OpenApi3_1); schema.Properties["status"].Const.Should().Be("active"); schema.Properties["user"].Properties["role"].Const.Should().Be("admin"); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs index cab621c14..54b468c47 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Expressions; using Microsoft.OpenApi.Models; @@ -21,14 +22,12 @@ public OpenApiCallbackTests() } [Fact] - public void ParseBasicCallbackShouldSucceed() + public async Task ParseBasicCallbackShouldSucceed() { // Act - var callback = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "basicCallback.yaml"), OpenApiSpecVersion.OpenApi3_0, out var diagnostic); + var callback = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "basicCallback.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert - diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); - callback.Should().BeEquivalentTo( new OpenApiCallback { @@ -64,12 +63,12 @@ public void ParseBasicCallbackShouldSucceed() } [Fact] - public void ParseCallbackWithReferenceShouldSucceed() + public async Task ParseCallbackWithReferenceShouldSucceed() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "callbackWithReference.yaml")); // Act - var result = OpenApiModelFactory.Load(stream, OpenApiConstants.Yaml); + var result = await OpenApiModelFactory.LoadAsync(stream, OpenApiConstants.Yaml); // Assert var path = result.OpenApiDocument.Paths.First().Value; @@ -122,10 +121,10 @@ public void ParseCallbackWithReferenceShouldSucceed() } [Fact] - public void ParseMultipleCallbacksWithReferenceShouldSucceed() + public async Task ParseMultipleCallbacksWithReferenceShouldSucceed() { // Act - var result = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "multipleCallbacksWithReference.yaml")); + var result = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "multipleCallbacksWithReference.yaml")); // Assert var path = result.OpenApiDocument.Paths.First().Value; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 2d3b02820..fa6a4dee4 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.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; @@ -106,10 +107,10 @@ public void ParseDocumentFromInlineStringShouldSucceed() } [Fact] - public void ParseBasicDocumentWithMultipleServersShouldSucceed() + public async Task ParseBasicDocumentWithMultipleServersShouldSucceed() { var path = System.IO.Path.Combine(SampleFolderPath, "basicDocumentWithMultipleServers.yaml"); - var result = OpenApiDocument.Load(path); + var result = await OpenApiDocument.LoadAsync(path); result.OpenApiDiagnostic.Errors.Should().BeEmpty(); result.OpenApiDocument.Should().BeEquivalentTo( @@ -137,10 +138,10 @@ public void ParseBasicDocumentWithMultipleServersShouldSucceed() }, options => options.Excluding(x => x.Workspace).Excluding(y => y.BaseUri)); } [Fact] - public void ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() + public async Task ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() { using var stream = Resources.GetStream(System.IO.Path.Combine(SampleFolderPath, "brokenMinimalDocument.yaml")); - var result = OpenApiDocument.Load(stream, OpenApiConstants.Yaml); + var result = await OpenApiDocument.LoadAsync(stream, OpenApiConstants.Yaml); result.OpenApiDocument.Should().BeEquivalentTo( new OpenApiDocument @@ -164,9 +165,9 @@ public void ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() } [Fact] - public void ParseMinimalDocumentShouldSucceed() + public async Task ParseMinimalDocumentShouldSucceed() { - var result = OpenApiDocument.Load(System.IO.Path.Combine(SampleFolderPath, "minimalDocument.yaml")); + var result = await OpenApiDocument.LoadAsync(System.IO.Path.Combine(SampleFolderPath, "minimalDocument.yaml")); result.OpenApiDocument.Should().BeEquivalentTo( new OpenApiDocument @@ -187,10 +188,10 @@ public void ParseMinimalDocumentShouldSucceed() } [Fact] - public void ParseStandardPetStoreDocumentShouldSucceed() + public async Task ParseStandardPetStoreDocumentShouldSucceed() { using var stream = Resources.GetStream(System.IO.Path.Combine(SampleFolderPath, "petStore.yaml")); - var actual = OpenApiDocument.Load(stream, OpenApiConstants.Yaml); + var actual = await OpenApiDocument.LoadAsync(stream, OpenApiConstants.Yaml); var components = new OpenApiComponents { @@ -573,10 +574,10 @@ public void ParseStandardPetStoreDocumentShouldSucceed() } [Fact] - public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() + public async Task ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() { using var stream = Resources.GetStream(System.IO.Path.Combine(SampleFolderPath, "petStoreWithTagAndSecurity.yaml")); - var actual = OpenApiDocument.Load(stream, OpenApiConstants.Yaml); + var actual = await OpenApiDocument.LoadAsync(stream, OpenApiConstants.Yaml); var components = new OpenApiComponents { @@ -1085,9 +1086,9 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() } [Fact] - public void ParsePetStoreExpandedShouldSucceed() + public async Task ParsePetStoreExpandedShouldSucceed() { - var actual = OpenApiDocument.Load(System.IO.Path.Combine(SampleFolderPath, "petStoreExpanded.yaml")); + var actual = await OpenApiDocument.LoadAsync(System.IO.Path.Combine(SampleFolderPath, "petStoreExpanded.yaml")); // TODO: Create the object in memory and compare with the one read from YAML file. @@ -1096,9 +1097,9 @@ public void ParsePetStoreExpandedShouldSucceed() } [Fact] - public void GlobalSecurityRequirementShouldReferenceSecurityScheme() + public async Task GlobalSecurityRequirementShouldReferenceSecurityScheme() { - var result = OpenApiDocument.Load(System.IO.Path.Combine(SampleFolderPath, "securedApi.yaml")); + var result = await OpenApiDocument.LoadAsync(System.IO.Path.Combine(SampleFolderPath, "securedApi.yaml")); var securityRequirement = result.OpenApiDocument.SecurityRequirements.First(); @@ -1107,9 +1108,9 @@ public void GlobalSecurityRequirementShouldReferenceSecurityScheme() } [Fact] - public void HeaderParameterShouldAllowExample() + public async Task HeaderParameterShouldAllowExample() { - var result = OpenApiDocument.Load(System.IO.Path.Combine(SampleFolderPath, "apiWithFullHeaderComponent.yaml")); + var result = await OpenApiDocument.LoadAsync(System.IO.Path.Combine(SampleFolderPath, "apiWithFullHeaderComponent.yaml")); var exampleHeader = result.OpenApiDocument.Components?.Headers?["example-header"]; Assert.NotNull(exampleHeader); @@ -1169,7 +1170,7 @@ public void HeaderParameterShouldAllowExample() } [Fact] - public void ParseDocumentWithReferencedSecuritySchemeWorks() + public async Task ParseDocumentWithReferencedSecuritySchemeWorks() { // Act var settings = new OpenApiReaderSettings @@ -1177,7 +1178,7 @@ public void ParseDocumentWithReferencedSecuritySchemeWorks() ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences }; - var result = OpenApiDocument.Load(System.IO.Path.Combine(SampleFolderPath, "docWithSecuritySchemeReference.yaml"), settings); + var result = await OpenApiDocument.LoadAsync(System.IO.Path.Combine(SampleFolderPath, "docWithSecuritySchemeReference.yaml"), settings); var securityScheme = result.OpenApiDocument.Components.SecuritySchemes["OAuth2"]; // Assert @@ -1186,7 +1187,7 @@ public void ParseDocumentWithReferencedSecuritySchemeWorks() } [Fact] - public void ParseDocumentWithJsonSchemaReferencesWorks() + public async Task ParseDocumentWithJsonSchemaReferencesWorks() { // Arrange using var stream = Resources.GetStream(System.IO.Path.Combine(SampleFolderPath, "docWithJsonSchema.yaml")); @@ -1196,7 +1197,7 @@ public void ParseDocumentWithJsonSchemaReferencesWorks() { ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences }; - var result = OpenApiDocument.Load(stream, OpenApiConstants.Yaml, settings); + var result = await OpenApiDocument.LoadAsync(stream, OpenApiConstants.Yaml, settings); var actualSchema = result.OpenApiDocument.Paths["/users/{userId}"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema; @@ -1206,10 +1207,10 @@ public void ParseDocumentWithJsonSchemaReferencesWorks() } [Fact] - public void ValidateExampleShouldNotHaveDataTypeMismatch() + public async Task ValidateExampleShouldNotHaveDataTypeMismatch() { // Act - var result = OpenApiDocument.Load(System.IO.Path.Combine(SampleFolderPath, "documentWithDateExampleInSchema.yaml"), new OpenApiReaderSettings + var result = await OpenApiDocument.LoadAsync(System.IO.Path.Combine(SampleFolderPath, "documentWithDateExampleInSchema.yaml"), new OpenApiReaderSettings { ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences @@ -1221,7 +1222,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatch() } [Fact] - public void ParseDocWithRefsUsingProxyReferencesSucceeds() + public async Task ParseDocWithRefsUsingProxyReferencesSucceeds() { // Arrange var expected = new OpenApiDocument @@ -1312,11 +1313,10 @@ public void ParseDocWithRefsUsingProxyReferencesSucceeds() using var stream = Resources.GetStream(System.IO.Path.Combine(SampleFolderPath, "minifiedPetStore.yaml")); // Act - var doc = OpenApiDocument.Load(stream, "yaml").OpenApiDocument; - var actualParam = doc.Paths["/pets"].Operations[OperationType.Get].Parameters.First(); + var doc = (await OpenApiDocument.LoadAsync(stream, "yaml")).OpenApiDocument; + var actualParam = doc.Paths["/pets"].Operations[OperationType.Get].Parameters[0]; var outputDoc = doc.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0).MakeLineBreaksEnvironmentNeutral(); - var output = actualParam.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0); - var expectedParam = expected.Paths["/pets"].Operations[OperationType.Get].Parameters.First(); + var expectedParam = expected.Paths["/pets"].Operations[OperationType.Get].Parameters[0]; // Assert actualParam.Should().BeEquivalentTo(expectedParam, options => options @@ -1397,9 +1397,9 @@ public void ParseBasicDocumentWithServerVariableAndNoDefaultShouldFail() } [Fact] - public void ParseDocumentWithEmptyPathsSucceeds() + public async Task ParseDocumentWithEmptyPathsSucceeds() { - var result = OpenApiDocument.Load(System.IO.Path.Combine(SampleFolderPath, "docWithEmptyPaths.yaml")); + var result = await OpenApiDocument.LoadAsync(System.IO.Path.Combine(SampleFolderPath, "docWithEmptyPaths.yaml")); result.OpenApiDiagnostic.Errors.Should().BeEmpty(); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs index eaf802d8c..2d214c9dc 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.IO; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Reader; @@ -20,10 +21,10 @@ public OpenApiEncodingTests() } [Fact] - public void ParseBasicEncodingShouldSucceed() + public async Task ParseBasicEncodingShouldSucceed() { // Act - var encoding = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "basicEncoding.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var encoding = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "basicEncoding.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert encoding.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs index 84f028f6b..9b32b0cbf 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiExampleTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.Text.Json.Nodes; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; @@ -22,9 +23,9 @@ public OpenApiExampleTests() } [Fact] - public void ParseAdvancedExampleShouldSucceed() + public async Task ParseAdvancedExampleShouldSucceed() { - var example = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "advancedExample.yaml"), OpenApiSpecVersion.OpenApi3_0, out var diagnostic); + var example = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "advancedExample.yaml"), OpenApiSpecVersion.OpenApi3_0); var expected = new OpenApiExample { Value = new JsonObject @@ -62,11 +63,6 @@ public void ParseAdvancedExampleShouldSucceed() } }; - var actualRoot = example.Value["versions"][0]["status"].Root; - var expectedRoot = expected.Value["versions"][0]["status"].Root; - - diagnostic.Errors.Should().BeEmpty(); - example.Should().BeEquivalentTo(expected, options => options.IgnoringCyclicReferences() .Excluding(e => e.Value["versions"][0]["status"].Root) .Excluding(e => e.Value["versions"][0]["id"].Root) @@ -79,9 +75,9 @@ public void ParseAdvancedExampleShouldSucceed() } [Fact] - public void ParseExampleForcedStringSucceed() + public async Task ParseExampleForcedStringSucceed() { - var result= OpenApiDocument.Load(Path.Combine(SampleFolderPath, "explicitString.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "explicitString.yaml")); result.OpenApiDiagnostic.Errors.Should().BeEmpty(); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs index 2fa75cf60..ffe4b9896 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs @@ -4,6 +4,7 @@ using System; using System.IO; using System.Text.Json.Nodes; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; @@ -23,10 +24,10 @@ public OpenApiInfoTests() } [Fact] - public void ParseAdvancedInfoShouldSucceed() + public async Task ParseAdvancedInfoShouldSucceed() { // Act - var openApiInfo = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "advancedInfo.yaml"), OpenApiSpecVersion.OpenApi3_0, out var diagnostic); + var openApiInfo = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "advancedInfo.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert openApiInfo.Should().BeEquivalentTo( @@ -80,10 +81,10 @@ public void ParseAdvancedInfoShouldSucceed() } [Fact] - public void ParseBasicInfoShouldSucceed() + public async Task ParseBasicInfoShouldSucceed() { // Act - var openApiInfo = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "basicInfo.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var openApiInfo = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "basicInfo.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert openApiInfo.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs index 26de35edb..6197cca71 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.IO; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; @@ -24,10 +25,10 @@ public OpenApiMediaTypeTests() } [Fact] - public void ParseMediaTypeWithExampleShouldSucceed() + public async Task ParseMediaTypeWithExampleShouldSucceed() { // Act - var mediaType = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "mediaTypeWithExample.yaml"), OpenApiSpecVersion.OpenApi3_0, out var diagnostic); + var mediaType = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "mediaTypeWithExample.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert mediaType.Should().BeEquivalentTo( @@ -45,10 +46,10 @@ public void ParseMediaTypeWithExampleShouldSucceed() } [Fact] - public void ParseMediaTypeWithExamplesShouldSucceed() + public async Task ParseMediaTypeWithExamplesShouldSucceed() { // Act - var mediaType = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "mediaTypeWithExamples.yaml"), OpenApiSpecVersion.OpenApi3_0, out var diagnostic); + var mediaType = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "mediaTypeWithExamples.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert mediaType.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs index 9ba96bbda..e9c722def 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.References; @@ -21,21 +22,21 @@ public OpenApiOperationTests() } [Fact] - public void OperationWithSecurityRequirementShouldReferenceSecurityScheme() + public async Task OperationWithSecurityRequirementShouldReferenceSecurityScheme() { - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "securedOperation.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "securedOperation.yaml")); - var securityScheme = result.OpenApiDocument.Paths["/"].Operations[OperationType.Get].Security.First().Keys.First(); + var securityScheme = result.OpenApiDocument.Paths["/"].Operations[OperationType.Get].Security[0].Keys.First(); securityScheme.Should().BeEquivalentTo(result.OpenApiDocument.Components.SecuritySchemes.First().Value, options => options.Excluding(x => x.Reference)); } [Fact] - public void ParseOperationWithParameterWithNoLocationShouldSucceed() + public async Task ParseOperationWithParameterWithNoLocationShouldSucceed() { // Act - var operation = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "operationWithParameterWithNoLocation.json"), OpenApiSpecVersion.OpenApi3_0, out _); + var operation = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "operationWithParameterWithNoLocation.json"), OpenApiSpecVersion.OpenApi3_0); var expectedOp = new OpenApiOperation { Tags = diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs index e0f6460aa..837edd165 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs @@ -11,6 +11,7 @@ using Xunit; using Microsoft.OpenApi.Reader.V3; using Microsoft.OpenApi.Services; +using System.Threading.Tasks; namespace Microsoft.OpenApi.Readers.Tests.V3Tests { @@ -49,10 +50,10 @@ public void ParsePathParameterShouldSucceed() } [Fact] - public void ParseQueryParameterShouldSucceed() + public async Task ParseQueryParameterShouldSucceed() { // Act - var parameter = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "queryParameter.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var parameter = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "queryParameter.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( @@ -76,10 +77,10 @@ public void ParseQueryParameterShouldSucceed() } [Fact] - public void ParseQueryParameterWithObjectTypeShouldSucceed() + public async Task ParseQueryParameterWithObjectTypeShouldSucceed() { // Act - var parameter = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "queryParameterWithObjectType.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var parameter = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "queryParameterWithObjectType.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( @@ -144,10 +145,10 @@ public void ParseQueryParameterWithObjectTypeAndContentShouldSucceed() } [Fact] - public void ParseHeaderParameterShouldSucceed() + public async Task ParseHeaderParameterShouldSucceed() { // Act - var parameter = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "headerParameter.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var parameter = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "headerParameter.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( @@ -172,10 +173,10 @@ public void ParseHeaderParameterShouldSucceed() } [Fact] - public void ParseParameterWithNullLocationShouldSucceed() + public async Task ParseParameterWithNullLocationShouldSucceed() { // Act - var parameter = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "parameterWithNullLocation.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var parameter = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "parameterWithNullLocation.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( @@ -241,10 +242,10 @@ public void ParseParameterWithUnknownLocationShouldSucceed() } [Fact] - public void ParseParameterWithExampleShouldSucceed() + public async Task ParseParameterWithExampleShouldSucceed() { // Act - var parameter = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "parameterWithExample.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var parameter = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "parameterWithExample.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( @@ -264,10 +265,10 @@ public void ParseParameterWithExampleShouldSucceed() } [Fact] - public void ParseParameterWithExamplesShouldSucceed() + public async Task ParseParameterWithExamplesShouldSucceed() { // Act - var parameter = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "parameterWithExamples.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var parameter = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "parameterWithExamples.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs index 09a1d00a1..4f798ad39 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiResponseTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Reader; @@ -21,9 +22,9 @@ public OpenApiResponseTests() } [Fact] - public void ResponseWithReferencedHeaderShouldReferenceComponent() + public async Task ResponseWithReferencedHeaderShouldReferenceComponent() { - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "responseWithHeaderReference.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "responseWithHeaderReference.yaml")); var response = result.OpenApiDocument.Components.Responses["Test"]; var expected = response.Headers.First().Value; diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index 6c1370626..70bfb4a51 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -16,6 +16,7 @@ using Microsoft.OpenApi.Reader.V3; using FluentAssertions.Equivalency; using Microsoft.OpenApi.Models.References; +using System.Threading.Tasks; namespace Microsoft.OpenApi.Readers.Tests.V3Tests { @@ -35,7 +36,7 @@ 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; + var yamlNode = yamlStream.Documents[0].RootNode; var diagnostic = new OpenApiDiagnostic(); var context = new ParsingContext(diagnostic); @@ -65,10 +66,9 @@ public void ParseExampleStringFragmentShouldSucceed() ""foo"": ""bar"", ""baz"": [ 1,2] }"; - var diagnostic = new OpenApiDiagnostic(); // Act - var openApiAny = OpenApiModelFactory.Parse(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + var openApiAny = OpenApiModelFactory.Parse(input, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); @@ -89,10 +89,9 @@ public void ParseEnumFragmentShouldSucceed() ""foo"", ""baz"" ]"; - var diagnostic = new OpenApiDiagnostic(); // Act - var openApiAny = OpenApiModelFactory.Parse(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic); + var openApiAny = OpenApiModelFactory.Parse(input, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); @@ -115,10 +114,9 @@ public void ParsePathFragmentShouldSucceed() '200': description: Ok "; - var diagnostic = new OpenApiDiagnostic(); // Act - var openApiAny = OpenApiModelFactory.Parse(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic, "yaml"); + var openApiAny = OpenApiModelFactory.Parse(input, OpenApiSpecVersion.OpenApi3_0, out var diagnostic, "yaml"); // Assert diagnostic.Should().BeEquivalentTo(new OpenApiDiagnostic()); @@ -150,7 +148,7 @@ public void ParseDictionarySchemaShouldSucceed() { var yamlStream = new YamlStream(); yamlStream.Load(new StreamReader(stream)); - var yamlNode = yamlStream.Documents.First().RootNode; + var yamlNode = yamlStream.Documents[0].RootNode; var diagnostic = new OpenApiDiagnostic(); var context = new ParsingContext(diagnostic); @@ -182,7 +180,7 @@ 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; + var yamlNode = yamlStream.Documents[0].RootNode; var diagnostic = new OpenApiDiagnostic(); var context = new ParsingContext(diagnostic); @@ -230,10 +228,10 @@ public void ParseBasicSchemaWithExampleShouldSucceed() } [Fact] - public void ParseBasicSchemaWithReferenceShouldSucceed() + public async Task ParseBasicSchemaWithReferenceShouldSucceed() { // Act - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "basicSchemaWithReference.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "basicSchemaWithReference.yaml")); // Assert var components = result.OpenApiDocument.Components; @@ -296,10 +294,10 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() } [Fact] - public void ParseAdvancedSchemaWithReferenceShouldSucceed() + public async Task ParseAdvancedSchemaWithReferenceShouldSucceed() { // Act - var result = OpenApiDocument.Load(Path.Combine(SampleFolderPath, "advancedSchemaWithReference.yaml")); + var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "advancedSchemaWithReference.yaml")); var expectedComponents = new OpenApiComponents { diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs index ef1aa0fdb..3f99bb2c5 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs @@ -3,6 +3,7 @@ using System; using System.IO; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Reader; @@ -20,10 +21,10 @@ public OpenApiSecuritySchemeTests() } [Fact] - public void ParseHttpSecuritySchemeShouldSucceed() + public async Task ParseHttpSecuritySchemeShouldSucceed() { // Act - var securityScheme = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "httpSecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var securityScheme = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "httpSecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert securityScheme.Should().BeEquivalentTo( @@ -35,10 +36,10 @@ public void ParseHttpSecuritySchemeShouldSucceed() } [Fact] - public void ParseApiKeySecuritySchemeShouldSucceed() + public async Task ParseApiKeySecuritySchemeShouldSucceed() { // Act - var securityScheme = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "apiKeySecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var securityScheme = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "apiKeySecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert securityScheme.Should().BeEquivalentTo( @@ -51,10 +52,10 @@ public void ParseApiKeySecuritySchemeShouldSucceed() } [Fact] - public void ParseBearerSecuritySchemeShouldSucceed() + public async Task ParseBearerSecuritySchemeShouldSucceed() { // Act - var securityScheme = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "bearerSecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var securityScheme = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "bearerSecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert securityScheme.Should().BeEquivalentTo( @@ -67,10 +68,10 @@ public void ParseBearerSecuritySchemeShouldSucceed() } [Fact] - public void ParseOAuth2SecuritySchemeShouldSucceed() + public async Task ParseOAuth2SecuritySchemeShouldSucceed() { // Act - var securityScheme = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "oauth2SecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var securityScheme = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "oauth2SecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert securityScheme.Should().BeEquivalentTo( @@ -93,10 +94,10 @@ public void ParseOAuth2SecuritySchemeShouldSucceed() } [Fact] - public void ParseOpenIdConnectSecuritySchemeShouldSucceed() + public async Task ParseOpenIdConnectSecuritySchemeShouldSucceed() { // Act - var securityScheme = OpenApiModelFactory.Load(Path.Combine(SampleFolderPath, "openIdConnectSecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0, out _); + var securityScheme = await OpenApiModelFactory.LoadAsync(Path.Combine(SampleFolderPath, "openIdConnectSecurityScheme.yaml"), OpenApiSpecVersion.OpenApi3_0); // Assert securityScheme.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 884ffa68c..24ed216db 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1583,8 +1583,6 @@ public void SerializeDocumentWithReferenceButNoComponents() } }; - var reference = document.Paths["/"].Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema.Reference; - // Act var actual = document.Serialize(OpenApiSpecVersion.OpenApi2_0, OpenApiFormat.Json); @@ -1684,14 +1682,14 @@ public void SerializeRelativeRootPathWithHostAsV2JsonWorks() } [Fact] - public void TestHashCodesForSimilarOpenApiDocuments() + public async Task 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")); + var doc1 = await ParseInputFileAsync(Path.Combine(sampleFolderPath, "sampleDocument.yaml")); + var doc2 = await ParseInputFileAsync(Path.Combine(sampleFolderPath, "sampleDocument.yaml")); + var doc3 = await ParseInputFileAsync(Path.Combine(sampleFolderPath, "sampleDocumentWithWhiteSpaces.yaml")); // Act && Assert /* @@ -1702,13 +1700,9 @@ And reading in similar documents(one has a whitespace) yields the same hash code Assert.Equal(doc1.HashCode, doc3.HashCode); } - private static OpenApiDocument ParseInputFile(string filePath) + private static async Task ParseInputFileAsync(string filePath) { - // Read in the input yaml file - using FileStream stream = File.OpenRead(filePath); - var format = OpenApiModelFactory.GetFormat(filePath); - var openApiDoc = OpenApiDocument.Load(stream, format).OpenApiDocument; - + var openApiDoc = (await OpenApiDocument.LoadAsync(filePath)).OpenApiDocument; return openApiDoc; } @@ -1999,7 +1993,7 @@ public void SerializeDocumentWithRootJsonSchemaDialectPropertyWorks() } [Fact] - public void SerializeV31DocumentWithRefsInWebhooksWorks() + public async Task SerializeV31DocumentWithRefsInWebhooksWorks() { var expected = @"description: Returns all pets from the system that the user has access to operationId: findPets @@ -2013,7 +2007,7 @@ public void SerializeV31DocumentWithRefsInWebhooksWorks() items: type: object"; - var doc = OpenApiDocument.Load("Models/Samples/docWithReusableWebhooks.yaml").OpenApiDocument; + var doc = (await OpenApiDocument.LoadAsync("Models/Samples/docWithReusableWebhooks.yaml")).OpenApiDocument; var stringWriter = new StringWriter(); var writer = new OpenApiYamlWriter(stringWriter, new OpenApiWriterSettings { InlineLocalReferences = true }); @@ -2025,7 +2019,7 @@ public void SerializeV31DocumentWithRefsInWebhooksWorks() } [Fact] - public void SerializeDocWithDollarIdInDollarRefSucceeds() + public async Task SerializeDocWithDollarIdInDollarRefSucceeds() { var expected = @"openapi: '3.1.1' info: @@ -2067,7 +2061,7 @@ public void SerializeDocWithDollarIdInDollarRefSucceeds() radius: type: number "; - var doc = OpenApiDocument.Load("Models/Samples/docWithDollarId.yaml").OpenApiDocument; + var doc = (await OpenApiDocument.LoadAsync("Models/Samples/docWithDollarId.yaml")).OpenApiDocument; var actual = doc.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_1); actual.MakeLineBreaksEnvironmentNeutral().Should().BeEquivalentTo(expected.MakeLineBreaksEnvironmentNeutral()); From 627d75b37483377d06d7fe36709d35f22fd99978 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 28 Nov 2024 18:46:48 +0300 Subject: [PATCH 08/50] Dispose stream --- src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index 1a85e6a27..08a9190f6 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -29,7 +29,9 @@ public async Task ReadAsync(Stream input, if (input is MemoryStream memoryStream) { return Read(memoryStream, settings); - } else { + } + else + { using var preparedStream = new MemoryStream(); await input.CopyToAsync(preparedStream, copyBufferSize, cancellationToken); preparedStream.Position = 0; @@ -39,14 +41,15 @@ public async Task ReadAsync(Stream input, /// public ReadResult Read(MemoryStream input, - OpenApiReaderSettings settings = null) + OpenApiReaderSettings settings = null) { JsonNode jsonNode; // Parse the YAML text in the TextReader into a sequence of JsonNodes try { - jsonNode = LoadJsonNodesFromYamlDocument(new StreamReader(input)); // Should we leave the stream open? + using var stream = new StreamReader(input); + jsonNode = LoadJsonNodesFromYamlDocument(stream); } catch (JsonException ex) { @@ -73,7 +76,8 @@ public T ReadFragment(MemoryStream input, // Parse the YAML try { - jsonNode = LoadJsonNodesFromYamlDocument(new StreamReader(input)); + using var stream = new StreamReader(input); + jsonNode = LoadJsonNodesFromYamlDocument(stream); } catch (JsonException ex) { From 46718f0e4e978fca7e719f25cc94bfb8fd092cfc Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 28 Nov 2024 18:48:01 +0300 Subject: [PATCH 09/50] clean up and dispose stream if specified in the settings --- .../Reader/OpenApiJsonReader.cs | 4 ---- .../Reader/OpenApiModelFactory.cs | 16 +++++++++++++--- .../V3Tests/OpenApiDiscriminatorTests.cs | 1 + 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index d24d31b9d..25add6e39 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -11,11 +11,7 @@ using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Validations; using System.Linq; -using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Interfaces; -using Microsoft.OpenApi.Reader.Services; -using System.Collections.Generic; -using System; namespace Microsoft.OpenApi.Reader { diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 65268394a..2884dd803 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -118,7 +118,7 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null) where T : IOpenApiElement { var result = await RetrieveStreamAndFormatAsync(url); - return Load(result.Item1 as MemoryStream, version, result.Item2, out var diagnostic, settings); + return Load(result.Item1, version, result.Item2, out var diagnostic, settings); } /// @@ -149,8 +149,18 @@ public static async Task LoadAsync(Stream input, string format = nul preparedStream.Position = 0; } - // Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON) - return await InternalLoadAsync(preparedStream, format, settings, cancellationToken); + try + { + // Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON) + return await InternalLoadAsync(preparedStream, format, settings, cancellationToken); + } + finally + { + if (!settings.LeaveStreamOpen) + { + input.Dispose(); + } + } } /// diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs index bcbc6a02a..ba62c7f33 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDiscriminatorTests.cs @@ -28,6 +28,7 @@ public async Task ParseBasicDiscriminatorShouldSucceed() // Copy stream to MemoryStream using var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream); + memoryStream.Position = 0; // Act var discriminator = OpenApiModelFactory.Load(memoryStream, OpenApiSpecVersion.OpenApi3_0, OpenApiConstants.Yaml, out var diagnostic); From bd6461253543ede124040f02994ec01c4cace41b Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 28 Nov 2024 18:48:09 +0300 Subject: [PATCH 10/50] Update public API --- .../PublicApi/PublicApi.approved.txt | 34 ++++++++----------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 8f9f8ed41..822b3048a 100644 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -219,9 +219,10 @@ namespace Microsoft.OpenApi.Interfaces } public interface IOpenApiReader { - System.Threading.Tasks.Task ReadAsync(System.IO.TextReader input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default); - System.Threading.Tasks.Task ReadAsync(System.Text.Json.Nodes.JsonNode jsonNode, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, string format = null, System.Threading.CancellationToken cancellationToken = default); - T ReadFragment(System.IO.TextReader input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) + Microsoft.OpenApi.Reader.ReadResult Read(System.IO.MemoryStream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null); + Microsoft.OpenApi.Reader.ReadResult Read(System.Text.Json.Nodes.JsonNode jsonNode, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, string format = null); + System.Threading.Tasks.Task ReadAsync(System.IO.Stream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default); + T ReadFragment(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement; T ReadFragment(System.Text.Json.Nodes.JsonNode input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement; @@ -577,11 +578,8 @@ namespace Microsoft.OpenApi.Models public void SerializeAsV31(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SetReferenceHostDocument() { } public static string GenerateHashValue(Microsoft.OpenApi.Models.OpenApiDocument doc) { } - public static Microsoft.OpenApi.Reader.ReadResult Load(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } - public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.Stream stream, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } - public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.TextReader input, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } + public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.MemoryStream stream, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } - public static System.Threading.Tasks.Task LoadAsync(System.IO.TextReader input, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream stream, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null, System.Threading.CancellationToken cancellationToken = default) { } public static Microsoft.OpenApi.Reader.ReadResult Parse(string input, string? format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } } @@ -1315,32 +1313,28 @@ namespace Microsoft.OpenApi.Reader public class OpenApiJsonReader : Microsoft.OpenApi.Interfaces.IOpenApiReader { public OpenApiJsonReader() { } - public System.Threading.Tasks.Task ReadAsync(System.IO.TextReader input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } - public System.Threading.Tasks.Task ReadAsync(System.Text.Json.Nodes.JsonNode jsonNode, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, string format = null, System.Threading.CancellationToken cancellationToken = default) { } - public T ReadFragment(System.IO.TextReader input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) + public Microsoft.OpenApi.Reader.ReadResult Read(System.IO.MemoryStream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } + public Microsoft.OpenApi.Reader.ReadResult Read(System.Text.Json.Nodes.JsonNode jsonNode, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, string format = null) { } + public System.Threading.Tasks.Task ReadAsync(System.IO.Stream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } + public T ReadFragment(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public T ReadFragment(System.Text.Json.Nodes.JsonNode input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } } public static class OpenApiModelFactory { - public static string GetFormat(string url) { } - public static Microsoft.OpenApi.Reader.ReadResult Load(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } - public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.Stream stream, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } - public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.TextReader input, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } - public static T Load(string url, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) + public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.MemoryStream stream, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } + public static T Load(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, string format, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public static T Load(System.IO.Stream input, Microsoft.OpenApi.OpenApiSpecVersion version, string format, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } - public static T Load(System.IO.TextReader input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) - where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } - public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream input, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } - public static System.Threading.Tasks.Task LoadAsync(System.IO.TextReader input, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream input, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.OpenApiSpecVersion version, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) + where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public static Microsoft.OpenApi.Reader.ReadResult Parse(string input, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } public static T Parse(string input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } - public static System.Threading.Tasks.Task ParseAsync(string input, System.IO.StringReader reader, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } } public static class OpenApiReaderRegistry { From a2f70aea67df13cdb3121bdb30929d06fbab7b81 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 28 Nov 2024 18:54:06 +0300 Subject: [PATCH 11/50] Leave stream open if specified in settings --- src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index 08a9190f6..1ee22e8b2 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -48,7 +48,7 @@ public ReadResult Read(MemoryStream input, // Parse the YAML text in the TextReader into a sequence of JsonNodes try { - using var stream = new StreamReader(input); + using var stream = new StreamReader(input, default, true, -1, settings.LeaveStreamOpen); jsonNode = LoadJsonNodesFromYamlDocument(stream); } catch (JsonException ex) From 8bbb3dd9abde2fce6b3a14a4f31967e2dacbbf3c Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 28 Nov 2024 19:01:14 +0300 Subject: [PATCH 12/50] Guard against null references --- src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs | 2 +- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index 1ee22e8b2..db7482f44 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -48,7 +48,7 @@ public ReadResult Read(MemoryStream input, // Parse the YAML text in the TextReader into a sequence of JsonNodes try { - using var stream = new StreamReader(input, default, true, -1, settings.LeaveStreamOpen); + using var stream = new StreamReader(input, default, true, -1, settings?.LeaveStreamOpen); jsonNode = LoadJsonNodesFromYamlDocument(stream); } catch (JsonException ex) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 2884dd803..e1db00832 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -210,7 +210,7 @@ private static async Task InternalLoadAsync(Stream input, string for var reader = OpenApiReaderRegistry.GetReader(format); var readResult = await reader.ReadAsync(input, settings, cancellationToken); - if (settings.LoadExternalRefs) + if (settings is not null && settings.LoadExternalRefs) { var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.OpenApiDocument, cancellationToken, settings, format); // Merge diagnostics of external reference @@ -239,7 +239,7 @@ private static async Task LoadExternalRefsAsync(OpenApiDocume private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings = null) { Utils.CheckArgumentNull(format, nameof(format)); - if (settings.LoadExternalRefs) + if (settings is not null && settings.LoadExternalRefs) { throw new InvalidOperationException("Loading external references are not supported when using synchronous methods."); } From cecf011bf3b0e1f69d8b808eeda8e3a6e0e7bd54 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 28 Nov 2024 19:10:45 +0300 Subject: [PATCH 13/50] code cleanup --- .../OpenApiYamlReader.cs | 6 ++--- .../Interfaces/IOpenApiReader.cs | 4 ++-- .../Reader/OpenApiJsonReader.cs | 6 ++--- .../Reader/OpenApiModelFactory.cs | 24 ++++++++----------- 4 files changed, 18 insertions(+), 22 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index db7482f44..8639798d6 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -23,7 +23,7 @@ public class OpenApiYamlReader : IOpenApiReader /// public async Task ReadAsync(Stream input, - OpenApiReaderSettings settings = null, + OpenApiReaderSettings settings, CancellationToken cancellationToken = default) { if (input is MemoryStream memoryStream) @@ -41,14 +41,14 @@ public async Task ReadAsync(Stream input, /// public ReadResult Read(MemoryStream input, - OpenApiReaderSettings settings = null) + OpenApiReaderSettings settings) { JsonNode jsonNode; // Parse the YAML text in the TextReader into a sequence of JsonNodes try { - using var stream = new StreamReader(input, default, true, -1, settings?.LeaveStreamOpen); + using var stream = new StreamReader(input, default, true, -1, settings.LeaveStreamOpen); jsonNode = LoadJsonNodesFromYamlDocument(stream); } catch (JsonException ex) diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs index b746b857b..642572985 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs @@ -21,7 +21,7 @@ public interface IOpenApiReader /// The OpenApi reader settings. /// Propagates notification that an operation should be cancelled. /// - Task ReadAsync(Stream input, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default); + Task ReadAsync(Stream input, OpenApiReaderSettings settings, CancellationToken cancellationToken = default); /// /// Provides a synchronous method to read the input memory stream and parse it into an Open API document. @@ -29,7 +29,7 @@ public interface IOpenApiReader /// /// /// - ReadResult Read(MemoryStream input, OpenApiReaderSettings settings = null); + ReadResult Read(MemoryStream input, OpenApiReaderSettings settings); /// /// Parses the JsonNode input into an Open API document. diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index 25add6e39..ec696abd5 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -61,7 +61,7 @@ public ReadResult Read(MemoryStream input, /// Propagates notifications that operations should be cancelled. /// public async Task ReadAsync(Stream input, - OpenApiReaderSettings settings = null, + OpenApiReaderSettings settings, CancellationToken cancellationToken = default) { JsonNode jsonNode; @@ -94,8 +94,8 @@ public async Task ReadAsync(Stream input, /// The OpenAPI format. /// public ReadResult Read(JsonNode jsonNode, - OpenApiReaderSettings settings, - string format = null) + OpenApiReaderSettings settings, + string format = null) { var diagnostic = new OpenApiDiagnostic(); var context = new ParsingContext(diagnostic) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index e1db00832..b9abca5ab 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -149,18 +149,14 @@ public static async Task LoadAsync(Stream input, string format = nul preparedStream.Position = 0; } - try + // Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON) + var result = await InternalLoadAsync(preparedStream, format, settings, cancellationToken); + if (!settings.LeaveStreamOpen) { - // Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON) - return await InternalLoadAsync(preparedStream, format, settings, cancellationToken); - } - finally - { - if (!settings.LeaveStreamOpen) - { - input.Dispose(); - } + input.Dispose(); } + + return result; } /// @@ -204,13 +200,13 @@ public static T Parse(string input, return Load(stream, version, format, out diagnostic, settings); } - private static async Task InternalLoadAsync(Stream input, string format, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) + private static async Task InternalLoadAsync(Stream input, string format, OpenApiReaderSettings settings, CancellationToken cancellationToken = default) { Utils.CheckArgumentNull(format, nameof(format)); var reader = OpenApiReaderRegistry.GetReader(format); var readResult = await reader.ReadAsync(input, settings, cancellationToken); - if (settings is not null && settings.LoadExternalRefs) + if (settings.LoadExternalRefs) { var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.OpenApiDocument, cancellationToken, settings, format); // Merge diagnostics of external reference @@ -236,10 +232,10 @@ private static async Task LoadExternalRefsAsync(OpenApiDocume return await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document, format ?? OpenApiConstants.Json, null, cancellationToken); } - private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings = null) + private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings) { Utils.CheckArgumentNull(format, nameof(format)); - if (settings is not null && settings.LoadExternalRefs) + if (settings.LoadExternalRefs) { throw new InvalidOperationException("Loading external references are not supported when using synchronous methods."); } From be3bbf51c56a6994e383ffa067eabce4e14ad101 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Mon, 2 Dec 2024 11:07:53 +0300 Subject: [PATCH 14/50] Update public API --- .../PublicApi/PublicApi.approved.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 822b3048a..3200dfb65 100644 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -219,9 +219,9 @@ namespace Microsoft.OpenApi.Interfaces } public interface IOpenApiReader { - Microsoft.OpenApi.Reader.ReadResult Read(System.IO.MemoryStream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null); + Microsoft.OpenApi.Reader.ReadResult Read(System.IO.MemoryStream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings); Microsoft.OpenApi.Reader.ReadResult Read(System.Text.Json.Nodes.JsonNode jsonNode, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, string format = null); - System.Threading.Tasks.Task ReadAsync(System.IO.Stream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default); + System.Threading.Tasks.Task ReadAsync(System.IO.Stream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, System.Threading.CancellationToken cancellationToken = default); T ReadFragment(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement; T ReadFragment(System.Text.Json.Nodes.JsonNode input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) @@ -1315,7 +1315,7 @@ namespace Microsoft.OpenApi.Reader public OpenApiJsonReader() { } public Microsoft.OpenApi.Reader.ReadResult Read(System.IO.MemoryStream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } public Microsoft.OpenApi.Reader.ReadResult Read(System.Text.Json.Nodes.JsonNode jsonNode, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, string format = null) { } - public System.Threading.Tasks.Task ReadAsync(System.IO.Stream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } + public System.Threading.Tasks.Task ReadAsync(System.IO.Stream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, System.Threading.CancellationToken cancellationToken = default) { } public T ReadFragment(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public T ReadFragment(System.Text.Json.Nodes.JsonNode input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) From 408e793cfe1fcf76c5a89f1e5af2122e4c7881a9 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Mon, 2 Dec 2024 12:00:33 +0300 Subject: [PATCH 15/50] remove extra semi-colon and commented out code --- src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index ec696abd5..61290e48d 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -71,7 +71,7 @@ public async Task ReadAsync(Stream input, // Parse the JSON text in the TextReader into JsonNodes try { - jsonNode = await JsonNode.ParseAsync(input);; + jsonNode = await JsonNode.ParseAsync(input); } catch (JsonException ex) { @@ -110,18 +110,6 @@ public ReadResult Read(JsonNode jsonNode, { // Parse the OpenAPI Document document = context.Parse(jsonNode); - - // if (settings.LoadExternalRefs) - // { - // var diagnosticExternalRefs = await LoadExternalRefsAsync(document, cancellationToken, settings, format); - // // Merge diagnostics of external reference - // if (diagnosticExternalRefs != null) - // { - // diagnostic.Errors.AddRange(diagnosticExternalRefs.Errors); - // diagnostic.Warnings.AddRange(diagnosticExternalRefs.Warnings); - // } - // } - document.SetReferenceHostDocument(); } catch (OpenApiException ex) From 7acdf9b7fcca2e5285cf9ee6231ff69a1f4db38b Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Mon, 2 Dec 2024 12:12:16 +0300 Subject: [PATCH 16/50] Remove unnecessary using --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index b9abca5ab..69d0de388 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System; -using System.Buffers.Text; using System.IO; using System.Linq; using System.Net.Http; From dc25f9ec7658a8c6aaaf76afa03094bed813ea22 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Tue, 3 Dec 2024 11:00:53 +0300 Subject: [PATCH 17/50] Inspect string input's format if not explicitly provided --- .../Reader/OpenApiModelFactory.cs | 10 +++++++--- .../V3Tests/OpenApiDocumentTests.cs | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 69d0de388..71dfbbb2c 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -169,7 +169,7 @@ public static ReadResult Parse(string input, string format = null, OpenApiReaderSettings settings = null) { - format ??= OpenApiConstants.Json; + format ??= InspectInputFormat(input); settings ??= new OpenApiReaderSettings(); // Copy string into MemoryStream @@ -193,7 +193,7 @@ public static T Parse(string input, string format = null, OpenApiReaderSettings settings = null) where T : IOpenApiElement { - format ??= OpenApiConstants.Json; + format ??= InspectInputFormat(input); settings ??= new OpenApiReaderSettings(); var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); return Load(stream, version, format, out diagnostic, settings); @@ -201,7 +201,6 @@ public static T Parse(string input, private static async Task InternalLoadAsync(Stream input, string format, OpenApiReaderSettings settings, CancellationToken cancellationToken = default) { - Utils.CheckArgumentNull(format, nameof(format)); var reader = OpenApiReaderRegistry.GetReader(format); var readResult = await reader.ReadAsync(input, settings, cancellationToken); @@ -289,5 +288,10 @@ SecurityException or } return (null, null); } + + private static string InspectInputFormat(string input) + { + return input.StartsWith("{", StringComparison.OrdinalIgnoreCase) || input.StartsWith("[", StringComparison.OrdinalIgnoreCase) ? OpenApiConstants.Json : OpenApiConstants.Yaml; + } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index fa6a4dee4..daf253af3 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -106,6 +106,21 @@ public void ParseDocumentFromInlineStringShouldSucceed() }); } + [Fact] + public void ParseInlineStringWithoutProvidingFormatSucceeds() + { + var stringOpenApiDoc = """ +openapi: 3.1.0 +info: + title: Sample API + version: 1.0.0 +paths: {} +"""; + + var readResult = OpenApiDocument.Parse(stringOpenApiDoc); + readResult.OpenApiDocument.Info.Title.Should().Be("Sample API"); + } + [Fact] public async Task ParseBasicDocumentWithMultipleServersShouldSucceed() { From 63ab53f3125b2ad729d77c9689a8fbc6931ebd19 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Tue, 3 Dec 2024 12:40:44 +0300 Subject: [PATCH 18/50] Remove unnecessary using and whitespace --- src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs | 1 - src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index 61290e48d..0494bc1e1 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -20,7 +20,6 @@ namespace Microsoft.OpenApi.Reader /// public class OpenApiJsonReader : IOpenApiReader { - /// /// Reads the memory stream input and parses it into an Open API document. /// diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 71dfbbb2c..e2c95c687 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.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.IO; using System.Linq; using System.Net.Http; +using System.Runtime.InteropServices.ComTypes; using System.Security; using System.Text; using System.Threading; From d022fa4bdd25dee8a246497ff11b636076ae9c69 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 5 Dec 2024 15:28:32 +0300 Subject: [PATCH 19/50] Remove unnecessary using --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index e2c95c687..7f3857089 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -5,7 +5,6 @@ using System.IO; using System.Linq; using System.Net.Http; -using System.Runtime.InteropServices.ComTypes; using System.Security; using System.Text; using System.Threading; From 04af1a6f90b82c7dc7ad2ccac68b6f13668c6baa Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 5 Dec 2024 16:10:57 +0300 Subject: [PATCH 20/50] Make format optional; add logic for inspecting stream format --- .../Models/OpenApiDocument.cs | 4 +- .../Reader/OpenApiModelFactory.cs | 100 +++++++++++++++--- .../OpenApiStreamReaderTests.cs | 8 +- .../V3Tests/OpenApiDocumentTests.cs | 7 +- .../V3Tests/OpenApiEncodingTests.cs | 2 +- .../V3Tests/OpenApiInfoTests.cs | 2 +- .../V3Tests/OpenApiParameterTests.cs | 8 +- .../V3Tests/OpenApiXmlTests.cs | 2 +- .../PublicApi/PublicApi.approved.txt | 8 +- 9 files changed, 107 insertions(+), 34 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 13de5f7f8..25b605d6d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -543,7 +543,7 @@ private static string ConvertByteArrayToString(byte[] hash) /// The OpenApi reader settings. /// public static ReadResult Load(MemoryStream stream, - string format, + string? format = null, OpenApiReaderSettings? settings = null) { return OpenApiModelFactory.Load(stream, format, settings); @@ -568,7 +568,7 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings /// The OpenApi reader settings. /// Propagates information about operation cancelling. /// - public static async Task LoadAsync(Stream stream, string format, OpenApiReaderSettings? settings = null, CancellationToken cancellationToken = default) + public static async Task LoadAsync(Stream stream, string? format = null, OpenApiReaderSettings? settings = null, CancellationToken cancellationToken = default) { return await OpenApiModelFactory.LoadAsync(stream, format, settings, cancellationToken); } diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 7f3857089..2bb3cb8a3 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.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; @@ -36,11 +36,13 @@ static OpenApiModelFactory() /// The OpenAPI format. /// An OpenAPI document instance. public static ReadResult Load(MemoryStream stream, - string format, + string format = null, OpenApiReaderSettings settings = null) { settings ??= new OpenApiReaderSettings(); + // Get the format of the stream if not provided + format ??= InspectStreamFormat(stream); var result = InternalLoad(stream, format, settings); if (!settings.LeaveStreamOpen) @@ -61,7 +63,11 @@ public static ReadResult Load(MemoryStream stream, /// /// /// - public static T Load(Stream input, OpenApiSpecVersion version, string format, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement + public static T Load(Stream input, + OpenApiSpecVersion version, + out OpenApiDiagnostic diagnostic, + string format = null, + OpenApiReaderSettings settings = null) where T : IOpenApiElement { if (input is MemoryStream memoryStream) { @@ -89,7 +95,7 @@ public static T Load(Stream input, OpenApiSpecVersion version, string format, /// The OpenAPI element. public static T Load(MemoryStream input, OpenApiSpecVersion version, string format, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement { - format ??= OpenApiConstants.Json; + format ??= InspectStreamFormat(input); return OpenApiReaderRegistry.GetReader(format).ReadFragment(input, version, out diagnostic, settings); } @@ -117,7 +123,7 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null) where T : IOpenApiElement { var result = await RetrieveStreamAndFormatAsync(url); - return Load(result.Item1, version, result.Item2, out var diagnostic, settings); + return Load(result.Item1, version, out var diagnostic, result.Item2, settings); } /// @@ -130,22 +136,17 @@ public static async Task LoadAsync(string url, OpenApiSpecVersion version, /// public static async Task LoadAsync(Stream input, string format = null, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) { - Utils.CheckArgumentNull(format, nameof(format)); settings ??= new OpenApiReaderSettings(); - Stream preparedStream; - - // Avoid buffering for JSON documents - if (input is MemoryStream || format.Equals(OpenApiConstants.Json, StringComparison.OrdinalIgnoreCase)) + if (format is null) { - preparedStream = input; + var readResult = await PrepareStreamForReadingAsync(input, format, cancellationToken); + preparedStream = readResult.Item1; + format = readResult.Item2; } else { - // Buffer stream for non-JSON formats (e.g., YAML) since they require synchronous reading - preparedStream = new MemoryStream(); - await input.CopyToAsync(preparedStream, 81920, cancellationToken); - preparedStream.Position = 0; + preparedStream = input; } // Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON) @@ -232,7 +233,6 @@ private static async Task LoadExternalRefsAsync(OpenApiDocume private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings) { - Utils.CheckArgumentNull(format, nameof(format)); if (settings.LoadExternalRefs) { throw new InvalidOperationException("Loading external references are not supported when using synchronous methods."); @@ -293,5 +293,73 @@ private static string InspectInputFormat(string input) { return input.StartsWith("{", StringComparison.OrdinalIgnoreCase) || input.StartsWith("[", StringComparison.OrdinalIgnoreCase) ? OpenApiConstants.Json : OpenApiConstants.Yaml; } + + private static string InspectStreamFormat(Stream stream) + { + if (stream == null) throw new ArgumentNullException(nameof(stream)); + + long initialPosition = stream.Position; + int firstByte = stream.ReadByte(); + + // Skip whitespace if present and read the next non-whitespace byte + if (char.IsWhiteSpace((char)firstByte)) + { + firstByte = stream.ReadByte(); + } + + stream.Position = initialPosition; // Reset the stream position to the beginning + + char firstChar = (char)firstByte; + return firstChar switch + { + '{' or '[' => OpenApiConstants.Json, // If the first character is '{' or '[', assume JSON + _ => OpenApiConstants.Yaml // Otherwise assume YAML + }; + } + + private static async Task<(Stream, string)> PrepareStreamForReadingAsync(Stream input, string format, CancellationToken token = default) + { + Stream preparedStream = input; + + if (!input.CanSeek) + { + // Use a temporary buffer to read a small portion for format detection + using var bufferStream = new MemoryStream(); + await input.CopyToAsync(bufferStream, 1024, token); + bufferStream.Position = 0; + + // Inspect the format from the buffered portion + format ??= InspectStreamFormat(bufferStream); + + // If format is JSON, no need to buffer further — use the original stream. + if (format.Equals(OpenApiConstants.Json, StringComparison.OrdinalIgnoreCase)) + { + preparedStream = input; + } + else + { + // YAML or other non-JSON format; copy remaining input to a new stream. + preparedStream = new MemoryStream(); + bufferStream.Position = 0; + await bufferStream.CopyToAsync(preparedStream, 81920, token); // Copy buffered portion + await input.CopyToAsync(preparedStream, 81920, token); // Copy remaining data + preparedStream.Position = 0; + } + } + else + { + format ??= InspectStreamFormat(input); + + if (!format.Equals(OpenApiConstants.Json, StringComparison.OrdinalIgnoreCase)) + { + // Buffer stream for non-JSON formats (e.g., YAML) since they require synchronous reading + preparedStream = new MemoryStream(); + await input.CopyToAsync(preparedStream, 81920, token); + preparedStream.Position = 0; + } + } + + return (preparedStream, format); + } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs index 91407f0b7..9ce10d22e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs @@ -25,7 +25,7 @@ public async Task StreamShouldCloseIfLeaveStreamOpenSettingEqualsFalse() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml")); var settings = new OpenApiReaderSettings { LeaveStreamOpen = false }; - _ = await OpenApiDocument.LoadAsync(stream, "yaml", settings); + _ = await OpenApiDocument.LoadAsync(stream, settings: settings); Assert.False(stream.CanRead); } @@ -34,7 +34,7 @@ public async Task StreamShouldNotCloseIfLeaveStreamOpenSettingEqualsTrue() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml")); var settings = new OpenApiReaderSettings { LeaveStreamOpen = true }; - _ = await OpenApiDocument.LoadAsync(stream, "yaml", settings); + _ = await OpenApiDocument.LoadAsync(stream, settings: settings); Assert.True(stream.CanRead); } @@ -48,7 +48,7 @@ public async Task StreamShouldNotBeDisposedIfLeaveStreamOpenSettingIsTrueAsync() memoryStream.Position = 0; var stream = memoryStream; - _ = await OpenApiDocument.LoadAsync(stream, "yaml", new OpenApiReaderSettings { LeaveStreamOpen = true }); + _ = await OpenApiDocument.LoadAsync(stream, settings: new OpenApiReaderSettings { LeaveStreamOpen = true }); stream.Seek(0, SeekOrigin.Begin); // does not throw an object disposed exception Assert.True(stream.CanRead); } @@ -64,7 +64,7 @@ public async Task StreamShouldReadWhenInitializedAsync() var stream = await httpClient.GetStreamAsync("20fe7a7b720a0e48e5842d002ac418b12a8201df/tests/v3.0/pass/petstore.yaml"); // Read V3 as YAML - var result = await OpenApiDocument.LoadAsync(stream, "yaml"); + var result = await OpenApiDocument.LoadAsync(stream); Assert.NotNull(result.OpenApiDocument); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index daf253af3..aeb0a301f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -156,7 +156,12 @@ public async Task ParseBasicDocumentWithMultipleServersShouldSucceed() public async Task ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() { using var stream = Resources.GetStream(System.IO.Path.Combine(SampleFolderPath, "brokenMinimalDocument.yaml")); - var result = await OpenApiDocument.LoadAsync(stream, OpenApiConstants.Yaml); + // Copy stream to MemoryStream + using var memoryStream = new MemoryStream(); + await stream.CopyToAsync(memoryStream); + memoryStream.Position = 0; + + var result = OpenApiDocument.Load(memoryStream); result.OpenApiDocument.Should().BeEquivalentTo( new OpenApiDocument diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs index 2d214c9dc..c2d34493b 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs @@ -40,7 +40,7 @@ public void ParseAdvancedEncodingShouldSucceed() using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedEncoding.yaml")); // Act - var encoding = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, OpenApiConstants.Yaml, out _); + var encoding = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _); // Assert encoding.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs index ffe4b9896..25da65e9d 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs @@ -114,7 +114,7 @@ public void ParseMinimalInfoShouldSucceed() using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalInfo.yaml")); // Act - var openApiInfo = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, "yaml", out _); + var openApiInfo = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _, "yaml"); // Assert openApiInfo.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs index 837edd165..638c47c4a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs @@ -32,7 +32,7 @@ public void ParsePathParameterShouldSucceed() using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "pathParameter.yaml")); // Act - var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, "yaml", out _); + var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _, "yaml"); // Assert parameter.Should().BeEquivalentTo( @@ -107,7 +107,7 @@ public void ParseQueryParameterWithObjectTypeAndContentShouldSucceed() using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "queryParameterWithObjectTypeAndContent.yaml")); // Act - var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, "yaml", out _); + var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _, "yaml"); // Assert parameter.Should().BeEquivalentTo( @@ -200,7 +200,7 @@ public void ParseParameterWithNoLocationShouldSucceed() using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "parameterWithNoLocation.yaml")); // Act - var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, "yaml", out _); + var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _); // Assert parameter.Should().BeEquivalentTo( @@ -224,7 +224,7 @@ public void ParseParameterWithUnknownLocationShouldSucceed() using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "parameterWithUnknownLocation.yaml")); // Act - var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, "yaml", out _); + var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _); // Assert parameter.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs index c0d99793e..aab130202 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs @@ -24,7 +24,7 @@ public OpenApiXmlTests() public void ParseBasicXmlShouldSucceed() { // Act - var xml = OpenApiModelFactory.Load(Resources.GetStream(Path.Combine(SampleFolderPath, "basicXml.yaml")), OpenApiSpecVersion.OpenApi3_0, "yaml", out _); + var xml = OpenApiModelFactory.Load(Resources.GetStream(Path.Combine(SampleFolderPath, "basicXml.yaml")), OpenApiSpecVersion.OpenApi3_0, out _); // Assert xml.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 3200dfb65..9405b04d3 100644 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -578,9 +578,9 @@ namespace Microsoft.OpenApi.Models public void SerializeAsV31(Microsoft.OpenApi.Writers.IOpenApiWriter writer) { } public void SetReferenceHostDocument() { } public static string GenerateHashValue(Microsoft.OpenApi.Models.OpenApiDocument doc) { } - public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.MemoryStream stream, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } + public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.MemoryStream stream, string? format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } - public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream stream, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream stream, string? format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null, System.Threading.CancellationToken cancellationToken = default) { } public static Microsoft.OpenApi.Reader.ReadResult Parse(string input, string? format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings? settings = null) { } } public class OpenApiEncoding : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiExtensible, Microsoft.OpenApi.Interfaces.IOpenApiSerializable @@ -1323,10 +1323,10 @@ namespace Microsoft.OpenApi.Reader } public static class OpenApiModelFactory { - public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.MemoryStream stream, string format, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } + public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.MemoryStream stream, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } public static T Load(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, string format, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } - public static T Load(System.IO.Stream input, Microsoft.OpenApi.OpenApiSpecVersion version, string format, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) + public static T Load(System.IO.Stream input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream input, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } From 86b70c941d764857ca07026d0b46ce70477be3c7 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 5 Dec 2024 16:53:30 +0300 Subject: [PATCH 21/50] code cleanup --- .../OpenApiYamlReader.cs | 26 +++---- .../Reader/OpenApiJsonReader.cs | 69 +++++++++---------- 2 files changed, 47 insertions(+), 48 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index 8639798d6..4d4289b81 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -65,6 +65,12 @@ public ReadResult Read(MemoryStream input, return Read(jsonNode, settings); } + /// + public ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null) + { + return OpenApiReaderRegistry.DefaultReader.Read(jsonNode, settings, OpenApiConstants.Yaml); + } + /// public T ReadFragment(MemoryStream input, OpenApiSpecVersion version, @@ -89,6 +95,12 @@ public T ReadFragment(MemoryStream input, return ReadFragment(jsonNode, version, out diagnostic); } + /// + public T ReadFragment(JsonNode input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement + { + return OpenApiReaderRegistry.DefaultReader.ReadFragment(input, version, out diagnostic); + } + /// /// Helper method to turn streams into a sequence of JsonNodes /// @@ -98,20 +110,8 @@ static JsonNode LoadJsonNodesFromYamlDocument(TextReader input) { var yamlStream = new YamlStream(); yamlStream.Load(input); - var yamlDocument = yamlStream.Documents.First(); + var yamlDocument = yamlStream.Documents[0]; return yamlDocument.ToJsonNode(); } - - /// - public ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null) - { - return OpenApiReaderRegistry.DefaultReader.Read(jsonNode, settings, OpenApiConstants.Yaml); - } - - /// - public T ReadFragment(JsonNode input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement - { - return OpenApiReaderRegistry.DefaultReader.ReadFragment(input, version, out diagnostic); - } } } diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index 0494bc1e1..862cccf39 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -27,7 +27,7 @@ public class OpenApiJsonReader : IOpenApiReader /// The Reader settings to be used during parsing. /// public ReadResult Read(MemoryStream input, - OpenApiReaderSettings settings = null) + OpenApiReaderSettings settings) { JsonNode jsonNode; var diagnostic = new OpenApiDiagnostic(); @@ -51,40 +51,6 @@ public ReadResult Read(MemoryStream input, return Read(jsonNode, settings); } - - /// - /// Reads the stream input asynchronously and parses it into an Open API document. - /// - /// TextReader containing OpenAPI description to parse. - /// The Reader settings to be used during parsing. - /// Propagates notifications that operations should be cancelled. - /// - public async Task ReadAsync(Stream input, - OpenApiReaderSettings settings, - CancellationToken cancellationToken = default) - { - JsonNode jsonNode; - var diagnostic = new OpenApiDiagnostic(); - settings ??= new OpenApiReaderSettings(); - - // Parse the JSON text in the TextReader into JsonNodes - try - { - jsonNode = await JsonNode.ParseAsync(input); - } - catch (JsonException ex) - { - diagnostic.Errors.Add(new OpenApiError($"#line={ex.LineNumber}", $"Please provide the correct format, {ex.Message}")); - return new ReadResult - { - OpenApiDocument = null, - OpenApiDiagnostic = diagnostic - }; - } - - return Read(jsonNode, settings); - } - /// /// Parses the JsonNode input into an Open API document. /// @@ -137,6 +103,39 @@ public ReadResult Read(JsonNode jsonNode, }; } + /// + /// Reads the stream input asynchronously and parses it into an Open API document. + /// + /// TextReader containing OpenAPI description to parse. + /// The Reader settings to be used during parsing. + /// Propagates notifications that operations should be cancelled. + /// + public async Task ReadAsync(Stream input, + OpenApiReaderSettings settings, + CancellationToken cancellationToken = default) + { + JsonNode jsonNode; + var diagnostic = new OpenApiDiagnostic(); + settings ??= new OpenApiReaderSettings(); + + // Parse the JSON text in the TextReader into JsonNodes + try + { + jsonNode = await JsonNode.ParseAsync(input); + } + catch (JsonException ex) + { + diagnostic.Errors.Add(new OpenApiError($"#line={ex.LineNumber}", $"Please provide the correct format, {ex.Message}")); + return new ReadResult + { + OpenApiDocument = null, + OpenApiDiagnostic = diagnostic + }; + } + + return Read(jsonNode, settings); + } + /// public T ReadFragment(MemoryStream input, OpenApiSpecVersion version, From dd80ab7464495af86c1bc0b92ac38aecedb8368d Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Wed, 11 Dec 2024 00:36:39 +0300 Subject: [PATCH 22/50] Update public API --- 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 9405b04d3..418673906 100644 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1313,7 +1313,7 @@ namespace Microsoft.OpenApi.Reader public class OpenApiJsonReader : Microsoft.OpenApi.Interfaces.IOpenApiReader { public OpenApiJsonReader() { } - public Microsoft.OpenApi.Reader.ReadResult Read(System.IO.MemoryStream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } + public Microsoft.OpenApi.Reader.ReadResult Read(System.IO.MemoryStream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings) { } public Microsoft.OpenApi.Reader.ReadResult Read(System.Text.Json.Nodes.JsonNode jsonNode, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, string format = null) { } public System.Threading.Tasks.Task ReadAsync(System.IO.Stream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, System.Threading.CancellationToken cancellationToken = default) { } public T ReadFragment(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) From 2c2bbe672eae87b4d3a6f3d68daf3e300b4b0ce8 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 11 Dec 2024 07:35:14 -0500 Subject: [PATCH 23/50] chore: code fixes recommended by sonarqube Signed-off-by: Vincent Biret --- .../Models/OpenApiDocument.cs | 2 +- .../Reader/OpenApiModelFactory.cs | 2 +- .../V3Tests/OpenApiDocumentTests.cs | 54 ++++++++----------- 3 files changed, 24 insertions(+), 34 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 25b605d6d..b90f1b203 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -371,7 +371,7 @@ private static void WriteHostInfoV2(IOpenApiWriter writer, IList? // Arbitrarily choose the first server given that V2 only allows // one host, port, and base path. - var serverUrl = ParseServerUrl(servers.First()); + var serverUrl = ParseServerUrl(servers[0]); // Divide the URL in the Url property into host and basePath required in OpenAPI V2 // The Url property cannot contain path templating to be valid for V2 serialization. diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 2bb3cb8a3..d60e067e0 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -123,7 +123,7 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null) where T : IOpenApiElement { var result = await RetrieveStreamAndFormatAsync(url); - return Load(result.Item1, version, out var diagnostic, result.Item2, settings); + return Load(result.Item1, version, out var _, result.Item2, settings); } /// diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index aeb0a301f..a0ffc90c1 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -34,46 +34,36 @@ public OpenApiDocumentTests() public T Clone(T element) where T : IOpenApiSerializable { - using (var stream = new MemoryStream()) + using var stream = new MemoryStream(); + var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); + var 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; + InlineLocalReferences = true + }); + element.SerializeAsV3(writer); + writer.Flush(); + stream.Position = 0; - using (var streamReader = new StreamReader(stream)) - { - var result = streamReader.ReadToEnd(); - return OpenApiModelFactory.Parse(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); - } - } + using var streamReader = new StreamReader(stream); + var result = streamReader.ReadToEnd(); + return OpenApiModelFactory.Parse(result, OpenApiSpecVersion.OpenApi3_0, out var _); } public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) { - using (var stream = new MemoryStream()) + using var stream = new MemoryStream(); + var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); + var 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; + InlineLocalReferences = true + }); + element.SerializeAsV3(writer); + writer.Flush(); + stream.Position = 0; - using (var streamReader = new StreamReader(stream)) - { - var result = streamReader.ReadToEnd(); - return OpenApiModelFactory.Parse(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); - } - } + using var streamReader = new StreamReader(stream); + var result = streamReader.ReadToEnd(); + return OpenApiModelFactory.Parse(result, OpenApiSpecVersion.OpenApi3_0, out var _); } [Fact] From 3665930fdf6949fa40f7739b2f0d57c247b88a98 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 Dec 2024 18:07:09 +0300 Subject: [PATCH 24/50] Update src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index 4d4289b81..e8adb5bd5 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -33,7 +33,7 @@ public async Task ReadAsync(Stream input, else { using var preparedStream = new MemoryStream(); - await input.CopyToAsync(preparedStream, copyBufferSize, cancellationToken); + await input.CopyToAsync(preparedStream, copyBufferSize, cancellationToken).ConfigureAwait(false); preparedStream.Position = 0; return Read(preparedStream, settings); } From 5ca061bb05e35a7325a3de84b95eb59121e687e8 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 Dec 2024 18:10:05 +0300 Subject: [PATCH 25/50] Update src/Microsoft.OpenApi/Models/OpenApiDocument.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index b90f1b203..268007141 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -570,7 +570,7 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings /// public static async Task LoadAsync(Stream stream, string? format = null, OpenApiReaderSettings? settings = null, CancellationToken cancellationToken = default) { - return await OpenApiModelFactory.LoadAsync(stream, format, settings, cancellationToken); + return await OpenApiModelFactory.LoadAsync(stream, format, settings, cancellationToken).ConfigureAwait(false); } From e8c76dbdada2c224568c051acb95d83c063ec508 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 Dec 2024 18:10:33 +0300 Subject: [PATCH 26/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index d60e067e0..539f15bf1 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -325,7 +325,7 @@ private static string InspectStreamFormat(Stream stream) { // Use a temporary buffer to read a small portion for format detection using var bufferStream = new MemoryStream(); - await input.CopyToAsync(bufferStream, 1024, token); + await input.CopyToAsync(bufferStream, 1024, token).ConfigureAwait(false); bufferStream.Position = 0; // Inspect the format from the buffered portion From a66e21b511071b7af25f95eeb40ec927f89383a3 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 Dec 2024 18:10:43 +0300 Subject: [PATCH 27/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 539f15bf1..935196a05 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -341,8 +341,8 @@ private static string InspectStreamFormat(Stream stream) // YAML or other non-JSON format; copy remaining input to a new stream. preparedStream = new MemoryStream(); bufferStream.Position = 0; - await bufferStream.CopyToAsync(preparedStream, 81920, token); // Copy buffered portion - await input.CopyToAsync(preparedStream, 81920, token); // Copy remaining data + await bufferStream.CopyToAsync(preparedStream, 81920, token).ConfigureAwait(false); // Copy buffered portion + await input.CopyToAsync(preparedStream, 81920, token).ConfigureAwait(false); // Copy remaining data preparedStream.Position = 0; } } From 4198c82f3fddb404f4bac5029fda6fda04aa3cd8 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 Dec 2024 18:10:52 +0300 Subject: [PATCH 28/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 935196a05..6bdd20454 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -354,7 +354,7 @@ private static string InspectStreamFormat(Stream stream) { // Buffer stream for non-JSON formats (e.g., YAML) since they require synchronous reading preparedStream = new MemoryStream(); - await input.CopyToAsync(preparedStream, 81920, token); + await input.CopyToAsync(preparedStream, 81920, token).ConfigureAwait(false); preparedStream.Position = 0; } } From 0836e97d4b21966ee6aa75278fea812e25cb5e77 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 11 Dec 2024 10:12:32 -0500 Subject: [PATCH 29/50] chore: code linting Signed-off-by: Vincent Biret --- .../V3Tests/OpenApiDocumentTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index a0ffc90c1..e2274efab 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -32,7 +32,7 @@ public OpenApiDocumentTests() OpenApiReaderRegistry.RegisterReader(OpenApiConstants.Yaml, new OpenApiYamlReader()); } - public T Clone(T element) where T : IOpenApiSerializable + private static T Clone(T element) where T : IOpenApiSerializable { using var stream = new MemoryStream(); var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); @@ -49,7 +49,7 @@ public T Clone(T element) where T : IOpenApiSerializable return OpenApiModelFactory.Parse(result, OpenApiSpecVersion.OpenApi3_0, out var _); } - public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) + private static OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) { using var stream = new MemoryStream(); var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); From a5e1057c2036b8d8d31346dd93e193905624c6a2 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 Dec 2024 18:15:13 +0300 Subject: [PATCH 30/50] Update src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index 862cccf39..7f5b2bcd3 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -121,7 +121,7 @@ public async Task ReadAsync(Stream input, // Parse the JSON text in the TextReader into JsonNodes try { - jsonNode = await JsonNode.ParseAsync(input); + jsonNode = await JsonNode.ParseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (JsonException ex) { From 01e4f4940598008dac81d2fc2f288988bbcd65ec Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 11 Dec 2024 10:17:11 -0500 Subject: [PATCH 31/50] chore: adds missing defensive programming and passes settings when required Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index e8adb5bd5..f66276a9b 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -11,6 +11,7 @@ using SharpYaml.Serialization; using System.Linq; using Microsoft.OpenApi.Models; +using System; namespace Microsoft.OpenApi.Readers { @@ -26,6 +27,7 @@ public async Task ReadAsync(Stream input, OpenApiReaderSettings settings, CancellationToken cancellationToken = default) { + if (input is null) throw new ArgumentNullException(nameof(input)); if (input is MemoryStream memoryStream) { return Read(memoryStream, settings); @@ -43,6 +45,8 @@ public async Task ReadAsync(Stream input, public ReadResult Read(MemoryStream input, OpenApiReaderSettings settings) { + if (input is null) throw new ArgumentNullException(nameof(input)); + if (settings is null) throw new ArgumentNullException(nameof(settings)); JsonNode jsonNode; // Parse the YAML text in the TextReader into a sequence of JsonNodes @@ -77,6 +81,7 @@ public T ReadFragment(MemoryStream input, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement { + if (input is null) throw new ArgumentNullException(nameof(input)); JsonNode jsonNode; // Parse the YAML @@ -92,13 +97,13 @@ public T ReadFragment(MemoryStream input, return default; } - return ReadFragment(jsonNode, version, out diagnostic); + return ReadFragment(jsonNode, version, out diagnostic, settings); } /// public T ReadFragment(JsonNode input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement { - return OpenApiReaderRegistry.DefaultReader.ReadFragment(input, version, out diagnostic); + return OpenApiReaderRegistry.DefaultReader.ReadFragment(input, version, out diagnostic, settings); } /// From 07ab67ae0deba3ccb6de97f8b7cb2892efcd12c6 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 Dec 2024 18:19:27 +0300 Subject: [PATCH 32/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 6bdd20454..3462f2592 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -228,7 +228,7 @@ private static async Task LoadExternalRefsAsync(OpenApiDocume // 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, format ?? OpenApiConstants.Json, null, cancellationToken); + return await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document, format ?? OpenApiConstants.Json, null, cancellationToken).ConfigureAwait(false); } private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings) From 3123cb76abc3b638e1d287c262906a86b0461544 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Wed, 11 Dec 2024 18:20:36 +0300 Subject: [PATCH 33/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 3462f2592..130ce3c87 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -108,7 +108,7 @@ public static T Load(MemoryStream input, OpenApiSpecVersion version, string f public static async Task LoadAsync(string url, OpenApiReaderSettings settings = null) { var result = await RetrieveStreamAndFormatAsync(url); - return await LoadAsync(result.Item1, result.Item2, settings); + return await LoadAsync(result.Item1, result.Item2, settings).ConfigureAwait(false); } /// From ab2ddf0f264ccaf6efbf127c23be00adec51be1f Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 11 Dec 2024 10:21:45 -0500 Subject: [PATCH 34/50] fix: default settings in case of null value Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 6bdd20454..35c64fd05 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -200,12 +200,14 @@ public static T Parse(string input, return Load(stream, version, format, out diagnostic, settings); } + private static readonly OpenApiReaderSettings DefaultReaderSettings = new(); + private static async Task InternalLoadAsync(Stream input, string format, OpenApiReaderSettings settings, CancellationToken cancellationToken = default) { var reader = OpenApiReaderRegistry.GetReader(format); var readResult = await reader.ReadAsync(input, settings, cancellationToken); - if (settings.LoadExternalRefs) + if (settings?.LoadExternalRefs ?? DefaultReaderSettings.LoadExternalRefs) { var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.OpenApiDocument, cancellationToken, settings, format); // Merge diagnostics of external reference @@ -233,7 +235,7 @@ private static async Task LoadExternalRefsAsync(OpenApiDocume private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings) { - if (settings.LoadExternalRefs) + if (settings?.LoadExternalRefs ?? DefaultReaderSettings.LoadExternalRefs) { throw new InvalidOperationException("Loading external references are not supported when using synchronous methods."); } From 955f7fbfac065373b11f676c41785bcac6ffb79f Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 19 Dec 2024 15:18:44 +0300 Subject: [PATCH 35/50] Fix issues from resolving merge conflicts --- src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs | 4 ++-- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 6 +++--- .../Services/OpenApiFilterServiceTests.cs | 2 +- .../V3Tests/OpenApiDocumentTests.cs | 4 ++-- test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index a729dc10f..1cdf6bb04 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -128,8 +128,8 @@ public async Task ReadAsync(Stream input, diagnostic.Errors.Add(new OpenApiError($"#line={ex.LineNumber}", $"Please provide the correct format, {ex.Message}")); return new ReadResult { - OpenApiDocument = null, - OpenApiDiagnostic = diagnostic + Document = null, + Diagnostic = diagnostic }; } diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index f9048db17..139e1f80c 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -209,12 +209,12 @@ private static async Task InternalLoadAsync(Stream input, string for if (settings?.LoadExternalRefs ?? DefaultReaderSettings.LoadExternalRefs) { - var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.OpenApiDocument, cancellationToken, settings, format); + var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.Document, cancellationToken, settings, format); // Merge diagnostics of external reference if (diagnosticExternalRefs != null) { - readResult.OpenApiDiagnostic.Errors.AddRange(diagnosticExternalRefs.Errors); - readResult.OpenApiDiagnostic.Warnings.AddRange(diagnosticExternalRefs.Warnings); + readResult.Diagnostic.Errors.AddRange(diagnosticExternalRefs.Errors); + readResult.Diagnostic.Warnings.AddRange(diagnosticExternalRefs.Warnings); } } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs index f51c1ec9b..12293c4e5 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs @@ -232,7 +232,7 @@ public async Task CopiesOverAllReferencedComponentsToTheSubsetDocumentCorrectly( // Act using var stream = File.OpenRead(filePath); - var doc = OpenApiDocument.Load(stream, "yaml").Document; + var doc = (await OpenApiDocument.LoadAsync(stream, "yaml")).Document; var predicate = OpenApiFilterService.CreatePredicate(operationIds: operationIds); var subsetOpenApiDocument = OpenApiFilterService.CreateFilteredDocument(doc, predicate); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 5c9fd71dc..c281206e3 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -108,7 +108,7 @@ public void ParseInlineStringWithoutProvidingFormatSucceeds() """; var readResult = OpenApiDocument.Parse(stringOpenApiDoc); - readResult.OpenApiDocument.Info.Title.Should().Be("Sample API"); + readResult.Document.Info.Title.Should().Be("Sample API"); } [Fact] @@ -1323,7 +1323,7 @@ public async Task ParseDocWithRefsUsingProxyReferencesSucceeds() using var stream = Resources.GetStream(System.IO.Path.Combine(SampleFolderPath, "minifiedPetStore.yaml")); // Act - var doc = OpenApiDocument.Load(stream, "yaml").Document; + var doc = (await OpenApiDocument.LoadAsync(stream)).Document; var actualParam = doc.Paths["/pets"].Operations[OperationType.Get].Parameters[0]; var outputDoc = doc.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0).MakeLineBreaksEnvironmentNeutral(); var expectedParam = expected.Paths["/pets"].Operations[OperationType.Get].Parameters[0]; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index c2e0f192a..5d493fc55 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1702,7 +1702,7 @@ And reading in similar documents(one has a whitespace) yields the same hash code private static async Task ParseInputFileAsync(string filePath) { - var openApiDoc = (await OpenApiDocument.LoadAsync(filePath)).OpenApiDocument; + var openApiDoc = (await OpenApiDocument.LoadAsync(filePath)).Document; return openApiDoc; } From a4933ef3802cc469fdfa1146d3bcfc9e958696bc Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Thu, 19 Dec 2024 15:43:19 +0300 Subject: [PATCH 36/50] Update input doc comments --- src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs | 2 +- src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs | 2 +- src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs | 10 ++++------ 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index 4abfdbddb..3c5046c96 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -49,7 +49,7 @@ public ReadResult Read(MemoryStream input, if (settings is null) throw new ArgumentNullException(nameof(settings)); JsonNode jsonNode; - // Parse the YAML text in the TextReader into a sequence of JsonNodes + // Parse the YAML text in the stream into a sequence of JsonNodes try { using var stream = new StreamReader(input, default, true, -1, settings.LeaveStreamOpen); diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs index 642572985..42e7e466d 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs @@ -17,7 +17,7 @@ public interface IOpenApiReader /// /// Async method to reads the stream and parse it into an Open API document. /// - /// The TextReader input. + /// The stream input. /// The OpenApi reader settings. /// Propagates notification that an operation should be cancelled. /// diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index 1cdf6bb04..d058596dc 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -23,7 +23,7 @@ public class OpenApiJsonReader : IOpenApiReader /// /// Reads the memory stream input and parses it into an Open API document. /// - /// TextReader containing OpenAPI description to parse. + /// Memory stream containing OpenAPI description to parse. /// The Reader settings to be used during parsing. /// public ReadResult Read(MemoryStream input, @@ -33,7 +33,7 @@ public ReadResult Read(MemoryStream input, var diagnostic = new OpenApiDiagnostic(); settings ??= new OpenApiReaderSettings(); - // Parse the JSON text in the TextReader into JsonNodes + // Parse the JSON text in the stream into JsonNodes try { jsonNode = JsonNode.Parse(input); @@ -106,7 +106,7 @@ public ReadResult Read(JsonNode jsonNode, /// /// Reads the stream input asynchronously and parses it into an Open API document. /// - /// TextReader containing OpenAPI description to parse. + /// Memory stream containing OpenAPI description to parse. /// The Reader settings to be used during parsing. /// Propagates notifications that operations should be cancelled. /// @@ -118,7 +118,7 @@ public async Task ReadAsync(Stream input, var diagnostic = new OpenApiDiagnostic(); settings ??= new OpenApiReaderSettings(); - // Parse the JSON text in the TextReader into JsonNodes + // Parse the JSON text in the stream into JsonNodes try { jsonNode = await JsonNode.ParseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -195,7 +195,5 @@ public T ReadFragment(JsonNode input, return (T)element; } - - } } From 538d2ebab86efe39cc2129d967ae293619d70dde Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 19 Dec 2024 16:54:03 +0300 Subject: [PATCH 37/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 139e1f80c..75388c376 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -122,7 +122,7 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings /// The OpenAPI element. public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null) where T : IOpenApiElement { - var result = await RetrieveStreamAndFormatAsync(url); + var result = await RetrieveStreamAndFormatAsync(url).ConfigureAwait(false); return Load(result.Item1, version, out var _, result.Item2, settings); } From f879452ca0e7a836eca8950054d12c70d89dc450 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 19 Dec 2024 16:54:51 +0300 Subject: [PATCH 38/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 75388c376..961a01f71 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -196,7 +196,7 @@ public static T Parse(string input, { format ??= InspectInputFormat(input); settings ??= new OpenApiReaderSettings(); - var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); return Load(stream, version, format, out diagnostic, settings); } From aac99fe98d49d8e8c4ac5c2d381c38e51ab40b45 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 19 Dec 2024 16:55:18 +0300 Subject: [PATCH 39/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 961a01f71..5889b8222 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -140,7 +140,7 @@ public static async Task LoadAsync(Stream input, string format = nul Stream preparedStream; if (format is null) { - var readResult = await PrepareStreamForReadingAsync(input, format, cancellationToken); + var readResult = await PrepareStreamForReadingAsync(input, format, cancellationToken).ConfigureAwait(false); preparedStream = readResult.Item1; format = readResult.Item2; } From e3049a60cbe95f153544eed476d2b680da32046d Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 19 Dec 2024 16:55:45 +0300 Subject: [PATCH 40/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 5889b8222..25d6156cf 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -174,7 +174,7 @@ public static ReadResult Parse(string input, settings ??= new OpenApiReaderSettings(); // Copy string into MemoryStream - var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); return InternalLoad(stream, format, settings); } From 8a17bf2bee62a1c1b25d69bade9119182d9ca003 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Thu, 19 Dec 2024 16:56:11 +0300 Subject: [PATCH 41/50] Update src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 25d6156cf..75c41a89f 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -205,7 +205,7 @@ public static T Parse(string input, private static async Task InternalLoadAsync(Stream input, string format, OpenApiReaderSettings settings, CancellationToken cancellationToken = default) { var reader = OpenApiReaderRegistry.GetReader(format); - var readResult = await reader.ReadAsync(input, settings, cancellationToken); + var readResult = await reader.ReadAsync(input, settings, cancellationToken).ConfigureAwait(false); if (settings?.LoadExternalRefs ?? DefaultReaderSettings.LoadExternalRefs) { From c944a316794651fb705d0f110756dfef5ef684ed Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 11:22:54 +0300 Subject: [PATCH 42/50] Defensive programming; pass cancellation token --- .../Reader/OpenApiJsonReader.cs | 13 ++++++- .../Reader/OpenApiModelFactory.cs | 36 ++++++++++++------- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs index d058596dc..71cf3f8c3 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs @@ -12,6 +12,7 @@ using Microsoft.OpenApi.Validations; using System.Linq; using Microsoft.OpenApi.Interfaces; +using System; namespace Microsoft.OpenApi.Reader { @@ -29,6 +30,9 @@ public class OpenApiJsonReader : IOpenApiReader public ReadResult Read(MemoryStream input, OpenApiReaderSettings settings) { + if (input is null) throw new ArgumentNullException(nameof(input)); + if (settings is null) throw new ArgumentNullException(nameof(settings)); + JsonNode jsonNode; var diagnostic = new OpenApiDiagnostic(); settings ??= new OpenApiReaderSettings(); @@ -62,6 +66,9 @@ public ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null) { + if (jsonNode is null) throw new ArgumentNullException(nameof(jsonNode)); + if (settings is null) throw new ArgumentNullException(nameof(settings)); + var diagnostic = new OpenApiDiagnostic(); var context = new ParsingContext(diagnostic) { @@ -114,9 +121,11 @@ public async Task ReadAsync(Stream input, OpenApiReaderSettings settings, CancellationToken cancellationToken = default) { + if (input is null) throw new ArgumentNullException(nameof(input)); + if (settings is null) throw new ArgumentNullException(nameof(settings)); + JsonNode jsonNode; var diagnostic = new OpenApiDiagnostic(); - settings ??= new OpenApiReaderSettings(); // Parse the JSON text in the stream into JsonNodes try @@ -142,6 +151,8 @@ public T ReadFragment(MemoryStream input, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement { + if (input is null) throw new ArgumentNullException(nameof(input)); + JsonNode jsonNode; // Parse the JSON diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 139e1f80c..3080d2849 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -39,6 +39,7 @@ public static ReadResult Load(MemoryStream stream, string format = null, OpenApiReaderSettings settings = null) { + if (stream is null) throw new ArgumentNullException(nameof(stream)); settings ??= new OpenApiReaderSettings(); // Get the format of the stream if not provided @@ -69,6 +70,7 @@ public static T Load(Stream input, string format = null, OpenApiReaderSettings settings = null) where T : IOpenApiElement { + if (input is null) throw new ArgumentNullException(nameof(input)); if (input is MemoryStream memoryStream) { return Load(memoryStream, version, format, out diagnostic, settings); @@ -104,11 +106,12 @@ public static T Load(MemoryStream input, OpenApiSpecVersion version, string f /// /// The path to the OpenAPI file /// The OpenApi reader settings. + /// /// - public static async Task LoadAsync(string url, OpenApiReaderSettings settings = null) + public static async Task LoadAsync(string url, OpenApiReaderSettings settings = null, CancellationToken token = default) { - var result = await RetrieveStreamAndFormatAsync(url); - return await LoadAsync(result.Item1, result.Item2, settings).ConfigureAwait(false); + var result = await RetrieveStreamAndFormatAsync(url, token).ConfigureAwait(false); + return await LoadAsync(result.Item1, result.Item2, settings, token).ConfigureAwait(false); } /// @@ -118,11 +121,12 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings /// The path to the OpenAPI file /// Version of the OpenAPI specification that the fragment conforms to. /// The OpenApiReader settings. + /// /// Instance of newly created IOpenApiElement. /// The OpenAPI element. - public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null) where T : IOpenApiElement + public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null, CancellationToken token = default) where T : IOpenApiElement { - var result = await RetrieveStreamAndFormatAsync(url); + var result = await RetrieveStreamAndFormatAsync(url, token).ConfigureAwait(false); return Load(result.Item1, version, out var _, result.Item2, settings); } @@ -136,11 +140,13 @@ public static async Task LoadAsync(string url, OpenApiSpecVersion version, /// public static async Task LoadAsync(Stream input, string format = null, OpenApiReaderSettings settings = null, CancellationToken cancellationToken = default) { + if (input is null) throw new ArgumentNullException(nameof(input)); settings ??= new OpenApiReaderSettings(); + Stream preparedStream; if (format is null) { - var readResult = await PrepareStreamForReadingAsync(input, format, cancellationToken); + var readResult = await PrepareStreamForReadingAsync(input, format, cancellationToken).ConfigureAwait(false); preparedStream = readResult.Item1; format = readResult.Item2; } @@ -150,7 +156,7 @@ public static async Task LoadAsync(Stream input, string format = nul } // Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON) - var result = await InternalLoadAsync(preparedStream, format, settings, cancellationToken); + var result = await InternalLoadAsync(preparedStream, format, settings, cancellationToken).ConfigureAwait(false); if (!settings.LeaveStreamOpen) { input.Dispose(); @@ -170,6 +176,7 @@ public static ReadResult Parse(string input, string format = null, OpenApiReaderSettings settings = null) { + if (input is null) throw new ArgumentNullException(nameof(input)); format ??= InspectInputFormat(input); settings ??= new OpenApiReaderSettings(); @@ -194,6 +201,7 @@ public static T Parse(string input, string format = null, OpenApiReaderSettings settings = null) where T : IOpenApiElement { + if (input is null) throw new ArgumentNullException(nameof(input)); format ??= InspectInputFormat(input); settings ??= new OpenApiReaderSettings(); var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)); @@ -209,7 +217,7 @@ private static async Task InternalLoadAsync(Stream input, string for if (settings?.LoadExternalRefs ?? DefaultReaderSettings.LoadExternalRefs) { - var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.Document, cancellationToken, settings, format); + var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.Document, settings, format, cancellationToken).ConfigureAwait(false); // Merge diagnostics of external reference if (diagnosticExternalRefs != null) { @@ -221,7 +229,7 @@ private static async Task InternalLoadAsync(Stream input, string for return readResult; } - private static async Task LoadExternalRefsAsync(OpenApiDocument document, CancellationToken cancellationToken, OpenApiReaderSettings settings, string format = null) + private static async Task LoadExternalRefsAsync(OpenApiDocument document, OpenApiReaderSettings settings, string format = null, CancellationToken token = default) { // Create workspace for all documents to live in. var baseUrl = settings.BaseUrl ?? new Uri(OpenApiConstants.BaseRegistryUri); @@ -230,7 +238,7 @@ private static async Task LoadExternalRefsAsync(OpenApiDocume // 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, format ?? OpenApiConstants.Json, null, cancellationToken).ConfigureAwait(false); + return await workspaceLoader.LoadAsync(new OpenApiReference() { ExternalResource = "/" }, document, format ?? OpenApiConstants.Json, null, token).ConfigureAwait(false); } private static ReadResult InternalLoad(MemoryStream input, string format, OpenApiReaderSettings settings) @@ -246,7 +254,7 @@ private static ReadResult InternalLoad(MemoryStream input, string format, OpenAp return readResult; } - private static async Task<(Stream, string)> RetrieveStreamAndFormatAsync(string url) + private static async Task<(Stream, string)> RetrieveStreamAndFormatAsync(string url, CancellationToken token = default) { if (!string.IsNullOrEmpty(url)) { @@ -256,11 +264,15 @@ private static ReadResult InternalLoad(MemoryStream input, string format, OpenAp if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { - var response = await _httpClient.GetAsync(url); + var response = await _httpClient.GetAsync(url, token).ConfigureAwait(false); var mediaType = response.Content.Headers.ContentType.MediaType; var contentType = mediaType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0]; format = contentType.Split('/').LastOrDefault(); +#if NETSTANDARD2_0 stream = await response.Content.ReadAsStreamAsync(); +#else + stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);; +#endif return (stream, format); } else From 47dca99227d1f357a823034c359027f72ee52e09 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 11:49:28 +0300 Subject: [PATCH 43/50] Code cleanup and fix tests --- .../Interfaces/IOpenApiReader.cs | 4 +- .../Reader/OpenApiModelFactory.cs | 62 +++++++++---------- .../V3Tests/OpenApiEncodingTests.cs | 4 +- .../V3Tests/OpenApiInfoTests.cs | 4 +- .../V3Tests/OpenApiParameterTests.cs | 16 ++--- .../V3Tests/OpenApiXmlTests.cs | 5 +- 6 files changed, 47 insertions(+), 48 deletions(-) diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs index 42e7e466d..8f001df0c 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs @@ -43,7 +43,7 @@ public interface IOpenApiReader /// /// Reads the MemoryStream and parses the fragment of an OpenAPI description into an Open API Element. /// - /// TextReader containing OpenAPI description to parse. + /// Memory stream containing OpenAPI description to parse. /// Version of the OpenAPI specification that the fragment conforms to. /// Returns diagnostic object containing errors detected during parsing. /// The OpenApiReader settings. @@ -53,7 +53,7 @@ public interface IOpenApiReader /// /// Reads the JsonNode input and parses the fragment of an OpenAPI description into an Open API Element. /// - /// TextReader containing OpenAPI description to parse. + /// Memory stream containing OpenAPI description to parse. /// Version of the OpenAPI specification that the fragment conforms to. /// Returns diagnostic object containing errors detected during parsing. /// The OpenApiReader settings. diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index f192cae15..b714667a6 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.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; @@ -54,36 +54,6 @@ public static ReadResult Load(MemoryStream stream, return result; } - /// - /// Reads the stream input and ensures it is buffered before passing it to the Load method. - /// - /// - /// - /// - /// - /// - /// - /// - public static T Load(Stream input, - OpenApiSpecVersion version, - out OpenApiDiagnostic diagnostic, - string format = null, - OpenApiReaderSettings settings = null) where T : IOpenApiElement - { - if (input is null) throw new ArgumentNullException(nameof(input)); - if (input is MemoryStream memoryStream) - { - return Load(memoryStream, version, format, out diagnostic, settings); - } - else - { - memoryStream = new MemoryStream(); - input.CopyTo(memoryStream); - memoryStream.Position = 0; - return Load(memoryStream, version, format, out diagnostic, settings); - } - } - /// /// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element. /// @@ -127,7 +97,7 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null, CancellationToken token = default) where T : IOpenApiElement { var result = await RetrieveStreamAndFormatAsync(url, token).ConfigureAwait(false); - return Load(result.Item1, version, out var _, result.Item2, settings); + return await LoadAsync(result.Item1, version, result.Item2, settings); } /// @@ -165,6 +135,34 @@ public static async Task LoadAsync(Stream input, string format = nul return result; } + /// + /// Reads the stream input and ensures it is buffered before passing it to the Load method. + /// + /// + /// + /// + /// + /// + /// + public static async Task LoadAsync(Stream input, + OpenApiSpecVersion version, + string format = null, + OpenApiReaderSettings settings = null) where T : IOpenApiElement + { + if (input is null) throw new ArgumentNullException(nameof(input)); + if (input is MemoryStream memoryStream) + { + return Load(memoryStream, version, format, out var _, settings); + } + else + { + memoryStream = new MemoryStream(); + await input.CopyToAsync(memoryStream).ConfigureAwait(false); + memoryStream.Position = 0; + return Load(memoryStream, version, format, out var _, settings); + } + } + /// /// Reads the input string and parses it into an Open API document. /// diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs index c2d34493b..91e428c49 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs @@ -35,12 +35,12 @@ public async Task ParseBasicEncodingShouldSucceed() } [Fact] - public void ParseAdvancedEncodingShouldSucceed() + public async Task ParseAdvancedEncodingShouldSucceed() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "advancedEncoding.yaml")); // Act - var encoding = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _); + var encoding = await OpenApiModelFactory.LoadAsync(stream, OpenApiSpecVersion.OpenApi3_0); // Assert encoding.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs index 25da65e9d..fdd5ae8ee 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs @@ -109,12 +109,12 @@ public async Task ParseBasicInfoShouldSucceed() } [Fact] - public void ParseMinimalInfoShouldSucceed() + public async Task ParseMinimalInfoShouldSucceed() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "minimalInfo.yaml")); // Act - var openApiInfo = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _, "yaml"); + var openApiInfo = await OpenApiModelFactory.LoadAsync(stream, OpenApiSpecVersion.OpenApi3_0); // Assert openApiInfo.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs index 638c47c4a..a40cb4144 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs @@ -26,13 +26,13 @@ public OpenApiParameterTests() } [Fact] - public void ParsePathParameterShouldSucceed() + public async Task ParsePathParameterShouldSucceed() { // Arrange using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "pathParameter.yaml")); // Act - var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _, "yaml"); + var parameter = await OpenApiModelFactory.LoadAsync(stream, OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( @@ -101,13 +101,13 @@ public async Task ParseQueryParameterWithObjectTypeShouldSucceed() } [Fact] - public void ParseQueryParameterWithObjectTypeAndContentShouldSucceed() + public async Task ParseQueryParameterWithObjectTypeAndContentShouldSucceed() { // Arrange using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "queryParameterWithObjectTypeAndContent.yaml")); // Act - var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _, "yaml"); + var parameter = await OpenApiModelFactory.LoadAsync(stream, OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( @@ -194,13 +194,13 @@ public async Task ParseParameterWithNullLocationShouldSucceed() } [Fact] - public void ParseParameterWithNoLocationShouldSucceed() + public async Task ParseParameterWithNoLocationShouldSucceed() { // Arrange using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "parameterWithNoLocation.yaml")); // Act - var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _); + var parameter = await OpenApiModelFactory.LoadAsync(stream, OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( @@ -218,13 +218,13 @@ public void ParseParameterWithNoLocationShouldSucceed() } [Fact] - public void ParseParameterWithUnknownLocationShouldSucceed() + public async Task ParseParameterWithUnknownLocationShouldSucceed() { // Arrange using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "parameterWithUnknownLocation.yaml")); // Act - var parameter = OpenApiModelFactory.Load(stream, OpenApiSpecVersion.OpenApi3_0, out _); + var parameter = await OpenApiModelFactory.LoadAsync(stream, OpenApiSpecVersion.OpenApi3_0); // Assert parameter.Should().BeEquivalentTo( diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs index aab130202..fc23865ba 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs @@ -3,6 +3,7 @@ using System; using System.IO; +using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Reader; @@ -21,10 +22,10 @@ public OpenApiXmlTests() } [Fact] - public void ParseBasicXmlShouldSucceed() + public async Task ParseBasicXmlShouldSucceed() { // Act - var xml = OpenApiModelFactory.Load(Resources.GetStream(Path.Combine(SampleFolderPath, "basicXml.yaml")), OpenApiSpecVersion.OpenApi3_0, out _); + var xml = await OpenApiModelFactory.LoadAsync(Resources.GetStream(Path.Combine(SampleFolderPath, "basicXml.yaml")), OpenApiSpecVersion.OpenApi3_0); // Assert xml.Should().BeEquivalentTo( From e243f4efcb74d489a616962956ae885134d2e3c0 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 12:06:36 +0300 Subject: [PATCH 44/50] simplify tuple variables --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index b714667a6..32bf3dccf 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -80,8 +80,8 @@ public static T Load(MemoryStream input, OpenApiSpecVersion version, string f /// public static async Task LoadAsync(string url, OpenApiReaderSettings settings = null, CancellationToken token = default) { - var result = await RetrieveStreamAndFormatAsync(url, token).ConfigureAwait(false); - return await LoadAsync(result.Item1, result.Item2, settings, token).ConfigureAwait(false); + var (stream, format) = await RetrieveStreamAndFormatAsync(url, token).ConfigureAwait(false); + return await LoadAsync(stream, format, settings, token).ConfigureAwait(false); } /// @@ -96,8 +96,8 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings /// The OpenAPI element. public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null, CancellationToken token = default) where T : IOpenApiElement { - var result = await RetrieveStreamAndFormatAsync(url, token).ConfigureAwait(false); - return await LoadAsync(result.Item1, version, result.Item2, settings); + var (stream, format) = await RetrieveStreamAndFormatAsync(url, token).ConfigureAwait(false); + return await LoadAsync(stream, version, format, settings); } /// @@ -116,9 +116,7 @@ public static async Task LoadAsync(Stream input, string format = nul Stream preparedStream; if (format is null) { - var readResult = await PrepareStreamForReadingAsync(input, format, cancellationToken).ConfigureAwait(false); - preparedStream = readResult.Item1; - format = readResult.Item2; + (preparedStream, format) = await PrepareStreamForReadingAsync(input, format, cancellationToken).ConfigureAwait(false); } else { From 28e1ecd5d48cd4499d5feda1487815c7dd4a6f77 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 12:07:48 +0300 Subject: [PATCH 45/50] Update public API --- .../PublicApi/PublicApi.approved.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index 986eeb4d6..f3aa38ed4 100644 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1323,11 +1323,11 @@ namespace Microsoft.OpenApi.Reader public static Microsoft.OpenApi.Reader.ReadResult Load(System.IO.MemoryStream stream, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } public static T Load(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, string format, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } - public static T Load(System.IO.Stream input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) - where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } - public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } + public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken token = default) { } public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream input, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } - public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.OpenApiSpecVersion version, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) + public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream input, Microsoft.OpenApi.OpenApiSpecVersion version, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) + where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } + public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.OpenApiSpecVersion version, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken token = default) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public static Microsoft.OpenApi.Reader.ReadResult Parse(string input, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } public static T Parse(string input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) From 56742b996ff73a963fa27b26df1a2e4e34f50da7 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 12:31:12 +0300 Subject: [PATCH 46/50] Dispose stream in caller method --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 32bf3dccf..1f1924efb 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -128,6 +128,7 @@ public static async Task LoadAsync(Stream input, string format = nul if (!settings.LeaveStreamOpen) { input.Dispose(); + preparedStream.Dispose(); } return result; From ee637588a4344dee1d03f0b6006bc1f00330adad Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 13:27:22 +0300 Subject: [PATCH 47/50] Abstract implementation detail from interface --- .../OpenApiYamlReader.cs | 9 +++++---- .../Interfaces/IOpenApiReader.cs | 19 ------------------- .../PublicApi/PublicApi.approved.txt | 3 --- 3 files changed, 5 insertions(+), 26 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs index 3c5046c96..95e58c52f 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs @@ -21,6 +21,7 @@ namespace Microsoft.OpenApi.Readers public class OpenApiYamlReader : IOpenApiReader { private const int copyBufferSize = 4096; + private static readonly OpenApiJsonReader _jsonReader = new(); /// public async Task ReadAsync(Stream input, @@ -70,9 +71,9 @@ public ReadResult Read(MemoryStream input, } /// - public ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null) + public static ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null) { - return OpenApiReaderRegistry.DefaultReader.Read(jsonNode, settings, OpenApiConstants.Yaml); + return _jsonReader.Read(jsonNode, settings, OpenApiConstants.Yaml); } /// @@ -101,9 +102,9 @@ public T ReadFragment(MemoryStream input, } /// - public T ReadFragment(JsonNode input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement + public static T ReadFragment(JsonNode input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement { - return OpenApiReaderRegistry.DefaultReader.ReadFragment(input, version, out diagnostic, settings); + return _jsonReader.ReadFragment(input, version, out diagnostic, settings); } /// diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs index 8f001df0c..9398551dd 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs @@ -31,15 +31,6 @@ public interface IOpenApiReader /// ReadResult Read(MemoryStream input, OpenApiReaderSettings settings); - /// - /// Parses the JsonNode input into an Open API document. - /// - /// The JsonNode input. - /// The Reader settings to be used during parsing. - /// The OpenAPI format. - /// - ReadResult Read(JsonNode jsonNode, OpenApiReaderSettings settings, string format = null); - /// /// Reads the MemoryStream and parses the fragment of an OpenAPI description into an Open API Element. /// @@ -49,15 +40,5 @@ public interface IOpenApiReader /// The OpenApiReader settings. /// Instance of newly created IOpenApiElement. T ReadFragment(MemoryStream input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement; - - /// - /// Reads the JsonNode input and parses the fragment of an OpenAPI description into an Open API Element. - /// - /// Memory stream containing OpenAPI description to parse. - /// Version of the OpenAPI specification that the fragment conforms to. - /// Returns diagnostic object containing errors detected during parsing. - /// The OpenApiReader settings. - /// Instance of newly created IOpenApiElement. - T ReadFragment(JsonNode input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings settings = null) where T : IOpenApiElement; } } diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index f3aa38ed4..ddcf4f5c2 100644 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -220,12 +220,9 @@ namespace Microsoft.OpenApi.Interfaces public interface IOpenApiReader { Microsoft.OpenApi.Reader.ReadResult Read(System.IO.MemoryStream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings); - Microsoft.OpenApi.Reader.ReadResult Read(System.Text.Json.Nodes.JsonNode jsonNode, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, string format = null); System.Threading.Tasks.Task ReadAsync(System.IO.Stream input, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings, System.Threading.CancellationToken cancellationToken = default); T ReadFragment(System.IO.MemoryStream input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement; - T ReadFragment(System.Text.Json.Nodes.JsonNode input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) - where T : Microsoft.OpenApi.Interfaces.IOpenApiElement; } public interface IOpenApiReferenceable : Microsoft.OpenApi.Interfaces.IOpenApiElement, Microsoft.OpenApi.Interfaces.IOpenApiSerializable { From 7270a89dc96867a0398ef68d41cce630e7f0a090 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 16:22:10 +0300 Subject: [PATCH 48/50] Dispose preparedStream properly --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index 1f1924efb..d219a6fa9 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -124,14 +124,15 @@ public static async Task LoadAsync(Stream input, string format = nul } // Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON) - var result = await InternalLoadAsync(preparedStream, format, settings, cancellationToken).ConfigureAwait(false); - if (!settings.LeaveStreamOpen) + using (preparedStream) { - input.Dispose(); - preparedStream.Dispose(); + var result = await InternalLoadAsync(preparedStream, format, settings, cancellationToken).ConfigureAwait(false); + if (!settings.LeaveStreamOpen) + { + input.Dispose(); + } + return result; } - - return result; } /// From b033b767a8dc5782fc0bb0b82737c3bb442b6658 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 17:01:19 +0300 Subject: [PATCH 49/50] Pass cancellation token --- src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs index d219a6fa9..31b939548 100644 --- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs +++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs @@ -97,7 +97,7 @@ public static async Task LoadAsync(string url, OpenApiReaderSettings public static async Task LoadAsync(string url, OpenApiSpecVersion version, OpenApiReaderSettings settings = null, CancellationToken token = default) where T : IOpenApiElement { var (stream, format) = await RetrieveStreamAndFormatAsync(url, token).ConfigureAwait(false); - return await LoadAsync(stream, version, format, settings); + return await LoadAsync(stream, version, format, settings, token); } /// @@ -143,11 +143,13 @@ public static async Task LoadAsync(Stream input, string format = nul /// /// /// + /// /// public static async Task LoadAsync(Stream input, OpenApiSpecVersion version, string format = null, - OpenApiReaderSettings settings = null) where T : IOpenApiElement + OpenApiReaderSettings settings = null, + CancellationToken token = default) where T : IOpenApiElement { if (input is null) throw new ArgumentNullException(nameof(input)); if (input is MemoryStream memoryStream) @@ -157,7 +159,7 @@ public static async Task LoadAsync(Stream input, else { memoryStream = new MemoryStream(); - await input.CopyToAsync(memoryStream).ConfigureAwait(false); + await input.CopyToAsync(memoryStream, 81920, token).ConfigureAwait(false); memoryStream.Position = 0; return Load(memoryStream, version, format, out var _, settings); } From c24d670e6cb6ef1d3854aa8fc69792eb5461b580 Mon Sep 17 00:00:00 2001 From: Maggiekimani1 Date: Fri, 20 Dec 2024 17:11:23 +0300 Subject: [PATCH 50/50] Update API --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index ddcf4f5c2..cb7a86b3e 100644 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1322,10 +1322,10 @@ namespace Microsoft.OpenApi.Reader where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken token = default) { } public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream input, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken cancellationToken = default) { } - public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream input, Microsoft.OpenApi.OpenApiSpecVersion version, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) - where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public static System.Threading.Tasks.Task LoadAsync(string url, Microsoft.OpenApi.OpenApiSpecVersion version, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken token = default) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } + public static System.Threading.Tasks.Task LoadAsync(System.IO.Stream input, Microsoft.OpenApi.OpenApiSpecVersion version, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null, System.Threading.CancellationToken token = default) + where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { } public static Microsoft.OpenApi.Reader.ReadResult Parse(string input, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) { } public static T Parse(string input, Microsoft.OpenApi.OpenApiSpecVersion version, out Microsoft.OpenApi.Reader.OpenApiDiagnostic diagnostic, string format = null, Microsoft.OpenApi.Reader.OpenApiReaderSettings settings = null) where T : Microsoft.OpenApi.Interfaces.IOpenApiElement { }