-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathAssertHelper.cs
664 lines (567 loc) · 19.6 KB
/
AssertHelper.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
#pragma warning disable CA1031 // Do not catch general exception types
#pragma warning disable IDE0090 // Use 'new(...)'
#pragma warning disable IDE0300 // Collection initialization can be simplified
#if XUNIT_NULLABLE
#nullable enable
#else
// In case this is source-imported with global nullable enabled but no XUNIT_NULLABLE
#pragma warning disable CS8600
#pragma warning disable CS8601
#pragma warning disable CS8603
#pragma warning disable CS8604
#pragma warning disable CS8621
#pragma warning disable CS8625
#pragma warning disable CS8767
#endif
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using Xunit.Sdk;
#if XUNIT_NULLABLE
using System.Diagnostics.CodeAnalysis;
#endif
#if NET6_0_OR_GREATER
using System.Threading.Tasks;
#endif
namespace Xunit.Internal
{
internal static class AssertHelper
{
static readonly Dictionary<char, string> encodings = new Dictionary<char, string>
{
{ '\0', @"\0" }, // Null
{ '\a', @"\a" }, // Alert
{ '\b', @"\b" }, // Backspace
{ '\f', @"\f" }, // Form feed
{ '\n', @"\n" }, // New line
{ '\r', @"\r" }, // Carriage return
{ '\t', @"\t" }, // Horizontal tab
{ '\v', @"\v" }, // Vertical tab
{ '\\', @"\\" }, // Backslash
};
#if XUNIT_NULLABLE
static readonly ConcurrentDictionary<Type, Dictionary<string, Func<object?, object?>>> gettersByType = new ConcurrentDictionary<Type, Dictionary<string, Func<object?, object?>>>();
#else
static readonly ConcurrentDictionary<Type, Dictionary<string, Func<object, object>>> gettersByType = new ConcurrentDictionary<Type, Dictionary<string, Func<object, object>>>();
#endif
#if XUNIT_NULLABLE
static readonly Lazy<Type?> fileSystemInfoType = new Lazy<Type?>(() => GetTypeByName("System.IO.FileSystemInfo"));
static readonly Lazy<PropertyInfo?> fileSystemInfoFullNameProperty = new Lazy<PropertyInfo?>(() => fileSystemInfoType.Value?.GetProperty("FullName"));
#else
static readonly Lazy<Type> fileSystemInfoType = new Lazy<Type>(() => GetTypeByName("System.IO.FileSystemInfo"));
static readonly Lazy<PropertyInfo> fileSystemInfoFullNameProperty = new Lazy<PropertyInfo>(() => fileSystemInfoType.Value?.GetProperty("FullName"));
#endif
static readonly Lazy<Assembly[]> getAssemblies = new Lazy<Assembly[]>(AppDomain.CurrentDomain.GetAssemblies);
static readonly Type objectType = typeof(object);
static readonly IEqualityComparer<object> referenceEqualityComparer = new ReferenceEqualityComparer();
#if XUNIT_NULLABLE
static Dictionary<string, Func<object?, object?>> GetGettersForType(Type type) =>
#else
static Dictionary<string, Func<object, object>> GetGettersForType(Type type) =>
#endif
gettersByType.GetOrAdd(type, _type =>
{
var fieldGetters =
_type
.GetRuntimeFields()
.Where(f => f.IsPublic && !f.IsStatic)
#if XUNIT_NULLABLE
.Select(f => new { name = f.Name, getter = (Func<object?, object?>)f.GetValue });
#else
.Select(f => new { name = f.Name, getter = (Func<object, object>)f.GetValue });
#endif
var propertyGetters =
_type
.GetRuntimeProperties()
.Where(p =>
p.CanRead
&& p.GetMethod != null
&& p.GetMethod.IsPublic
&& !p.GetMethod.IsStatic
#if NET6_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
&& !p.GetMethod.ReturnType.IsByRefLike
#endif
&& p.GetIndexParameters().Length == 0
&& !p.GetCustomAttributes<ObsoleteAttribute>().Any()
&& !p.GetMethod.GetCustomAttributes<ObsoleteAttribute>().Any()
)
#if XUNIT_NULLABLE
.Select(p => new { name = p.Name, getter = (Func<object?, object?>)p.GetValue });
#else
.Select(p => new { name = p.Name, getter = (Func<object, object>)p.GetValue });
#endif
return
fieldGetters
.Concat(propertyGetters)
.ToDictionary(g => g.name, g => g.getter);
});
#if XUNIT_NULLABLE
static Type? GetTypeByName(string typeName)
#else
static Type GetTypeByName(string typeName)
#endif
{
try
{
foreach (var assembly in getAssemblies.Value)
{
var type = assembly.GetType(typeName);
if (type != null)
return type;
}
return null;
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Fatal error: Exception occurred while trying to retrieve type '{0}'", typeName), ex);
}
}
internal static bool IsCompilerGenerated(Type type) =>
type.CustomAttributes.Any(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
internal static string ShortenAndEncodeString(
#if XUNIT_NULLABLE
string? value,
#else
string value,
#endif
int index,
out int pointerIndent)
{
if (value == null)
{
pointerIndent = -1;
return "null";
}
var start = Math.Max(index - 20, 0);
var end = Math.Min(start + 41, value.Length);
start = Math.Max(end - 41, 0);
var printedValue = new StringBuilder(100);
pointerIndent = 0;
if (start > 0)
{
printedValue.Append(ArgumentFormatter.Ellipsis);
pointerIndent += 3;
}
printedValue.Append('\"');
pointerIndent++;
for (var idx = start; idx < end; ++idx)
{
var c = value[idx];
var paddingLength = 1;
if (encodings.TryGetValue(c, out var encoding))
{
printedValue.Append(encoding);
paddingLength = encoding.Length;
}
else
printedValue.Append(c);
if (idx < index)
pointerIndent += paddingLength;
}
printedValue.Append('\"');
if (end < value.Length)
printedValue.Append(ArgumentFormatter.Ellipsis);
return printedValue.ToString();
}
#if XUNIT_NULLABLE
internal static string ShortenAndEncodeString(string? value) =>
#else
internal static string ShortenAndEncodeString(string value) =>
#endif
ShortenAndEncodeString(value, 0, out var _);
#if XUNIT_NULLABLE
internal static string ShortenAndEncodeStringEnd(string? value) =>
#else
internal static string ShortenAndEncodeStringEnd(string value) =>
#endif
ShortenAndEncodeString(value, (value?.Length - 1) ?? 0, out var _);
#if NET6_0_OR_GREATER
#if XUNIT_NULLABLE
[return: NotNullIfNotNull(nameof(data))]
internal static IEnumerable<T>? ToEnumerable<T>(IAsyncEnumerable<T>? data) =>
#else
internal static IEnumerable<T> ToEnumerable<T>(IAsyncEnumerable<T> data) =>
#endif
data == null ? null : ToEnumerableImpl(data);
static IEnumerable<T> ToEnumerableImpl<T>(IAsyncEnumerable<T> data)
{
var enumerator = data.GetAsyncEnumerator();
try
{
while (WaitForValueTask(enumerator.MoveNextAsync()))
yield return enumerator.Current;
}
finally
{
WaitForValueTask(enumerator.DisposeAsync());
}
}
#endif
static bool TryConvert(
object value,
Type targetType,
#if XUNIT_NULLABLE
[NotNullWhen(true)] out object? converted)
#else
out object converted)
#endif
{
try
{
converted = Convert.ChangeType(value, targetType, CultureInfo.CurrentCulture);
return converted != null;
}
catch (InvalidCastException)
{
converted = null;
return false;
}
}
#if XUNIT_NULLABLE
static object? UnwrapLazy(
object? value,
#else
static object UnwrapLazy(
object value,
#endif
out Type valueType)
{
if (value == null)
{
valueType = objectType;
return null;
}
valueType = value.GetType();
if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Lazy<>))
{
var property = valueType.GetRuntimeProperty("Value");
if (property != null)
{
valueType = valueType.GenericTypeArguments[0];
return property.GetValue(value);
}
}
return value;
}
#if XUNIT_NULLABLE
public static EquivalentException? VerifyEquivalence(
object? expected,
object? actual,
#else
public static EquivalentException VerifyEquivalence(
object expected,
object actual,
#endif
bool strict) =>
VerifyEquivalence(expected, actual, strict, string.Empty, new HashSet<object>(referenceEqualityComparer), new HashSet<object>(referenceEqualityComparer), 1);
#if XUNIT_NULLABLE
static EquivalentException? VerifyEquivalence(
object? expected,
object? actual,
#else
static EquivalentException VerifyEquivalence(
object expected,
object actual,
#endif
bool strict,
string prefix,
HashSet<object> expectedRefs,
HashSet<object> actualRefs,
int depth)
{
// Check for exceeded depth
if (depth == 50)
return EquivalentException.ForExceededDepth(50, prefix);
// Unwrap Lazy<T>
expected = UnwrapLazy(expected, out var expectedType);
actual = UnwrapLazy(actual, out var actualType);
// Check for null equivalence
if (expected == null)
return
actual == null
? null
: EquivalentException.ForMemberValueMismatch(expected, actual, prefix);
if (actual == null)
return EquivalentException.ForMemberValueMismatch(expected, actual, prefix);
// Check for identical references
if (ReferenceEquals(expected, actual))
return null;
// Prevent circular references
if (expectedRefs.Contains(expected))
return EquivalentException.ForCircularReference(string.Format(CultureInfo.CurrentCulture, "{0}.{1}", nameof(expected), prefix));
if (actualRefs.Contains(actual))
return EquivalentException.ForCircularReference(string.Format(CultureInfo.CurrentCulture, "{0}.{1}", nameof(actual), prefix));
try
{
expectedRefs.Add(expected);
actualRefs.Add(actual);
// Primitive types, enums and strings should just fall back to their Equals implementation
if (expectedType.IsPrimitive || expectedType.IsEnum || expectedType == typeof(string) || expectedType == typeof(decimal) || expectedType == typeof(Guid))
return VerifyEquivalenceIntrinsics(expected, actual, prefix);
// DateTime and DateTimeOffset need to be compared via IComparable (because of a circular
// reference via the Date property).
if (expectedType == typeof(DateTime) || expectedType == typeof(DateTimeOffset))
return VerifyEquivalenceDateTime(expected, actual, prefix);
// FileSystemInfo has a recursion problem when getting the root directory
if (fileSystemInfoType.Value != null)
if (fileSystemInfoType.Value.IsAssignableFrom(expectedType) && fileSystemInfoType.Value.IsAssignableFrom(actualType))
return VerifyEquivalenceFileSystemInfo(expected, actual, strict, prefix, expectedRefs, actualRefs, depth);
// Uri can throw for relative URIs
var expectedUri = expected as Uri;
var actualUri = actual as Uri;
if (expectedUri != null && actualUri != null)
return VerifyEquivalenceUri(expectedUri, actualUri, prefix);
// IGrouping<TKey,TValue> is special, since it implements IEnumerable<TValue>
var expectedGroupingTypes = ArgumentFormatter.GetGroupingTypes(expected);
if (expectedGroupingTypes != null)
{
var actualGroupingTypes = ArgumentFormatter.GetGroupingTypes(actual);
if (actualGroupingTypes != null)
return VerifyEquivalenceGroupings(expected, expectedGroupingTypes, actual, actualGroupingTypes, strict);
}
// Enumerables? Check equivalence of individual members
if (expected is IEnumerable enumerableExpected && actual is IEnumerable enumerableActual)
return VerifyEquivalenceEnumerable(enumerableExpected, enumerableActual, strict, prefix, expectedRefs, actualRefs, depth);
return VerifyEquivalenceReference(expected, actual, strict, prefix, expectedRefs, actualRefs, depth);
}
finally
{
expectedRefs.Remove(expected);
actualRefs.Remove(actual);
}
}
#if XUNIT_NULLABLE
static EquivalentException? VerifyEquivalenceDateTime(
#else
static EquivalentException VerifyEquivalenceDateTime(
#endif
object expected,
object actual,
string prefix)
{
try
{
if (expected is IComparable expectedComparable)
return
expectedComparable.CompareTo(actual) == 0
? null
: EquivalentException.ForMemberValueMismatch(expected, actual, prefix);
}
catch (Exception ex)
{
return EquivalentException.ForMemberValueMismatch(expected, actual, prefix, ex);
}
try
{
if (actual is IComparable actualComparable)
return
actualComparable.CompareTo(expected) == 0
? null
: EquivalentException.ForMemberValueMismatch(expected, actual, prefix);
}
catch (Exception ex)
{
return EquivalentException.ForMemberValueMismatch(expected, actual, prefix, ex);
}
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
"VerifyEquivalenceDateTime was given non-DateTime(Offset) objects; typeof(expected) = {0}, typeof(actual) = {1}",
ArgumentFormatter.FormatTypeName(expected.GetType()),
ArgumentFormatter.FormatTypeName(actual.GetType())
)
);
}
#if XUNIT_NULLABLE
static EquivalentException? VerifyEquivalenceEnumerable(
#else
static EquivalentException VerifyEquivalenceEnumerable(
#endif
IEnumerable expected,
IEnumerable actual,
bool strict,
string prefix,
HashSet<object> expectedRefs,
HashSet<object> actualRefs,
int depth)
{
#if XUNIT_NULLABLE
var expectedValues = expected.Cast<object?>().ToList();
var actualValues = actual.Cast<object?>().ToList();
#else
var expectedValues = expected.Cast<object>().ToList();
var actualValues = actual.Cast<object>().ToList();
#endif
var actualOriginalValues = actualValues.ToList();
// Walk the list of expected values, and look for actual values that are equivalent
foreach (var expectedValue in expectedValues)
{
var actualIdx = 0;
for (; actualIdx < actualValues.Count; ++actualIdx)
if (VerifyEquivalence(expectedValue, actualValues[actualIdx], strict, "", expectedRefs, actualRefs, depth) == null)
break;
if (actualIdx == actualValues.Count)
return EquivalentException.ForMissingCollectionValue(expectedValue, actualOriginalValues, prefix);
actualValues.RemoveAt(actualIdx);
}
if (strict && actualValues.Count != 0)
return EquivalentException.ForExtraCollectionValue(expectedValues, actualOriginalValues, actualValues, prefix);
return null;
}
#if XUNIT_NULLABLE
static EquivalentException? VerifyEquivalenceFileSystemInfo(
#else
static EquivalentException VerifyEquivalenceFileSystemInfo(
#endif
object expected,
object actual,
bool strict,
string prefix,
HashSet<object> expectedRefs,
HashSet<object> actualRefs,
int depth)
{
if (fileSystemInfoFullNameProperty.Value == null)
throw new InvalidOperationException("Could not find 'FullName' property on type 'System.IO.FileSystemInfo'");
var expectedType = expected.GetType();
var actualType = actual.GetType();
if (expectedType != actualType)
return EquivalentException.ForMismatchedTypes(expectedType, actualType, prefix);
var fullName = fileSystemInfoFullNameProperty.Value.GetValue(expected);
var expectedAnonymous = new { FullName = fullName };
return VerifyEquivalenceReference(expectedAnonymous, actual, strict, prefix, expectedRefs, actualRefs, depth);
}
#if XUNIT_NULLABLE
static EquivalentException? VerifyEquivalenceGroupings(
#else
static EquivalentException VerifyEquivalenceGroupings(
#endif
object expected,
Type[] expectedGroupingTypes,
object actual,
Type[] actualGroupingTypes,
bool strict)
{
var expectedKey = typeof(IGrouping<,>).MakeGenericType(expectedGroupingTypes).GetRuntimeProperty("Key")?.GetValue(expected);
var actualKey = typeof(IGrouping<,>).MakeGenericType(actualGroupingTypes).GetRuntimeProperty("Key")?.GetValue(actual);
var keyException = VerifyEquivalence(expectedKey, actualKey, strict: false);
if (keyException != null)
return keyException;
var toArrayMethod =
typeof(Enumerable)
.GetRuntimeMethods()
.FirstOrDefault(m => m.IsStatic && m.IsPublic && m.Name == nameof(Enumerable.ToArray) && m.GetParameters().Length == 1)
?? throw new InvalidOperationException("Could not find method Enumerable.ToArray<>");
// Convert everything to an array so it doesn't endlessly loop on the IGrouping<> test
var expectedToArrayMethod = toArrayMethod.MakeGenericMethod(expectedGroupingTypes[1]);
var expectedValues = expectedToArrayMethod.Invoke(null, new[] { expected });
var actualToArrayMethod = toArrayMethod.MakeGenericMethod(actualGroupingTypes[1]);
var actualValues = actualToArrayMethod.Invoke(null, new[] { actual });
if (VerifyEquivalence(expectedValues, actualValues, strict) != null)
throw EquivalentException.ForGroupingWithMismatchedValues(expectedValues, actualValues, ArgumentFormatter.Format(expectedKey));
return null;
}
#if XUNIT_NULLABLE
static EquivalentException? VerifyEquivalenceIntrinsics(
#else
static EquivalentException VerifyEquivalenceIntrinsics(
#endif
object expected,
object actual,
string prefix)
{
var result = expected.Equals(actual);
if (!result && TryConvert(expected, actual.GetType(), out var converted))
result = converted.Equals(actual);
if (!result && TryConvert(actual, expected.GetType(), out converted))
result = converted.Equals(expected);
return result ? null : EquivalentException.ForMemberValueMismatch(expected, actual, prefix);
}
#if XUNIT_NULLABLE
static EquivalentException? VerifyEquivalenceReference(
#else
static EquivalentException VerifyEquivalenceReference(
#endif
object expected,
object actual,
bool strict,
string prefix,
HashSet<object> expectedRefs,
HashSet<object> actualRefs,
int depth)
{
Assert.GuardArgumentNotNull(nameof(prefix), prefix);
var prefixDot = prefix.Length == 0 ? string.Empty : prefix + ".";
// Enumerate over public instance fields and properties and validate equivalence
var expectedGetters = GetGettersForType(expected.GetType());
var actualGetters = GetGettersForType(actual.GetType());
if (strict && expectedGetters.Count != actualGetters.Count)
return EquivalentException.ForMemberListMismatch(expectedGetters.Keys, actualGetters.Keys, prefixDot);
foreach (var kvp in expectedGetters)
{
if (!actualGetters.TryGetValue(kvp.Key, out var actualGetter))
return EquivalentException.ForMemberListMismatch(expectedGetters.Keys, actualGetters.Keys, prefixDot);
var expectedMemberValue = kvp.Value(expected);
var actualMemberValue = actualGetter(actual);
var ex = VerifyEquivalence(expectedMemberValue, actualMemberValue, strict, prefixDot + kvp.Key, expectedRefs, actualRefs, depth + 1);
if (ex != null)
return ex;
}
return null;
}
#if XUNIT_NULLABLE
static EquivalentException? VerifyEquivalenceUri(
#else
static EquivalentException VerifyEquivalenceUri(
#endif
Uri expected,
Uri actual,
string prefix)
{
if (expected.OriginalString != actual.OriginalString)
return EquivalentException.ForMemberValueMismatch(expected, actual, prefix);
return null;
}
#if NET6_0_OR_GREATER
static void WaitForValueTask(ValueTask valueTask)
{
var valueTaskAwaiter = valueTask.GetAwaiter();
if (valueTaskAwaiter.IsCompleted)
return;
// Let the task complete on a thread pool thread while we block the main thread
Task.Run(valueTask.AsTask).GetAwaiter().GetResult();
}
static T WaitForValueTask<T>(ValueTask<T> valueTask)
{
var valueTaskAwaiter = valueTask.GetAwaiter();
if (valueTaskAwaiter.IsCompleted)
return valueTaskAwaiter.GetResult();
// Let the task complete on a thread pool thread while we block the main thread
return Task.Run(valueTask.AsTask).GetAwaiter().GetResult();
}
#endif
}
sealed class ReferenceEqualityComparer : IEqualityComparer<object>
{
public new bool Equals(
#if XUNIT_NULLABLE
object? x,
object? y) =>
#else
object x,
object y) =>
#endif
ReferenceEquals(x, y);
#if XUNIT_NULLABLE
public int GetHashCode([DisallowNull] object obj) =>
#else
public int GetHashCode(object obj) =>
#endif
obj.GetHashCode();
}
}