-
Notifications
You must be signed in to change notification settings - Fork 758
/
XunitSerializationInfo.cs
622 lines (519 loc) · 24.1 KB
/
XunitSerializationInfo.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Xunit.Abstractions;
using Xunit.Sdk;
#if !NET35
using System.Numerics;
using System.Reflection;
#endif
namespace Xunit.Serialization
{
/// <summary>
/// A mirror class of the CLR's <see cref="T:System.Runtime.Serialization.SerializationInfo"/> class.
/// </summary>
class XunitSerializationInfo : IXunitSerializationInfo
{
readonly IDictionary<string, XunitSerializationTriple> data = new Dictionary<string, XunitSerializationTriple>();
// DateOnly and TimeOnly only exist in .NET 6+, so we must access them via reflection. There is no way for us to
// do this from .NET 3.5 (and doesn't matter, because those types would never exist there) so we have to get all
// this code away from .NET 3.5.
#if !NET35
static readonly Type dateOnlyType = Type.GetType("System.DateOnly");
static readonly Type dateOnlyNullableType = dateOnlyType == null ? null : typeof(Nullable<>).MakeGenericType(dateOnlyType);
static readonly PropertyInfo dateOnlyDayNumber = dateOnlyType?.GetTypeInfo().GetDeclaredProperty("DayNumber");
static readonly MethodInfo dateOnlyFromDayNumber = dateOnlyType?.GetTypeInfo().GetDeclaredMethods("FromDayNumber").FirstOrDefault(m => m.IsPublic && m.IsStatic && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(int));
static readonly Type timeOnlyType = Type.GetType("System.TimeOnly");
static readonly Type timeOnlyNullableType = timeOnlyType == null ? null : typeof(Nullable<>).MakeGenericType(timeOnlyType);
static readonly PropertyInfo timeOnlyTicks = timeOnlyType?.GetTypeInfo().GetDeclaredProperty("Ticks");
static readonly ConstructorInfo timeOnlyCtor = timeOnlyType?.GetTypeInfo().DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == typeof(long));
#endif
static List<Type> supportedSerializationTypes = new()
{
typeof(IXunitSerializable),
typeof(char),
typeof(char?),
typeof(string),
typeof(byte),
typeof(byte?),
typeof(sbyte),
typeof(sbyte?),
typeof(short),
typeof(short?),
typeof(ushort),
typeof(ushort?),
typeof(int),
typeof(int?),
typeof(uint),
typeof(uint?),
typeof(long),
typeof(long?),
typeof(ulong),
typeof(ulong?),
typeof(float),
typeof(float?),
typeof(double),
typeof(double?),
typeof(decimal),
typeof(decimal?),
typeof(bool),
typeof(bool?),
typeof(DateTime),
typeof(DateTime?),
typeof(DateTimeOffset),
typeof(DateTimeOffset?),
#if !NETFRAMEWORK
typeof(BigInteger),
typeof(BigInteger?),
#endif
typeof(TimeSpan),
typeof(TimeSpan?),
};
#if !NET35
static XunitSerializationInfo()
{
if (dateOnlyType != null)
{
supportedSerializationTypes.Add(dateOnlyType);
supportedSerializationTypes.Add(dateOnlyNullableType);
}
if (timeOnlyType != null)
{
supportedSerializationTypes.Add(timeOnlyType);
supportedSerializationTypes.Add(timeOnlyNullableType);
}
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="XunitSerializationInfo"/> class.
/// </summary>
/// <param name="object">The data to copy into the serialization info</param>
public XunitSerializationInfo(IXunitSerializable @object = null)
{
if (@object != null)
@object.Serialize(this);
}
/// <inheritdoc/>
public void AddValue(string key, object value, Type type = null)
{
if (type == null)
type = value == null ? typeof(object) : value.GetType();
data[key] = new XunitSerializationTriple(key, value, type);
}
/// <inheritdoc/>
public T GetValue<T>(string key)
{
return (T)GetValue(key, typeof(T));
}
/// <inheritdoc/>
public object GetValue(string key, Type type)
{
XunitSerializationTriple val;
if (data.TryGetValue(key, out val))
return val.Value;
if (type.IsValueType())
return Activator.CreateInstance(type);
return null;
}
/// <summary>
/// Returns BASE64 encoded string that represents the entirety of the data.
/// </summary>
public string ToSerializedString()
{
return ToBase64(string.Join("\n", data.Select(kvp => SerializeTriple(kvp.Value)).ToArray()));
}
/// <summary>
/// Returns a triple for a key/value pair of data in a complex object
/// </summary>
/// <param name="triple">The triple to be serialized</param>
/// <returns>The serialized version of the triple</returns>
public static string SerializeTriple(XunitSerializationTriple triple)
{
var serializedType = SerializationHelper.GetTypeNameForSerialization(triple.Type);
var serializedValue = Serialize(triple.Value);
// Leaving off the colon is how we indicate null-ness
if (serializedValue == null)
return $"{triple.Key}:{serializedType}";
return $"{triple.Key}:{serializedType}:{serializedValue}";
}
/// <summary>
/// Returns the triple values out of a serialized triple.
/// </summary>
/// <param name="value">The serialized triple</param>
/// <returns>The de-serialized triple</returns>
public static XunitSerializationTriple DeserializeTriple(string value)
{
var pieces = value.Split(new[] { ':' }, 3);
if (pieces.Length < 2)
throw new ArgumentException("Data does not appear to be a valid serialized triple: " + value);
var pieceType = SerializationHelper.GetType(pieces[1]);
var deserializedValue = pieces.Length == 3 ? Deserialize(pieceType, pieces[2]) : null;
return new XunitSerializationTriple(pieces[0], deserializedValue, pieceType);
}
/// <summary>
/// De-serializes a value that was serialized with <see cref="XunitSerializationInfo"/>.
/// </summary>
/// <param name="type">The type of the object to de-serialize into</param>
/// <param name="serializedValue">The serialized value</param>
/// <returns>The de-serialized object</returns>
public static object Deserialize(Type type, string serializedValue)
{
if (serializedValue == null)
return null;
if (typeof(IXunitSerializable).IsAssignableFrom(type))
return DeserializeSerializable(type, serializedValue);
if (type == typeof(char?) || type == typeof(char))
return (char)ushort.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(string))
return FromBase64(serializedValue);
if (type == typeof(byte?) || type == typeof(byte))
return byte.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(sbyte?) || type == typeof(sbyte))
return sbyte.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(short?) || type == typeof(short))
return short.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(ushort?) || type == typeof(ushort))
return ushort.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(int?) || type == typeof(int))
return int.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(uint?) || type == typeof(uint))
return uint.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(long?) || type == typeof(long))
return long.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(ulong?) || type == typeof(ulong))
return ulong.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(float?) || type == typeof(float))
{
var arrSer = (ArraySerializer)DeserializeSerializable(typeof(ArraySerializer), serializedValue);
byte[] bytes = (byte[])arrSer.ArrayData;
return BitConverter.ToSingle(bytes, 0);
}
if (type == typeof(double?) || type == typeof(double))
{
var arrSer = (ArraySerializer)DeserializeSerializable(typeof(ArraySerializer), serializedValue);
byte[] bytes = (byte[])arrSer.ArrayData;
return BitConverter.ToDouble(bytes, 0);
}
if (type == typeof(decimal?) || type == typeof(decimal))
return decimal.Parse(serializedValue, CultureInfo.InvariantCulture);
if (type == typeof(bool?) || type == typeof(bool))
return bool.Parse(serializedValue);
if (type == typeof(DateTime?) || type == typeof(DateTime))
{
var styles = serializedValue.EndsWith("Z", StringComparison.Ordinal) ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None;
return DateTime.Parse(serializedValue, CultureInfo.InvariantCulture, styles);
}
if (type == typeof(DateTimeOffset?) || type == typeof(DateTimeOffset))
{
var styles = serializedValue.EndsWith("Z", StringComparison.Ordinal) ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None;
return DateTimeOffset.Parse(serializedValue, CultureInfo.InvariantCulture, styles);
}
#if !NET35
if ((type == dateOnlyType || type == dateOnlyNullableType) && dateOnlyFromDayNumber != null)
return dateOnlyFromDayNumber.Invoke(null, new object[] { int.Parse(serializedValue, CultureInfo.InvariantCulture) });
if ((type == timeOnlyType || type == timeOnlyNullableType) && timeOnlyCtor != null)
return timeOnlyCtor.Invoke(new object[] { long.Parse(serializedValue, CultureInfo.InvariantCulture) });
if (type == typeof(TimeSpan?) || type == typeof(TimeSpan))
return TimeSpan.Parse(serializedValue, CultureInfo.InvariantCulture);
#endif
#if !NETFRAMEWORK
if (type == typeof(BigInteger?) || type == typeof(BigInteger))
return BigInteger.Parse(serializedValue, CultureInfo.InvariantCulture);
#endif
if (type == typeof(Type))
return SerializationHelper.GetType(serializedValue);
if (type.IsEnum() || type.IsNullableEnum())
return Enum.Parse(type.UnwrapNullable(), serializedValue);
if (type.IsArray)
{
var arrSer = (ArraySerializer)DeserializeSerializable(typeof(ArraySerializer), serializedValue);
return arrSer.ArrayData;
}
throw new ArgumentException("We don't know how to de-serialize type " + type.FullName, nameof(serializedValue));
}
static IXunitSerializable DeserializeSerializable(Type type, string serializedValue)
{
var serializationInfo = new XunitSerializationInfo();
// Will end up with an empty string if the serialization type did not serialize any data
if (serializedValue != string.Empty)
{
var elements = FromBase64(serializedValue).Split('\n');
foreach (var element in elements)
{
var triple = DeserializeTriple(element);
serializationInfo.data[triple.Key] = triple;
}
}
try
{
var value = (IXunitSerializable)Activator.CreateInstance(type);
value.Deserialize(serializationInfo);
return value;
}
catch (MissingMemberException)
{
throw new InvalidOperationException($"Could not de-serialize type '{type.FullName}' because it lacks a parameterless constructor.");
}
}
/// <summary>
/// Serializes an object.
/// </summary>
/// <param name="value">The value to be serialized</param>
/// <returns>The serialized object</returns>
public static string Serialize(object value)
{
if (value == null)
return null;
var serializable = value as IXunitSerializable;
if (serializable != null)
{
var info = new XunitSerializationInfo();
serializable.Serialize(info);
return info.ToSerializedString();
}
var charData = value as char?;
if (charData != null)
return ((ushort)charData.GetValueOrDefault()).ToString(CultureInfo.InvariantCulture);
var stringData = value as string;
if (stringData != null)
return ToBase64(stringData);
var byteData = value as byte?;
if (byteData != null)
return byteData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var sbyteData = value as sbyte?;
if (sbyteData != null)
return sbyteData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var ushortData = value as ushort?;
if (ushortData != null)
return ushortData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var shortData = value as short?;
if (shortData != null)
return shortData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var uintData = value as uint?;
if (uintData != null)
return uintData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var intData = value as int?;
if (intData != null)
return intData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var ulongData = value as ulong?;
if (ulongData != null)
return ulongData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var longData = value as long?;
if (longData != null)
return longData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var floatData = value as float?;
if (floatData != null)
{
var info = new XunitSerializationInfo();
var arraySer = new ArraySerializer(BitConverter.GetBytes(floatData.GetValueOrDefault()));
arraySer.Serialize(info);
return info.ToSerializedString();
}
var doubleData = value as double?;
if (doubleData != null)
{
var info = new XunitSerializationInfo();
var arraySer = new ArraySerializer(BitConverter.GetBytes(doubleData.GetValueOrDefault()));
arraySer.Serialize(info);
return info.ToSerializedString();
}
var decimalData = value as decimal?;
if (decimalData != null)
return decimalData.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
var booleanData = value as bool?;
if (booleanData != null)
return booleanData.GetValueOrDefault().ToString();
var datetimeData = value as DateTime?;
if (datetimeData != null)
return datetimeData.GetValueOrDefault().ToString("o", CultureInfo.InvariantCulture); // Round-trippable format
var datetimeoffsetData = value as DateTimeOffset?;
if (datetimeoffsetData != null)
return datetimeoffsetData.GetValueOrDefault().ToString("o", CultureInfo.InvariantCulture); // Round-trippable format
var valueType = value.GetType();
#if !NET35
if (valueType == dateOnlyType && dateOnlyDayNumber != null)
return dateOnlyDayNumber.GetValue(value)?.ToString() ?? throw new InvalidOperationException($"Could not call DayNumber on an instance of '{dateOnlyType.FullName}': {value}");
if (valueType == timeOnlyType && timeOnlyTicks != null)
return timeOnlyTicks.GetValue(value)?.ToString() ?? throw new InvalidOperationException($"Could not call Ticks on an instance of '{timeOnlyType.FullName}': {value}");
if (value is TimeSpan)
return ((TimeSpan)value).ToString("c", CultureInfo.InvariantCulture);
#endif
#if !NETFRAMEWORK
if (value is BigInteger)
return ((BigInteger)value).ToString(CultureInfo.InvariantCulture);
#endif
var typeData = value as Type;
if (typeData != null)
return SerializationHelper.GetTypeNameForSerialization(typeData);
if (valueType.IsEnum())
{
if (!valueType.IsFromLocalAssembly())
throw new ArgumentException($"We cannot serialize enum {valueType.FullName}.{value} because it lives in the GAC", nameof(value));
return value.ToString();
}
var arrayData = value as Array;
if (arrayData != null)
{
var info = new XunitSerializationInfo();
var arraySer = new ArraySerializer(arrayData);
arraySer.Serialize(info);
return info.ToSerializedString();
}
throw new ArgumentException($"We don't know how to serialize type {valueType.FullName}", nameof(value));
}
internal static bool CanSerializeObject(object value)
{
if (value == null)
return true;
var valueType = value.GetType();
if (valueType.IsArray)
{
var vector = value as object[];
if (vector != null)
{
// Avoid enumerator allocation and bounds lookups that comes from enumerating a System.Array
foreach (object obj in vector)
if (!CanSerializeObject(obj))
return false;
}
else
{
foreach (object obj in ((Array)value))
if (!CanSerializeObject(obj))
return false;
}
return true;
}
foreach (Type supportedType in supportedSerializationTypes)
if (supportedType.IsAssignableFrom(valueType))
return true;
Type typeToCheck = valueType;
if (valueType.IsEnum() || valueType.IsNullableEnum() || (typeToCheck = value as Type) != null)
return typeToCheck.IsFromLocalAssembly();
return false;
}
static string FromBase64(string serializedValue)
{
var bytes = Convert.FromBase64String(serializedValue);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
static string ToBase64(string value)
{
var bytes = Encoding.UTF8.GetBytes(value);
return Convert.ToBase64String(bytes);
}
internal class ArraySerializer : IXunitSerializable
{
Array array;
readonly Type elementType;
public Array ArrayData { get { return array; } }
public ArraySerializer() { }
public ArraySerializer(Array array)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (!CanSerializeObject(array))
throw new ArgumentException("There is at least one object in this array that cannot be serialized", nameof(array));
this.array = array;
elementType = array.GetType().GetElementType();
}
public void Serialize(IXunitSerializationInfo info)
{
info.AddValue("ElementType", SerializationHelper.GetTypeNameForSerialization(elementType));
info.AddValue("Rank", array.Rank);
info.AddValue("TotalLength", array.Length);
for (int dimension = 0; dimension < array.Rank; dimension++)
{
info.AddValue("Length" + dimension, array.GetLength(dimension));
}
for (int dimension = 0; dimension < array.Rank; dimension++)
{
info.AddValue("LowerBound" + dimension, array.GetLowerBound(dimension));
}
int i = 0;
foreach (object obj in array)
{
info.AddValue("Item" + i, obj);
i++;
}
}
public void Deserialize(IXunitSerializationInfo info)
{
var arrType = SerializationHelper.GetType(info.GetValue<string>("ElementType"));
var rank = info.GetValue<int>("Rank");
var totalLength = info.GetValue<int>("TotalLength");
int[] lengths = new int[rank];
int[] lowerBounds = new int[rank];
for (int i = 0; i < lengths.Length; i++)
{
lengths[i] = info.GetValue<int>("Length" + i);
lowerBounds[i] = info.GetValue<int>("LowerBound" + i);
}
array = Array.CreateInstance(arrType, lengths, lowerBounds);
int[] indices = new int[rank];
for (int i = 0; i < indices.Length; i++)
{
indices[i] = lowerBounds[i];
}
for (int i = 0; i < totalLength; i++)
{
bool complete = false;
for (int dim = rank - 1; dim >= 0; dim--)
{
if (indices[dim] >= lowerBounds[dim] + lengths[dim])
{
if (dim == 0)
{
complete = true;
break;
}
for (int j = dim; j < rank; j++)
indices[j] = lowerBounds[dim];
indices[dim - 1]++;
}
}
if (complete)
{
break;
}
object item = info.GetValue("Item" + i, arrType);
array.SetValue(item, indices);
indices[rank - 1]++;
}
}
}
}
/// <summary>
/// Represents a triple of information used when serializing complex types: the property name,
/// the value to be serialized, and the value's type.
/// </summary>
class XunitSerializationTriple
{
/// <summary>
/// Gets the triple's key
/// </summary>
public readonly string Key;
/// <summary>
/// Gets the triple's value
/// </summary>
public readonly object Value;
/// <summary>
/// Gets the triple's value type
/// </summary>
public readonly Type Type;
/// <summary>
/// Initializes a new instance of the <see cref="XunitSerializationTriple"/> class.
/// </summary>
/// <param name="key">The triple's key</param>
/// <param name="value">The triple's value</param>
/// <param name="type">The triple's value type</param>
public XunitSerializationTriple(string key, object value, Type type)
{
Key = key;
Value = value;
Type = type;
}
}
}