|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 3 | + |
| 4 | +namespace Microsoft.VisualStudio.TestTools.UnitTesting; |
| 5 | + |
| 6 | +public sealed partial class Assert |
| 7 | +{ |
| 8 | + /// <summary> |
| 9 | + /// Walks two object graphs and reports the first structural difference, if any. |
| 10 | + /// </summary> |
| 11 | + private sealed partial class EquivalenceComparer |
| 12 | + { |
| 13 | + private EquivalenceMismatch? CompareDictionaries(DictionaryView expected, DictionaryView actual, Type valueDeclaredType, string path, int depth) |
| 14 | + { |
| 15 | + EquivalenceMismatch? failure = ForEachEntry(expected, isExpected: true, path, kvp => |
| 16 | + { |
| 17 | + string childPath = AppendDictionaryKey(path, kvp.Key); |
| 18 | + |
| 19 | + EquivalenceMismatch? lookup = SafeDictionaryOp( |
| 20 | + actual.TryGetValuePair, |
| 21 | + kvp.Key, |
| 22 | + isExpected: false, |
| 23 | + childPath, |
| 24 | + out DictionaryLookup lookupResult); |
| 25 | + return lookup is not null |
| 26 | + ? lookup |
| 27 | + : !lookupResult.Found |
| 28 | + ? EquivalenceMismatch.MissingKey(childPath, kvp.Key) |
| 29 | + : Compare(kvp.Value, lookupResult.Value, valueDeclaredType, childPath, depth + 1); |
| 30 | + }); |
| 31 | + if (failure is not null) |
| 32 | + { |
| 33 | + return failure; |
| 34 | + } |
| 35 | + |
| 36 | + // In strict mode, additional keys on actual are a mismatch. In non-strict mode, they |
| 37 | + // are ignored (matching xUnit's `Assert.Equivalent` behaviour and the public docs). |
| 38 | + if (_strict) |
| 39 | + { |
| 40 | + failure = ForEachEntry(actual, isExpected: false, path, kvp => |
| 41 | + { |
| 42 | + string childPath = AppendDictionaryKey(path, kvp.Key); |
| 43 | + EquivalenceMismatch? lookup = SafeDictionaryOp( |
| 44 | + expected.ContainsKey, |
| 45 | + kvp.Key, |
| 46 | + isExpected: true, |
| 47 | + childPath, |
| 48 | + out bool exists); |
| 49 | + return lookup is not null |
| 50 | + ? lookup |
| 51 | + : exists |
| 52 | + ? null |
| 53 | + : EquivalenceMismatch.UnexpectedKey(childPath, kvp.Key); |
| 54 | + }); |
| 55 | + } |
| 56 | + |
| 57 | + return failure; |
| 58 | + } |
| 59 | + |
| 60 | + /// <summary> |
| 61 | + /// Iterates the entries of a <see cref="DictionaryView"/>, catching any user-supplied exceptions |
| 62 | + /// thrown by the underlying enumerator and surfacing them as a structured mismatch. |
| 63 | + /// </summary> |
| 64 | + private static EquivalenceMismatch? ForEachEntry(DictionaryView view, bool isExpected, string path, Func<KeyValuePair<object, object?>, EquivalenceMismatch?> onEntry) |
| 65 | + { |
| 66 | + IEnumerator<KeyValuePair<object, object?>>? enumerator; |
| 67 | + try |
| 68 | + { |
| 69 | + enumerator = view.Entries.GetEnumerator(); |
| 70 | + } |
| 71 | + catch (TargetInvocationException tie) |
| 72 | + { |
| 73 | + ThrowIfAssertException(tie.InnerException); |
| 74 | + return EquivalenceMismatch.DictionaryAccessFailure(path, isExpected, tie.InnerException ?? tie); |
| 75 | + } |
| 76 | + catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException and not UnitTestAssertException) |
| 77 | + { |
| 78 | + return EquivalenceMismatch.DictionaryAccessFailure(path, isExpected, ex); |
| 79 | + } |
| 80 | + |
| 81 | + using (enumerator) |
| 82 | + { |
| 83 | + while (true) |
| 84 | + { |
| 85 | + KeyValuePair<object, object?> kvp; |
| 86 | + try |
| 87 | + { |
| 88 | + if (!enumerator.MoveNext()) |
| 89 | + { |
| 90 | + return null; |
| 91 | + } |
| 92 | + |
| 93 | + kvp = enumerator.Current; |
| 94 | + } |
| 95 | + catch (TargetInvocationException tie) |
| 96 | + { |
| 97 | + ThrowIfAssertException(tie.InnerException); |
| 98 | + return EquivalenceMismatch.DictionaryAccessFailure(path, isExpected, tie.InnerException ?? tie); |
| 99 | + } |
| 100 | + catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException and not UnitTestAssertException) |
| 101 | + { |
| 102 | + return EquivalenceMismatch.DictionaryAccessFailure(path, isExpected, ex); |
| 103 | + } |
| 104 | + |
| 105 | + EquivalenceMismatch? nested = onEntry(kvp); |
| 106 | + if (nested is not null) |
| 107 | + { |
| 108 | + return nested; |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + /// <summary> |
| 115 | + /// Runs a single dictionary access operation that takes one argument, catching user-supplied |
| 116 | + /// exceptions and surfacing them as a structured mismatch. On success, the operation's return |
| 117 | + /// value is exposed via <paramref name="result"/>. |
| 118 | + /// </summary> |
| 119 | + private static EquivalenceMismatch? SafeDictionaryOp<TArg, TResult>(Func<TArg, TResult> op, TArg arg, bool isExpected, string path, out TResult result) |
| 120 | + { |
| 121 | + try |
| 122 | + { |
| 123 | + result = op(arg); |
| 124 | + return null; |
| 125 | + } |
| 126 | + catch (TargetInvocationException tie) |
| 127 | + { |
| 128 | + ThrowIfAssertException(tie.InnerException); |
| 129 | + result = default!; |
| 130 | + return EquivalenceMismatch.DictionaryAccessFailure(path, isExpected, tie.InnerException ?? tie); |
| 131 | + } |
| 132 | + catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException and not UnitTestAssertException) |
| 133 | + { |
| 134 | + result = default!; |
| 135 | + return EquivalenceMismatch.DictionaryAccessFailure(path, isExpected, ex); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private static bool TryCreateDictionaryView(object value, out DictionaryView? view) |
| 140 | + { |
| 141 | + // Non-generic IDictionary takes precedence over IDictionary<,> / IReadOnlyDictionary<,>: |
| 142 | + // most BCL dictionaries implement both and route both surfaces to the same backing store |
| 143 | + // (so the choice is observationally equivalent), while custom hybrid types are expected |
| 144 | + // to keep their non-generic surface consistent with the generic one. Picking the non- |
| 145 | + // generic path first avoids reflection-based dispatch where possible. |
| 146 | + if (value is IDictionary nonGeneric) |
| 147 | + { |
| 148 | + view = new NonGenericDictionaryView(nonGeneric); |
| 149 | + return true; |
| 150 | + } |
| 151 | + |
| 152 | + // Look for an IDictionary<TKey, TValue> implementation first; fall back to |
| 153 | + // IReadOnlyDictionary<TKey, TValue> if only the read-only surface is present. |
| 154 | + // When a type implements both (which is the case for most BCL dictionaries), the mutating |
| 155 | + // contract wins deterministically — that's the same precedence System.Collections.Generic.Dictionary |
| 156 | + // expresses, and it lets users override semantics by implementing IDictionary<,> explicitly. |
| 157 | + Type? dictInterface = null; |
| 158 | + Type? readOnlyDictInterface = null; |
| 159 | + foreach (Type i in value.GetType().GetInterfaces()) |
| 160 | + { |
| 161 | + if (!i.IsGenericType) |
| 162 | + { |
| 163 | + continue; |
| 164 | + } |
| 165 | + |
| 166 | + Type def = i.GetGenericTypeDefinition(); |
| 167 | + if (def == typeof(IDictionary<,>)) |
| 168 | + { |
| 169 | + dictInterface = i; |
| 170 | + break; |
| 171 | + } |
| 172 | + |
| 173 | + if (def == typeof(IReadOnlyDictionary<,>)) |
| 174 | + { |
| 175 | + readOnlyDictInterface = i; |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + Type? selected = dictInterface ?? readOnlyDictInterface; |
| 180 | + if (selected is not null) |
| 181 | + { |
| 182 | + view = GenericDictionaryView.Create(value, selected); |
| 183 | + return true; |
| 184 | + } |
| 185 | + |
| 186 | + view = null; |
| 187 | + return false; |
| 188 | + } |
| 189 | + } |
| 190 | +} |
0 commit comments