-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathJsonTests.cs
382 lines (318 loc) · 14.1 KB
/
JsonTests.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
using System.Collections;
using System.Text.Json;
using System.Text.Json.Serialization;
using PolyType.Examples.JsonSerializer;
using PolyType.Examples.JsonSerializer.Converters;
using Xunit;
namespace PolyType.Tests;
public abstract partial class JsonTests(ProviderUnderTest providerUnderTest)
{
[Theory]
[MemberData(nameof(TestTypes.GetTestCases), MemberType = typeof(TestTypes))]
public void Roundtrip_Value<T>(TestCase<T> testCase)
{
if (IsUnsupportedBySTJ(testCase))
{
return;
}
JsonConverter<T> converter = GetConverterUnderTest(testCase);
string json = converter.Serialize(testCase.Value);
Assert.Equal(ToJsonBaseline(testCase.Value), json);
if (!providerUnderTest.HasConstructor(testCase) && testCase.Value is not null)
{
Assert.Throws<NotSupportedException>(() => converter.Deserialize(json));
}
else
{
T? deserializedValue = converter.Deserialize(json);
if (testCase.IsEquatable)
{
Assert.Equal(testCase.Value, deserializedValue);
}
else
{
if (testCase.IsStack)
{
deserializedValue = converter.Deserialize(converter.Serialize(deserializedValue));
}
Assert.Equal(json, ToJsonBaseline(deserializedValue));
}
}
}
[Theory]
[MemberData(nameof(TestTypes.GetTestCases), MemberType = typeof(TestTypes))]
public void Roundtrip_Property<T>(TestCase<T> testCase)
{
if (providerUnderTest.Kind is ProviderKind.SourceGen)
{
return;
}
if (IsUnsupportedBySTJ(testCase))
{
return;
}
JsonConverter<PocoWithGenericProperty<T>> converter = JsonSerializerTS.CreateConverter<PocoWithGenericProperty<T>>(providerUnderTest.Provider);
PocoWithGenericProperty<T> poco = new PocoWithGenericProperty<T> { Value = testCase.Value };
string json = converter.Serialize(poco);
Assert.Equal(ToJsonBaseline(poco), json);
if (!providerUnderTest.HasConstructor(testCase))
{
Assert.Throws<NotSupportedException>(() => converter.Deserialize(json));
}
else
{
PocoWithGenericProperty<T>? deserializedValue = converter.Deserialize(json);
Assert.NotNull(deserializedValue);
if (testCase.IsEquatable)
{
Assert.Equal(testCase.Value, deserializedValue.Value);
}
else
{
if (testCase.IsStack)
{
deserializedValue = converter.Deserialize(converter.Serialize(deserializedValue));
}
Assert.Equal(json, ToJsonBaseline(deserializedValue));
}
}
}
[Theory]
[MemberData(nameof(TestTypes.GetTestCases), MemberType = typeof(TestTypes))]
public void Roundtrip_CollectionElement<T>(TestCase<T> testCase)
{
if (providerUnderTest.Kind is ProviderKind.SourceGen)
{
return;
}
if (IsUnsupportedBySTJ(testCase))
{
return;
}
var converter = JsonSerializerTS.CreateConverter<List<T?>>(providerUnderTest.Provider);
var list = new List<T?> { testCase.Value, testCase.Value, testCase.Value };
string json = converter.Serialize(list);
Assert.Equal(ToJsonBaseline(list), json);
if (!providerUnderTest.HasConstructor(testCase))
{
Assert.Throws<NotSupportedException>(() => converter.Deserialize(json));
}
else
{
List<T?>? deserializedValue = converter.Deserialize(json)!;
Assert.NotEmpty(deserializedValue);
if (testCase.IsEquatable)
{
Assert.Equal<T?>(list, deserializedValue);
}
else
{
if (testCase.IsStack)
{
deserializedValue = converter.Deserialize(converter.Serialize(deserializedValue));
}
Assert.Equal(json, ToJsonBaseline(deserializedValue));
}
}
}
[Theory]
[MemberData(nameof(TestTypes.GetTestCases), MemberType = typeof(TestTypes))]
public void Roundtrip_DictionaryEntry<T>(TestCase<T> testCase)
{
if (providerUnderTest.Kind is ProviderKind.SourceGen)
{
return;
}
if (IsUnsupportedBySTJ(testCase))
{
return;
}
var converter = JsonSerializerTS.CreateConverter<Dictionary<string, T?>>(providerUnderTest.Provider);
var dict = new Dictionary<string, T?> { ["key1"] = testCase.Value, ["key2"] = testCase.Value, ["key3"] = testCase.Value };
string json = converter.Serialize(dict);
Assert.Equal(ToJsonBaseline(dict), json);
if (!providerUnderTest.HasConstructor(testCase))
{
Assert.Throws<NotSupportedException>(() => converter.Deserialize(json));
}
else
{
Dictionary<string, T?>? deserializedValue = converter.Deserialize(json)!;
Assert.NotEmpty(deserializedValue);
if (testCase.IsEquatable)
{
Assert.Equal<KeyValuePair<string, T?>>(dict, deserializedValue);
}
else
{
if (testCase.IsStack)
{
deserializedValue = converter.Deserialize(converter.Serialize(deserializedValue));
}
Assert.Equal(json, ToJsonBaseline(deserializedValue));
}
}
}
[Fact]
public void Serialize_NonNullablePropertyWithNullValue_ThrowsJsonException()
{
var invalidValue = new NonNullStringRecord(null!);
var converter = JsonSerializerTS.CreateConverter<NonNullStringRecord>(providerUnderTest.Provider);
Assert.Throws<JsonException>(() => converter.Serialize(invalidValue));
}
[Fact]
public void Deserialize_NonNullablePropertyWithNullJsonValue_ThrowsJsonException()
{
var converter = JsonSerializerTS.CreateConverter<NonNullStringRecord>(providerUnderTest.Provider);
Assert.Throws<JsonException>(() => converter.Deserialize("""{"value":null}"""));
}
[Fact]
public void Serialize_NullablePropertyWithNullValue_WorksAsExpected()
{
var converter = JsonSerializerTS.CreateConverter<NullableStringRecord>(providerUnderTest.Provider);
var valueWithNull = new NullableStringRecord(null);
string json = converter.Serialize(valueWithNull);
Assert.Equal("""{"value":null}""", json);
}
[Fact]
public void Serialize_NullablePropertyWithNullJsonValue_WorksAsExpected()
{
var converter = JsonSerializerTS.CreateConverter<NullableStringRecord>(providerUnderTest.Provider);
NullableStringRecord? result = converter.Deserialize("""{"value":null}""");
Assert.NotNull(result);
Assert.Null(result.value);
}
[Theory]
[MemberData(nameof(GetLongTuplesAndExpectedJson))]
public void LongTuples_SerializedAsFlatJson<TTuple>(TestCase<TTuple> testCase, string expectedEncoding)
{
// Tuples should be serialized as flat JSON, without exposing "Rest" fields.
var converter = GetConverterUnderTest(testCase);
string json = converter.Serialize(testCase.Value);
Assert.Equal(expectedEncoding, json);
var deserializedValue = converter.Deserialize(json);
Assert.Equal(testCase.Value, deserializedValue);
}
public static IEnumerable<object?[]> GetLongTuplesAndExpectedJson()
{
ITypeShapeProvider p = Witness.ShapeProvider;
yield return [TestCase.Create(
(x1: 1, x2: 2, x3: 3, x4: 4, x5: 5, x6: 6, x7: 7, x8: 8, x9: 9),p),
"""{"Item1":1,"Item2":2,"Item3":3,"Item4":4,"Item5":5,"Item6":6,"Item7":7,"Item8":8,"Item9":9}"""];
yield return [TestCase.Create(
(x1: 1, x2: 2, x3: 3, x4: 4, x5: 5, x6: 6, x7: 7, x8: 8, x9: 9, x10: 10, x11: 11, x12: 12, x13: 13, x14: 14, x15: 15, x16: 16, x17: 17, x18: 18, x19:19, x20:20, x21:21, x22:22, x23:23, x24:24, x25:25, x26:26, x27:27, x28:28, x29:29, x30:30), p),
"""{"Item1":1,"Item2":2,"Item3":3,"Item4":4,"Item5":5,"Item6":6,"Item7":7,"Item8":8,"Item9":9,"Item10":10,"Item11":11,"Item12":12,"Item13":13,"Item14":14,"Item15":15,"Item16":16,"Item17":17,"Item18":18,"Item19":19,"Item20":20,"Item21":21,"Item22":22,"Item23":23,"Item24":24,"Item25":25,"Item26":26,"Item27":27,"Item28":28,"Item29":29,"Item30":30}"""];
yield return [TestCase.Create(
new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>>(1, 2, 3, 4, 5, 6, 7, new(8, 9, 10)), p),
"""{"Item1":1,"Item2":2,"Item3":3,"Item4":4,"Item5":5,"Item6":6,"Item7":7,"Item8":8,"Item9":9,"Item10":10}"""];
yield return [TestCase.Create(
new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int, int, int, int, int, Tuple<int>>>(1, 2, 3, 4, 5, 6, 7, new(8, 9, 10, 11, 12, 13, 14, new(15))), p),
"""{"Item1":1,"Item2":2,"Item3":3,"Item4":4,"Item5":5,"Item6":6,"Item7":7,"Item8":8,"Item9":9,"Item10":10,"Item11":11,"Item12":12,"Item13":13,"Item14":14,"Item15":15}"""];
}
[Theory]
[MemberData(nameof(GetMultiDimensionalArraysAndExpectedJson))]
public void MultiDimensionalArrays_SerializedAsJaggedArray<TArray>(TestCase<TArray> testCase, string expectedEncoding)
where TArray : IEnumerable
{
var converter = GetConverterUnderTest(testCase);
string json = converter.Serialize(testCase.Value);
Assert.Equal(expectedEncoding, json);
TArray? result = converter.Deserialize(json);
Assert.Equal(testCase.Value, result);
}
public static IEnumerable<object?[]> GetMultiDimensionalArraysAndExpectedJson()
{
#if NET8_0_OR_GREATER
Witness p = new();
#else
ITypeShapeProvider p = Witness.ShapeProvider;
#endif
yield return [TestCase.Create(new int[,] { }, p), """[]"""];
yield return [TestCase.Create(new int[,,] { }, p), """[]"""];
yield return [TestCase.Create(new int[,,,,,] { }, p), """[]"""];
yield return [TestCase.Create(
new int[,] { { 1, 0, }, { 0, 1 } }, p),
"""[[1,0],[0,1]]"""];
yield return [TestCase.Create(
new int[,] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }, p),
"""[[1,0,0],[0,1,0],[0,0,1]]"""];
yield return [TestCase.Create(
new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }, p),
"""[[1,2,3],[4,5,6]]"""];
yield return [TestCase.Create(
new int[,,] // 3 x 2 x 2
{
{ { 1, 0 }, { 0, 1 } },
{ { 1, 2 }, { 3, 4 } },
{ { 1, 1 }, { 1, 1 } }
}, p),
"""[[[1,0],[0,1]],[[1,2],[3,4]],[[1,1],[1,1]]]"""];
yield return [TestCase.Create(
new int[,,] // 3 x 2 x 5
{
{ { 1, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0 } },
{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 } },
{ { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 } }
}, p),
"""[[[1,0,0,0,0],[0,1,0,0,0]],[[1,2,3,4,5],[6,7,8,9,10]],[[1,1,1,1,1],[1,1,1,1,1]]]"""];
}
[Fact]
public void Roundtrip_DerivedClassWithVirtualProperties()
{
const string ExpectedJson = """{"X":42,"Y":"str","Z":42,"W":0}""";
var converter = JsonSerializerTS.CreateConverter<DerivedClassWithVirtualProperties>(providerUnderTest.Provider);
var value = new DerivedClassWithVirtualProperties();
string json = converter.Serialize(value);
Assert.Equal(ExpectedJson, json);
}
[Fact]
public void Roundtrip_ClassWithMarshaller()
{
const string ExpectedJson = "\"the actual value\"";
var converter = JsonSerializerTS.CreateConverter<TypeWithStringSurrogate>(providerUnderTest.Provider);
TypeWithStringSurrogate value = new("the actual value");
string json = converter.Serialize(value);
Assert.Equal(ExpectedJson, json);
TypeWithStringSurrogate? deserializedValue = converter.Deserialize(json);
Assert.Equal(value, deserializedValue);
}
[Fact]
public void ClassWithInitOnlyProperties_MissingPayloadPreservesDefaultValues()
{
var converter = JsonSerializerTS.CreateConverter<ClassWithInitOnlyProperties>(providerUnderTest.Provider);
int expectedValue = new ClassWithInitOnlyProperties().Value;
List<int> expectedValues = new ClassWithInitOnlyProperties().Values;
ClassWithInitOnlyProperties? result = converter.Deserialize("{}");
Assert.Equal(expectedValue, result?.Value);
Assert.Equal(expectedValues, result?.Values);
}
public class PocoWithGenericProperty<T>
{
public T? Value { get; set; }
}
protected static string ToJsonBaseline<T>(T? value) => System.Text.Json.JsonSerializer.Serialize(value, s_baselineOptions);
private static readonly JsonSerializerOptions s_baselineOptions = new()
{
IncludeFields = true,
Converters =
{
new JsonStringEnumConverter(),
new BigIntegerConverter(),
#if NET8_0_OR_GREATER
new RuneConverter(),
#endif
},
};
private JsonConverter<T> GetConverterUnderTest<T>(TestCase<T> testCase) =>
JsonSerializerTS.CreateConverter(providerUnderTest.ResolveShape(testCase));
private protected static bool IsUnsupportedBySTJ<T>(TestCase<T> value) =>
value.IsMultiDimensionalArray ||
value.IsLongTuple ||
value.HasRefConstructorParameters ||
value.CustomKind is not null ||
value.UsesMarshaller ||
value.Value is DerivedClassWithVirtualProperties; // https://github.com/dotnet/runtime/issues/96996
}
public sealed class JsonTests_Reflection() : JsonTests(RefectionProviderUnderTest.NoEmit);
public sealed class JsonTests_ReflectionEmit() : JsonTests(RefectionProviderUnderTest.Emit);
public sealed class JsonTests_SourceGen() : JsonTests(SourceGenProviderUnderTest.Default);