-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Stream.Collections.cs
402 lines (346 loc) · 14.8 KB
/
Stream.Collections.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class StreamTests
{
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/35927", typeof(PlatformDetection), nameof(PlatformDetection.IsMonoInterpreter))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/35927", TestPlatforms.Browser)]
public static async Task HandleCollectionsAsync()
{
await RunTestAsync<string>();
await RunTestAsync<ClassWithKVP>();
await RunTestAsync<ImmutableStructWithStrings>();
}
private static async Task RunTestAsync<TElement>()
{
foreach ((Type, int) pair in CollectionTestData<TElement>())
{
Type type = pair.Item1;
int bufferSize = pair.Item2;
// bufferSize * 0.9 is the threshold size from codebase, subtract 2 for [ or { characters, then create a
// string containing (threshold - 2) amount of char 'a' which when written into output buffer produces buffer
// which size equal to or very close to threshold size, then adding the string to the list, then adding a big
// object to the list which changes depth of written json and should cause buffer flush.
int thresholdSize = (int)(bufferSize * 0.9 - 2);
var options = new JsonSerializerOptions
{
DefaultBufferSize = bufferSize,
WriteIndented = true
};
var optionsWithPreservedReferenceHandling = new JsonSerializerOptions(options)
{
ReferenceHandler = ReferenceHandler.Preserve
};
object obj = GetPopulatedCollection<TElement>(type, thresholdSize);
await PerformSerialization<TElement>(obj, type, options);
await PerformSerialization<TElement>(obj, type, optionsWithPreservedReferenceHandling);
}
}
private static async Task PerformSerialization<TElement>(object obj, Type type, JsonSerializerOptions options)
{
string expectedjson = JsonSerializer.Serialize(obj, options);
using var memoryStream = new MemoryStream();
await JsonSerializer.SerializeAsync(memoryStream, obj, options);
string serialized = Encoding.UTF8.GetString(memoryStream.ToArray());
JsonTestHelper.AssertJsonEqual(expectedjson, serialized);
memoryStream.Position = 0;
if (options.ReferenceHandler == null || !GetTypesNonRoundtrippableWithReferenceHandler().Contains(type))
{
await TestDeserialization<TElement>(memoryStream, expectedjson, type, options);
// Deserialize with extra whitespace
string jsonWithWhiteSpace = GetPayloadWithWhiteSpace(expectedjson);
using var memoryStreamWithWhiteSpace = new MemoryStream(Encoding.UTF8.GetBytes(jsonWithWhiteSpace));
await TestDeserialization<TElement>(memoryStreamWithWhiteSpace, expectedjson, type, options);
}
}
private static async Task TestDeserialization<TElement>(
Stream memoryStream,
string expectedJson,
Type type,
JsonSerializerOptions options)
{
try
{
object deserialized = await JsonSerializer.DeserializeAsync(memoryStream, type, options);
string serialized = JsonSerializer.Serialize(deserialized, options);
// Stack elements reversed during serialization.
if (StackTypes<TElement>().Contains(type))
{
deserialized = JsonSerializer.Deserialize(serialized, type, options);
serialized = JsonSerializer.Serialize(deserialized, options);
}
// TODO: https://github.com/dotnet/runtime/issues/35611.
// Can't control order of dictionary elements when serializing, so reference metadata might not match up.
if(!(CollectionTestTypes.DictionaryTypes<TElement>().Contains(type) && options.ReferenceHandler == ReferenceHandler.Preserve))
{
JsonTestHelper.AssertJsonEqual(expectedJson, serialized);
}
}
catch (NotSupportedException ex)
{
Assert.True(GetTypesNotSupportedForDeserialization<TElement>().Contains(type));
Assert.Contains(type.ToString(), ex.ToString());
}
}
private static object GetPopulatedCollection<TElement>(Type type, int stringLength)
{
if (type == typeof(TElement[]))
{
return GetArr_TypedElements<TElement>(stringLength);
}
else if (type == typeof(ImmutableList<TElement>))
{
return ImmutableList.CreateRange(GetArr_TypedElements<TElement>(stringLength));
}
else if (type == typeof(ImmutableStack<TElement>))
{
return ImmutableStack.CreateRange(GetArr_TypedElements<TElement>(stringLength));
}
else if (type == typeof(ImmutableDictionary<string, TElement>))
{
return ImmutableDictionary.CreateRange(GetDict_TypedElements<TElement>(stringLength));
}
else if (type == typeof(KeyValuePair<TElement, TElement>))
{
TElement item = GetCollectionElement<TElement>(stringLength);
return new KeyValuePair<TElement, TElement>(item, item);
}
else if (
typeof(IDictionary<string, TElement>).IsAssignableFrom(type) ||
typeof(IReadOnlyDictionary<string, TElement>).IsAssignableFrom(type) ||
typeof(IDictionary).IsAssignableFrom(type))
{
return Activator.CreateInstance(type, new object[] { GetDict_TypedElements<TElement>(stringLength) });
}
else if (typeof(IEnumerable<TElement>).IsAssignableFrom(type))
{
return Activator.CreateInstance(type, new object[] { GetArr_TypedElements<TElement>(stringLength) });
}
else
{
return Activator.CreateInstance(type, new object[] { GetArr_BoxedElements<TElement>(stringLength) });
}
}
private static object GetEmptyCollection<TElement>(Type type)
{
if (type == typeof(TElement[]))
{
return Array.Empty<TElement>();
}
else if (type == typeof(ImmutableList<TElement>))
{
return ImmutableList.CreateRange(Array.Empty<TElement>());
}
else if (type == typeof(ImmutableStack<TElement>))
{
return ImmutableStack.CreateRange(Array.Empty<TElement>());
}
else if (type == typeof(ImmutableDictionary<string, TElement>))
{
return ImmutableDictionary.CreateRange(new Dictionary<string, TElement>());
}
else
{
return Activator.CreateInstance(type);
}
}
private static string GetPayloadWithWhiteSpace(string json) => json.Replace(" ", new string(' ', 8));
private const int NumElements = 15;
private static TElement[] GetArr_TypedElements<TElement>(int stringLength)
{
Debug.Assert(NumElements > 2);
var arr = new TElement[NumElements];
TElement item = GetCollectionElement<TElement>(stringLength);
arr[0] = item;
for (int i = 1; i < NumElements - 1; i++)
{
arr[i] = GetCollectionElement<TElement>(stringLength);
}
arr[NumElements - 1] = item;
return arr;
}
private static object[] GetArr_BoxedElements<TElement>(int stringLength)
{
Debug.Assert(NumElements > 2);
var arr = new object[NumElements];
TElement item = GetCollectionElement<TElement>(stringLength);
arr[0] = item;
for (int i = 1; i < NumElements - 1; i++)
{
arr[i] = GetCollectionElement<TElement>(stringLength);
}
arr[NumElements - 1] = item;
return arr;
}
private static Dictionary<string, TElement> GetDict_TypedElements<TElement>(int stringLength)
{
Debug.Assert(NumElements > 2);
TElement item = GetCollectionElement<TElement>(stringLength);
var dict = new Dictionary<string, TElement>();
dict[$"{item}0"] = item;
for (int i = 1; i < NumElements - 1; i++)
{
TElement newItem = GetCollectionElement<TElement>(stringLength);
dict[$"{newItem}{i}"] = newItem;
}
dict[$"{item}{NumElements - 1}"] = item;
return dict;
}
private static TElement GetCollectionElement<TElement>(int stringLength)
{
Type type = typeof(TElement);
Random rand = new Random();
char randomChar = (char)rand.Next('a', 'z');
string value = new string(randomChar, stringLength);
var kvp = new KeyValuePair<string, SimpleStruct>(value, new SimpleStruct {
One = 1,
Two = 2
});
if (type == typeof(string))
{
return (TElement)(object)value;
}
else if (type == typeof(ClassWithKVP))
{
return (TElement)(object)new ClassWithKVP { MyKvp = kvp };
}
else
{
return (TElement)(object)new ImmutableStructWithStrings(value, value);
}
throw new NotImplementedException();
}
private static IEnumerable<(Type, int)> CollectionTestData<TElement>()
{
foreach (Type type in CollectionTypes<TElement>())
{
foreach (int bufferSize in BufferSizes())
{
yield return (type, bufferSize);
}
}
}
private static IEnumerable<int> BufferSizes()
{
yield return 128;
yield return 1024;
yield return 4096;
yield return 8192;
yield return 16384;
yield return 65536;
}
private static IEnumerable<Type> CollectionTypes<TElement>()
{
foreach (Type type in CollectionTestTypes.EnumerableTypes<TElement>())
{
yield return type;
}
foreach (Type type in ObjectNotationTypes<TElement>())
{
yield return type;
}
// Stack types
foreach (Type type in StackTypes<TElement>())
{
yield return type;
}
// Dictionary types
foreach (Type type in CollectionTestTypes.DictionaryTypes<TElement>())
{
yield return type;
}
}
private static IEnumerable<Type> ObjectNotationTypes<TElement>()
{
yield return typeof(KeyValuePair<TElement, TElement>); // KeyValuePairConverter
}
private static HashSet<Type> StackTypes<TElement>() => new HashSet<Type>
{
typeof(ConcurrentStack<TElement>), // ConcurrentStackOfTConverter
typeof(Stack), // IEnumerableWithAddMethodConverter
typeof(Stack<TElement>), // StackOfTConverter
typeof(ImmutableStack<TElement>) // ImmutableEnumerableOfTConverter
};
private static HashSet<Type> GetTypesNotSupportedForDeserialization<TElement>() => new HashSet<Type>
{
typeof(WrapperForIEnumerable),
typeof(WrapperForIReadOnlyCollectionOfT<TElement>),
typeof(GenericIReadOnlyDictionaryWrapper<string, TElement>)
};
// Non-generic types cannot roundtrip when they contain a $ref written on serialization and they are the root type.
private static HashSet<Type> GetTypesNonRoundtrippableWithReferenceHandler() => new HashSet<Type>
{
typeof(Hashtable),
typeof(Queue),
typeof(Stack),
typeof(WrapperForIList),
typeof(WrapperForIEnumerable)
};
private class ClassWithKVP
{
public KeyValuePair<string, SimpleStruct> MyKvp { get; set; }
}
private struct ImmutableStructWithStrings
{
public string MyFirstString { get; }
public string MySecondString { get; }
[JsonConstructor]
public ImmutableStructWithStrings(
string myFirstString, string mySecondString)
{
MyFirstString = myFirstString;
MySecondString = mySecondString;
}
}
[Theory]
[InlineData("")]
[InlineData("}")]
[InlineData("[")]
[InlineData("]")]
public static void DeserializeDictionaryStartsWithInvalidJson(string json)
{
foreach (Type type in CollectionTestTypes.DictionaryTypes<string>())
{
Assert.ThrowsAsync<JsonException>(async () =>
{
using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
await JsonSerializer.DeserializeAsync(memoryStream, type);
}
});
}
}
[Fact]
public static void SerializeEmptyCollection()
{
foreach (Type type in CollectionTestTypes.EnumerableTypes<int>())
{
Assert.Equal("[]", JsonSerializer.Serialize(GetEmptyCollection<int>(type)));
}
foreach (Type type in StackTypes<int>())
{
Assert.Equal("[]", JsonSerializer.Serialize(GetEmptyCollection<int>(type)));
}
foreach (Type type in CollectionTestTypes.DictionaryTypes<int>())
{
Assert.Equal("{}", JsonSerializer.Serialize(GetEmptyCollection<int>(type)));
}
foreach (Type type in ObjectNotationTypes<int>())
{
Assert.Equal(@"{""Key"":0,""Value"":0}", JsonSerializer.Serialize(GetEmptyCollection<int>(type)));
}
}
}
}