forked from confluentinc/confluent-kafka-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonSerializeDeserialize.cs
243 lines (209 loc) · 9.56 KB
/
JsonSerializeDeserialize.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Copyright 2020 Confluent Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Refer to LICENSE for more information.
// ConstructValueSubjectName is still used a an internal implementation detail.
#pragma warning disable CS0618
using Confluent.Kafka;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NJsonSchema.Generation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Confluent.SchemaRegistry.Serdes.UnitTests
{
public class JsonSerializeDeserialzeTests
{
public class UInt32Value
{
public int Value { get; set; }
}
#nullable enable
public class NonNullStringValue
{
public string Value { get; set; } = "";
public NestedNonNullStringValue Nested { get; set; } = new();
}
public class NestedNonNullStringValue
{
public string Value { get; set; } = "";
}
#nullable disable
private class UInt32ValueMultiplyConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var newValue = ((UInt32Value) value).Value * 2;
writer.WriteStartObject();
writer.WritePropertyName("Value");
writer.WriteValue(newValue);
writer.WriteEndObject();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject)
{
reader.Read();
}
var value = reader.ReadAsInt32() ?? 0;
reader.Read();
return new UInt32Value
{
Value = value / 2
};
}
public override bool CanConvert(Type objectType) => objectType == typeof(UInt32Value);
}
public enum EnumType
{
None,
EnumValue = 1234,
OtherValue = 5678
}
public class EnumObject
{
public EnumType Value { get; set; }
}
private ISchemaRegistryClient schemaRegistryClient;
private string testTopic;
private Dictionary<string, int> store = new Dictionary<string, int>();
public JsonSerializeDeserialzeTests()
{
testTopic = "topic";
var schemaRegistryMock = new Mock<ISchemaRegistryClient>();
schemaRegistryMock.Setup(x => x.ConstructValueSubjectName(testTopic, It.IsAny<string>())).Returns($"{testTopic}-value");
schemaRegistryMock.Setup(x => x.RegisterSchemaAsync("topic-value", It.IsAny<string>())).ReturnsAsync(
(string topic, string schema) => store.TryGetValue(schema, out int id) ? id : store[schema] = store.Count + 1
);
schemaRegistryMock.Setup(x => x.GetSchemaAsync(It.IsAny<int>(), It.IsAny<string>())).ReturnsAsync(
(int id, string format) => new Schema(store.Where(x => x.Value == id).First().Key, null, SchemaType.Protobuf)
);
schemaRegistryClient = schemaRegistryMock.Object;
}
[Fact]
public void Null()
{
var jsonSerializer = new JsonSerializer<UInt32Value>(schemaRegistryClient);
var jsonDeserializer = new JsonDeserializer<UInt32Value>();
var bytes = jsonSerializer.SerializeAsync(null, new SerializationContext(MessageComponentType.Value, testTopic)).Result;
Assert.Null(bytes);
Assert.Null(jsonDeserializer.DeserializeAsync(bytes, true, new SerializationContext(MessageComponentType.Value, testTopic)).Result);
}
[Fact]
public void UInt32SerDe()
{
var jsonSerializer = new JsonSerializer<UInt32Value>(schemaRegistryClient);
var jsonDeserializer = new JsonDeserializer<UInt32Value>();
var v = new UInt32Value { Value = 1234 };
var bytes = jsonSerializer.SerializeAsync(v, new SerializationContext(MessageComponentType.Value, testTopic)).Result;
Assert.Equal(v.Value, jsonDeserializer.DeserializeAsync(bytes, false, new SerializationContext(MessageComponentType.Value, testTopic)).Result.Value);
}
[Fact]
public async Task WithJsonSerializerSettingsSerDe()
{
const int value = 1234;
var expectedJson = $"{{\"Value\":{value * 2}}}";
var jsonSchemaGeneratorSettings = new JsonSchemaGeneratorSettings
{
SerializerSettings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new UInt32ValueMultiplyConverter()
},
ContractResolver = new DefaultContractResolver()
}
};
var jsonSerializer = new JsonSerializer<UInt32Value>(schemaRegistryClient, jsonSchemaGeneratorSettings: jsonSchemaGeneratorSettings);
var jsonDeserializer = new JsonDeserializer<UInt32Value>(jsonSchemaGeneratorSettings: jsonSchemaGeneratorSettings);
var v = new UInt32Value { Value = value };
var bytes = await jsonSerializer.SerializeAsync(v, new SerializationContext(MessageComponentType.Value, testTopic));
Assert.NotNull(bytes);
Assert.Equal(expectedJson, Encoding.UTF8.GetString(bytes.AsSpan().Slice(5)));
var actual = await jsonDeserializer.DeserializeAsync(bytes, false, new SerializationContext(MessageComponentType.Value, testTopic));
Assert.NotNull(actual);
Assert.Equal(v.Value, actual.Value);
}
[Theory]
[InlineData(EnumHandling.CamelCaseString, EnumType.EnumValue, "{\"Value\":\"enumValue\"}")]
[InlineData(EnumHandling.String, EnumType.None, "{\"Value\":\"None\"}")]
[InlineData(EnumHandling.Integer, EnumType.OtherValue, "{\"Value\":5678}")]
public async Task WithJsonSchemaGeneratorSettingsSerDe(EnumHandling enumHandling, EnumType value, string expectedJson)
{
var jsonSchemaGeneratorSettings = new JsonSchemaGeneratorSettings
{
DefaultEnumHandling = enumHandling
};
var jsonSerializer = new JsonSerializer<EnumObject>(schemaRegistryClient, jsonSchemaGeneratorSettings: jsonSchemaGeneratorSettings);
var jsonDeserializer = new JsonDeserializer<EnumObject>(jsonSchemaGeneratorSettings: jsonSchemaGeneratorSettings);
var v = new EnumObject { Value = value };
var bytes = await jsonSerializer.SerializeAsync(v, new SerializationContext(MessageComponentType.Value, testTopic));
Assert.NotNull(bytes);
Assert.Equal(expectedJson, Encoding.UTF8.GetString(bytes.AsSpan().Slice(5)));
var actual = await jsonDeserializer.DeserializeAsync(bytes, false, new SerializationContext(MessageComponentType.Value, testTopic));
Assert.NotNull(actual);
Assert.Equal(actual.Value, value);
}
[Fact]
public async Task ValidationFailureReturnsPath()
{
var jsonSerializer = new JsonSerializer<NonNullStringValue>(schemaRegistryClient);
var v = new NonNullStringValue { Value = null };
try
{
await jsonSerializer.SerializeAsync(v, new SerializationContext(MessageComponentType.Value, testTopic));
Assert.True(false, "Serialization did not throw an expected exception");
}
catch (InvalidDataException ex)
{
Assert.Equal("Schema validation failed for properties: [#/Value]", ex.Message);
}
catch (Exception ex)
{
Assert.True(false, $"Serialization threw exception of type {ex.GetType().FullName} instead of the expected {typeof(InvalidDataException).FullName}");
}
}
[Fact]
public async Task NestedValidationFailureReturnsPath()
{
var jsonSerializer = new JsonSerializer<NonNullStringValue>(schemaRegistryClient);
var v = new NonNullStringValue
{
Nested = new()
{
Value = null
}
};
try
{
await jsonSerializer.SerializeAsync(v, new SerializationContext(MessageComponentType.Value, testTopic));
Assert.True(false, "Serialization did not throw an expected exception");
}
catch (InvalidDataException ex)
{
Assert.Equal("Schema validation failed for properties: [#/Nested.Value]", ex.Message);
}
catch (Exception ex)
{
Assert.True(false, $"Serialization threw exception of type {ex.GetType().FullName} instead of the expected {typeof(InvalidDataException).FullName}");
}
}
}
}