Skip to content

Commit 9c86aff

Browse files
authored
Merge pull request #2642 from microsoft/fix/multi-whitespace
fix/multi whitespace
2 parents 76b0159 + 640e59a commit 9c86aff

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,9 @@ SecurityException or
360360

361361
private static string InspectInputFormat(string input)
362362
{
363-
return input.StartsWith("{", StringComparison.OrdinalIgnoreCase) || input.StartsWith("[", StringComparison.OrdinalIgnoreCase) ? OpenApiConstants.Json : OpenApiConstants.Yaml;
363+
var trimmedInput = input.TrimStart();
364+
return trimmedInput.StartsWith("{", StringComparison.OrdinalIgnoreCase) || trimmedInput.StartsWith("[", StringComparison.OrdinalIgnoreCase) ?
365+
OpenApiConstants.Json : OpenApiConstants.Yaml;
364366
}
365367

366368
/// <summary>
@@ -393,7 +395,7 @@ private static bool TryInspectStreamFormat(Stream stream, out string? format)
393395
var firstByte = (char)stream.ReadByte();
394396

395397
// Skip whitespace if present and read the next non-whitespace byte
396-
if (char.IsWhiteSpace(firstByte))
398+
while (char.IsWhiteSpace(firstByte))
397399
{
398400
firstByte = (char)stream.ReadByte();
399401
}

test/Microsoft.OpenApi.Tests/Reader/OpenApiModelFactoryTests.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,32 @@ public async Task CanLoadAnAsyncOnlyStreamInYamlAndDetectFormat()
203203
Assert.Equal("Sample API", document.Info.Title);
204204
}
205205

206+
[Fact]
207+
public async Task CanLoadANonSeekableStreamInJsonAndDetectFormatWhenPrecededBySpaces()
208+
{
209+
// Given
210+
using var memoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(" " + documentJson));
211+
using var nonSeekableStream = new NonSeekableStream(memoryStream);
212+
213+
// When
214+
var (document, _) = await OpenApiDocument.LoadAsync(nonSeekableStream);
215+
216+
// Then
217+
Assert.NotNull(document);
218+
Assert.Equal("Sample API", document.Info.Title);
219+
}
220+
221+
[Fact]
222+
public void CanLoadAStringJsonAndDetectFormatWhenPrecededBySpaces()
223+
{
224+
// When
225+
var (document, _) = OpenApiDocument.Parse(" " + documentJson);
226+
227+
// Then
228+
Assert.NotNull(document);
229+
Assert.Equal("Sample API", document.Info.Title);
230+
}
231+
206232
public sealed class AsyncOnlyStream : Stream
207233
{
208234
private readonly Stream _innerStream;

0 commit comments

Comments
 (0)