Skip to content

Commit f5d6e81

Browse files
authored
Merge pull request #2356 from microsoft/fix/base-url
fix: base url should be read from the settings when available
2 parents 9095321 + 7b7d4a6 commit f5d6e81

File tree

5 files changed

+135
-14
lines changed

5 files changed

+135
-14
lines changed

src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -241,11 +241,10 @@ private static async Task<ReadResult> InternalLoadAsync(Stream input, string for
241241
{
242242
settings ??= DefaultReaderSettings.Value;
243243
var reader = settings.GetReader(format);
244-
var location = new Uri(OpenApiConstants.BaseRegistryUri);
245-
if (input is FileStream fileStream)
246-
{
247-
location = new Uri(fileStream.Name);
248-
}
244+
var location =
245+
(input is FileStream fileStream ? new Uri(fileStream.Name) : null) ??
246+
settings.BaseUrl ??
247+
new Uri(OpenApiConstants.BaseRegistryUri);
249248

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

@@ -290,7 +289,7 @@ private static ReadResult InternalLoad(MemoryStream input, string format, OpenAp
290289
return readResult;
291290
}
292291

293-
private static async Task<(Stream, string?)> RetrieveStreamAndFormatAsync(string url, OpenApiReaderSettings settings, CancellationToken token = default)
292+
private static async Task<(Stream, string?)> RetrieveStreamAndFormatAsync(string url, OpenApiReaderSettings settings, CancellationToken token = default)
294293
{
295294
if (string.IsNullOrEmpty(url))
296295
{
@@ -308,8 +307,8 @@ private static ReadResult InternalLoad(MemoryStream input, string format, OpenAp
308307
var mediaType = response.Content.Headers.ContentType?.MediaType;
309308
var contentType = mediaType?.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0];
310309
format = contentType?.Split('/').Last().Split('+').Last().Split('-').Last();
311-
312-
// for non-standard MIME types e.g. text/x-yaml used in older libs or apps
310+
311+
// for non-standard MIME types e.g. text/x-yaml used in older libs or apps
313312
#if NETSTANDARD2_0
314313
stream = await response.Content.ReadAsStreamAsync();
315314
#else

src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ public class OpenApiWorkspace
1818
{
1919
private readonly Dictionary<string, Uri> _documentsIdRegistry = new();
2020
private readonly Dictionary<Uri, Stream> _artifactsRegistry = new();
21-
private readonly Dictionary<Uri, IOpenApiReferenceable> _IOpenApiReferenceableRegistry = new(new UriWithFragmentEquailityComparer());
21+
private readonly Dictionary<Uri, IOpenApiReferenceable> _IOpenApiReferenceableRegistry = new(new UriWithFragmentEqualityComparer());
2222

23-
private class UriWithFragmentEquailityComparer : IEqualityComparer<Uri>
23+
private sealed class UriWithFragmentEqualityComparer : IEqualityComparer<Uri>
2424
{
2525
public bool Equals(Uri? x, Uri? y)
2626
{

test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,10 @@ public async Task LoadDocumentWithExternalReferencesInSubDirectories()
7878
var sampleFolderPath = $"V3Tests/Samples/OpenApiWorkspace/ExternalReferencesInSubDirectories";
7979
var referenceBaseUri = "file://" + Path.GetFullPath(sampleFolderPath);
8080

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

test/Microsoft.OpenApi.Readers.Tests/V31Tests/OpenApiDocumentTests.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,8 @@ public async Task ParseDocumentWithReferenceByIdGetsResolved()
514514
public async Task ExternalDocumentDereferenceToOpenApiDocumentUsingJsonPointerWorks()
515515
{
516516
// Arrange
517-
var path = Path.Combine(Directory.GetCurrentDirectory(), SampleFolderPath);
517+
var documentName = "externalRefByJsonPointer.yaml";
518+
var path = Path.Combine(Directory.GetCurrentDirectory(), SampleFolderPath, documentName);
518519

519520
var settings = new OpenApiReaderSettings
520521
{
@@ -524,7 +525,7 @@ public async Task ExternalDocumentDereferenceToOpenApiDocumentUsingJsonPointerWo
524525
settings.AddYamlReader();
525526

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

530531
// Assert
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
using Xunit;
2+
using Microsoft.OpenApi.Reader;
3+
using Microsoft.OpenApi.Models;
4+
using System.Threading.Tasks;
5+
using System.IO;
6+
using System;
7+
8+
namespace Microsoft.OpenApi.Tests.Reader;
9+
10+
public class OpenApiModelFactoryTests
11+
{
12+
[Fact]
13+
public async Task UsesSettingsBaseUrl()
14+
{
15+
var tempFilePathReferee = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
16+
await File.WriteAllTextAsync(tempFilePathReferee,
17+
"""
18+
{
19+
"openapi": "3.1.1",
20+
"info": {
21+
"title": "OData Service for namespace microsoft.graph",
22+
"description": "This OData service is located at https://graph.microsoft.com/v1.0",
23+
"version": "1.0.1"
24+
},
25+
"servers": [
26+
{
27+
"url": "https://graph.microsoft.com/v1.0"
28+
}
29+
],
30+
"paths": {
31+
"/placeholder": {
32+
"get": {
33+
"responses": {
34+
"200": {
35+
"content": {
36+
"application/json": {
37+
"schema": {
38+
"type": "string"
39+
}
40+
}
41+
}
42+
}
43+
}
44+
}
45+
}
46+
},
47+
"components": {
48+
"schemas": {
49+
"MySchema": {
50+
"type": "object",
51+
"properties": {
52+
"id": {
53+
"type": "string"
54+
}
55+
}
56+
}
57+
}
58+
}
59+
}
60+
""");
61+
var tempFilePathReferrer = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
62+
await File.WriteAllTextAsync(tempFilePathReferrer,
63+
$$$"""
64+
{
65+
"openapi": "3.1.1",
66+
"info": {
67+
"title": "OData Service for namespace microsoft.graph",
68+
"description": "This OData service is located at https://graph.microsoft.com/v1.0",
69+
"version": "1.0.1"
70+
},
71+
"servers": [
72+
{
73+
"url": "https://graph.microsoft.com/v1.0"
74+
}
75+
],
76+
"paths": {
77+
"/placeholder": {
78+
"get": {
79+
"responses": {
80+
"200": {
81+
"content": {
82+
"application/json": {
83+
"schema": {
84+
"$ref": "./{{{Path.GetFileName(tempFilePathReferee)}}}#/components/schemas/MySchema"
85+
}
86+
}
87+
}
88+
}
89+
}
90+
}
91+
}
92+
},
93+
"components": {
94+
"schemas": {
95+
"MySchema": {
96+
"type": "object",
97+
"properties": {
98+
"id": {
99+
"type": "string"
100+
}
101+
}
102+
}
103+
}
104+
}
105+
}
106+
""");
107+
// read referrer document to a memory stream
108+
using var stream = new MemoryStream();
109+
using var reader = new StreamReader(tempFilePathReferrer);
110+
await reader.BaseStream.CopyToAsync(stream);
111+
stream.Position = 0;
112+
var baseUri = new Uri(tempFilePathReferrer);
113+
var settings = new OpenApiReaderSettings
114+
{
115+
BaseUrl = baseUri,
116+
};
117+
var readResult = await OpenApiDocument.LoadAsync(stream, settings: settings);
118+
Assert.NotNull(readResult.Document);
119+
Assert.NotNull(readResult.Document.Components);
120+
Assert.Equal(baseUri, readResult.Document.BaseUri);
121+
}
122+
}

0 commit comments

Comments
 (0)