Skip to content

fix: base url should be read from the settings when available #2356

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,11 +241,10 @@
{
settings ??= DefaultReaderSettings.Value;
var reader = settings.GetReader(format);
var location = new Uri(OpenApiConstants.BaseRegistryUri);
if (input is FileStream fileStream)
{
location = new Uri(fileStream.Name);
}
var location =
(input is FileStream fileStream ? new Uri(fileStream.Name) : null) ??
settings.BaseUrl ??
new Uri(OpenApiConstants.BaseRegistryUri);

var readResult = await reader.ReadAsync(input, location, settings, cancellationToken).ConfigureAwait(false);

Expand Down Expand Up @@ -290,7 +289,7 @@
return readResult;
}

private static async Task<(Stream, string?)> RetrieveStreamAndFormatAsync(string url, OpenApiReaderSettings settings, CancellationToken token = default)
private static async Task<(Stream, string?)> RetrieveStreamAndFormatAsync(string url, OpenApiReaderSettings settings, CancellationToken token = default)
{
if (string.IsNullOrEmpty(url))
{
Expand All @@ -307,9 +306,9 @@
var response = await settings.HttpClient.GetAsync(url, token).ConfigureAwait(false);
var mediaType = response.Content.Headers.ContentType?.MediaType;
var contentType = mediaType?.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0];
format = contentType?.Split('/').Last().Split('+').Last().Split('-').Last();

Check warning on line 309 in src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

View workflow job for this annotation

GitHub Actions / Build

Indexing at Count-1 should be used instead of the "Enumerable" extension method "Last" (https://rules.sonarsource.com/csharp/RSPEC-6608)

Check warning on line 309 in src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

View workflow job for this annotation

GitHub Actions / Build

Indexing at Count-1 should be used instead of the "Enumerable" extension method "Last" (https://rules.sonarsource.com/csharp/RSPEC-6608)

Check warning on line 309 in src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

View workflow job for this annotation

GitHub Actions / Build

Indexing at Count-1 should be used instead of the "Enumerable" extension method "Last" (https://rules.sonarsource.com/csharp/RSPEC-6608)

Check warning on line 309 in src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

View workflow job for this annotation

GitHub Actions / Build

Indexing at Count-1 should be used instead of the "Enumerable" extension method "Last" (https://rules.sonarsource.com/csharp/RSPEC-6608)

Check warning on line 309 in src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

View workflow job for this annotation

GitHub Actions / Build

Indexing at Count-1 should be used instead of the "Enumerable" extension method "Last" (https://rules.sonarsource.com/csharp/RSPEC-6608)

Check warning on line 309 in src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

View workflow job for this annotation

GitHub Actions / Build

Indexing at Count-1 should be used instead of the "Enumerable" extension method "Last" (https://rules.sonarsource.com/csharp/RSPEC-6608)
// for non-standard MIME types e.g. text/x-yaml used in older libs or apps

// for non-standard MIME types e.g. text/x-yaml used in older libs or apps
#if NETSTANDARD2_0
stream = await response.Content.ReadAsStreamAsync();
#else
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
{
private readonly Dictionary<string, Uri> _documentsIdRegistry = new();
private readonly Dictionary<Uri, Stream> _artifactsRegistry = new();
private readonly Dictionary<Uri, IOpenApiReferenceable> _IOpenApiReferenceableRegistry = new(new UriWithFragmentEquailityComparer());
private readonly Dictionary<Uri, IOpenApiReferenceable> _IOpenApiReferenceableRegistry = new(new UriWithFragmentEqualityComparer());

private class UriWithFragmentEquailityComparer : IEqualityComparer<Uri>
private sealed class UriWithFragmentEqualityComparer : IEqualityComparer<Uri>
{
public bool Equals(Uri? x, Uri? y)
{
Expand Down Expand Up @@ -84,7 +84,7 @@
/// Registers a document's components into the workspace
/// </summary>
/// <param name="document"></param>
public void RegisterComponents(OpenApiDocument document)

Check warning on line 87 in src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 31 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)

Check warning on line 87 in src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 31 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
if (document?.Components == null) return;

Expand Down Expand Up @@ -271,7 +271,7 @@
/// <param name="value"></param>
public void AddDocumentId(string? key, Uri? value)
{
if (!string.IsNullOrEmpty(key) && key is not null && value is not null && !_documentsIdRegistry.ContainsKey(key))

Check warning on line 274 in src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs

View workflow job for this annotation

GitHub Actions / Build

Change this condition so that it does not always evaluate to 'True'. (https://rules.sonarsource.com/csharp/RSPEC-2589)

Check warning on line 274 in src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs

View workflow job for this annotation

GitHub Actions / Build

Change this condition so that it does not always evaluate to 'True'. (https://rules.sonarsource.com/csharp/RSPEC-2589)
{
_documentsIdRegistry[key] = value;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,10 @@ public async Task LoadDocumentWithExternalReferencesInSubDirectories()
var sampleFolderPath = $"V3Tests/Samples/OpenApiWorkspace/ExternalReferencesInSubDirectories";
var referenceBaseUri = "file://" + Path.GetFullPath(sampleFolderPath);

// Create a reader that will resolve all references also of documentes located in the non-root directory
// Create a reader that will resolve all references also of documents located in the non-root directory
var settings = new OpenApiReaderSettings()
{
LoadExternalRefs = true,
BaseUrl = new Uri("file://")
};
settings.AddYamlReader();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,8 @@ public async Task ParseDocumentWithReferenceByIdGetsResolved()
public async Task ExternalDocumentDereferenceToOpenApiDocumentUsingJsonPointerWorks()
{
// Arrange
var path = Path.Combine(Directory.GetCurrentDirectory(), SampleFolderPath);
var documentName = "externalRefByJsonPointer.yaml";
var path = Path.Combine(Directory.GetCurrentDirectory(), SampleFolderPath, documentName);

var settings = new OpenApiReaderSettings
{
Expand All @@ -524,7 +525,7 @@ public async Task ExternalDocumentDereferenceToOpenApiDocumentUsingJsonPointerWo
settings.AddYamlReader();

// Act
var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, "externalRefByJsonPointer.yaml"), settings);
var result = await OpenApiDocument.LoadAsync(Path.Combine(SampleFolderPath, documentName), settings);
var responseSchema = result.Document.Paths["/resource"].Operations[HttpMethod.Get].Responses["200"].Content["application/json"].Schema;

// Assert
Expand Down
122 changes: 122 additions & 0 deletions test/Microsoft.OpenApi.Tests/Reader/OpenApiModelFactoryTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
using Xunit;
using Microsoft.OpenApi.Reader;
using Microsoft.OpenApi.Models;
using System.Threading.Tasks;
using System.IO;
using System;

namespace Microsoft.OpenApi.Tests.Reader;

public class OpenApiModelFactoryTests
{
[Fact]
public async Task UsesSettingsBaseUrl()
{
var tempFilePathReferee = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
await File.WriteAllTextAsync(tempFilePathReferee,
"""
{
"openapi": "3.1.1",
"info": {
"title": "OData Service for namespace microsoft.graph",
"description": "This OData service is located at https://graph.microsoft.com/v1.0",
"version": "1.0.1"
},
"servers": [
{
"url": "https://graph.microsoft.com/v1.0"
}
],
"paths": {
"/placeholder": {
"get": {
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"type": "string"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"MySchema": {
"type": "object",
"properties": {
"id": {
"type": "string"
}
}
}
}
}
}
""");
var tempFilePathReferrer = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
await File.WriteAllTextAsync(tempFilePathReferrer,
$$$"""
{
"openapi": "3.1.1",
"info": {
"title": "OData Service for namespace microsoft.graph",
"description": "This OData service is located at https://graph.microsoft.com/v1.0",
"version": "1.0.1"
},
"servers": [
{
"url": "https://graph.microsoft.com/v1.0"
}
],
"paths": {
"/placeholder": {
"get": {
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "./{{{Path.GetFileName(tempFilePathReferee)}}}#/components/schemas/MySchema"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"MySchema": {
"type": "object",
"properties": {
"id": {
"type": "string"
}
}
}
}
}
}
""");
// read referrer document to a memory stream
using var stream = new MemoryStream();
using var reader = new StreamReader(tempFilePathReferrer);
await reader.BaseStream.CopyToAsync(stream);
stream.Position = 0;
var baseUri = new Uri(tempFilePathReferrer);
var settings = new OpenApiReaderSettings
{
BaseUrl = baseUri,
};
var readResult = await OpenApiDocument.LoadAsync(stream, settings: settings);
Assert.NotNull(readResult.Document);
Assert.NotNull(readResult.Document.Components);
Assert.Equal(baseUri, readResult.Document.BaseUri);
}
}