Skip to content

Commit

Permalink
Use JSON source generator in SSE tests (#103126)
Browse files Browse the repository at this point in the history
So that the tests work with AOT.
  • Loading branch information
stephentoub authored Jun 6, 2024
1 parent 0afe5e1 commit 3178a5f
Showing 1 changed file with 9 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
Expand Down Expand Up @@ -508,8 +509,8 @@ public async Task JsonContent_DelegateInvoked(string newline, bool trickle, bool
trickle);

List<SseItem<Book>> items = useAsync ?
await ReadAllEventsAsync(stream, static (eventType, data) => JsonSerializer.Deserialize<Book>(data)) :
ReadAllEvents(stream, static (eventType, data) => JsonSerializer.Deserialize<Book>(data));
await ReadAllEventsAsync(stream, static (eventType, data) => JsonSerializer.Deserialize(data, JsonSerializerTestContext.Default.Book)) :
ReadAllEvents(stream, static (eventType, data) => JsonSerializer.Deserialize(data, JsonSerializerTestContext.Default.Book));

Assert.Equal(2, items.Count);
AssertSseItemEqual(new SseItem<Book>(new Book { title = "The Catcher in the Rye", author = "J.D. Salinger", published_year = 1951, genre = "Fiction" }, "message"), items[0]);
Expand Down Expand Up @@ -654,7 +655,7 @@ public async Task LongLines_ItemsProducedCorrectly(string newline, bool trickle,
{
string[] expected = Enumerable.Range(1, 100).Select(i => string.Concat(Enumerable.Repeat($"{i} ", i))).ToArray();

using Stream stream = GetStream([..expected.Select(s => $"data: {s}{newline}{newline}").SelectMany(Encoding.UTF8.GetBytes)], trickle);
using Stream stream = GetStream([.. expected.Select(s => $"data: {s}{newline}{newline}").SelectMany(Encoding.UTF8.GetBytes)], trickle);

List<SseItem<string>> items = useAsync ?
await ReadAllEventsAsync(stream) :
Expand Down Expand Up @@ -741,7 +742,7 @@ public async Task MultipleItemParsers_OpenAI_StreamingResponse(string newline, b
{
return bytes.SequenceEqual("[DONE]"u8) ?
new ChunkOrDone { Done = true } :
new ChunkOrDone { Json = JsonSerializer.Deserialize<JsonElement>(bytes) };
new ChunkOrDone { Json = JsonSerializer.Deserialize(bytes, JsonSerializerTestContext.Default.JsonElement) };
};

List<SseItem<ChunkOrDone>> items = useAsync ?
Expand Down Expand Up @@ -959,5 +960,9 @@ public override async ValueTask<int> ReadAsync(Memory<byte> buffer, Cancellation
}
#endif
}

[JsonSerializable(typeof(Book))]
[JsonSerializable(typeof(JsonElement))]
private sealed partial class JsonSerializerTestContext : JsonSerializerContext;
}
}

0 comments on commit 3178a5f

Please sign in to comment.