From 11c84b58d8dbd610ac71ac43cd9a89eeea8e7f70 Mon Sep 17 00:00:00 2001 From: Whit Waldo Date: Mon, 23 Oct 2023 23:20:20 -0500 Subject: [PATCH] Added unit test to prove out enum serialization working as expected during event publish Signed-off-by: Whit Waldo --- test/Dapr.Client.Test/PublishEventApiTest.cs | 57 ++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/test/Dapr.Client.Test/PublishEventApiTest.cs b/test/Dapr.Client.Test/PublishEventApiTest.cs index d8caf63d1..77d6ee905 100644 --- a/test/Dapr.Client.Test/PublishEventApiTest.cs +++ b/test/Dapr.Client.Test/PublishEventApiTest.cs @@ -11,6 +11,12 @@ // limitations under the License. // ------------------------------------------------------------------------ +using System.Collections.Immutable; +using System.Linq; +using System.Net.Http; +using System.Text.Json.Serialization; +using Grpc.Net.Client; + namespace Dapr.Client.Test { using System; @@ -51,6 +57,44 @@ public async Task PublishEventAsync_CanPublishTopicWithData() envelope.Metadata.Count.Should().Be(0); } + [Fact] + public async Task PublishEvent_ShouldRespectJsonStringEnumConverter() + { + //The following mimics how the TestClient is built, but adds the JsonStringEnumConverter to the serialization options + var handler = new TestClient.CapturingHandler(); + var httpClient = new HttpClient(handler); + var clientBuilder = new DaprClientBuilder() + .UseJsonSerializationOptions(new JsonSerializerOptions() + { + Converters = {new JsonStringEnumConverter(null, false)} + }) + .UseHttpClientFactory(() => httpClient) + .UseGrpcChannelOptions(new GrpcChannelOptions() + { + HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true + }); + var client = new TestClient(clientBuilder.Build(), handler); + + //Ensure that the JsonStringEnumConverter is registered + client.InnerClient.JsonSerializerOptions.Converters.Count.Should().Be(1); + client.InnerClient.JsonSerializerOptions.Converters.First().GetType().Name.Should() + .Match(nameof(JsonStringEnumConverter)); + + var publishData = new Widget {Size = "Large", Color = WidgetColor.Red}; + var request = await client.CaptureGrpcRequestAsync(async daprClient => + { + await daprClient.PublishEventAsync(TestPubsubName, "test", publishData); + }); + + request.Dismiss(); + + var envelope = await request.GetRequestEnvelopeAsync(); + var jsonFromRequest = envelope.Data.ToStringUtf8(); + jsonFromRequest.Should() + .Be(JsonSerializer.Serialize(publishData, client.InnerClient.JsonSerializerOptions)); + jsonFromRequest.Should().Match("{\"Size\":\"Large\",\"Color\":\"Red\"}"); + } + [Fact] public async Task PublishEventAsync_CanPublishTopicWithData_WithMetadata() { @@ -259,5 +303,18 @@ private class PublishData { public string PublishObjectParameter { get; set; } } + + private class Widget + { + public string Size { get; set; } + public WidgetColor Color { get; set; } + } + + private enum WidgetColor + { + Red, + Green, + Yellow + } } }