Skip to content

Commit 7d4e841

Browse files
CopilotEvangelink
andauthored
Refactor Assert.AreEquivalent comparer into focused partial-class files (#8775)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com>
1 parent a00e871 commit 7d4e841

5 files changed

Lines changed: 747 additions & 695 deletions
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
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+
}
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
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? CompareEnumerables(IEnumerable expected, IEnumerable actual, Type elementDeclaredType, string path, int depth)
14+
{
15+
EquivalenceMismatch? failure = TryGetEnumerator(expected, isExpected: true, path, out IEnumerator expectedEnumerator);
16+
if (failure is not null)
17+
{
18+
return failure;
19+
}
20+
21+
failure = TryGetEnumerator(actual, isExpected: false, path, out IEnumerator actualEnumerator);
22+
if (failure is not null)
23+
{
24+
DisposeEnumerator(expectedEnumerator);
25+
return failure;
26+
}
27+
28+
try
29+
{
30+
int index = 0;
31+
while (true)
32+
{
33+
failure = TryMoveNext(expectedEnumerator, isExpected: true, path, out bool expectedHasNext);
34+
if (failure is not null)
35+
{
36+
return failure;
37+
}
38+
39+
failure = TryMoveNext(actualEnumerator, isExpected: false, path, out bool actualHasNext);
40+
if (failure is not null)
41+
{
42+
return failure;
43+
}
44+
45+
if (!expectedHasNext || !actualHasNext)
46+
{
47+
if (expectedHasNext != actualHasNext)
48+
{
49+
failure = TryGetEnumerableCount(expectedEnumerator, expectedHasNext, isExpected: true, path, index, out int expectedCount);
50+
if (failure is not null)
51+
{
52+
return failure;
53+
}
54+
55+
failure = TryGetEnumerableCount(actualEnumerator, actualHasNext, isExpected: false, path, index, out int actualCount);
56+
return failure ?? EquivalenceMismatch.LengthMismatch(path, expectedCount, actualCount);
57+
}
58+
59+
return null;
60+
}
61+
62+
failure = TryGetCurrent(expectedEnumerator, isExpected: true, path, out object? expectedItem);
63+
if (failure is not null)
64+
{
65+
return failure;
66+
}
67+
68+
failure = TryGetCurrent(actualEnumerator, isExpected: false, path, out object? actualItem);
69+
if (failure is not null)
70+
{
71+
return failure;
72+
}
73+
74+
EquivalenceMismatch? nested = Compare(expectedItem, actualItem, elementDeclaredType, AppendIndex(path, index), depth + 1);
75+
if (nested is not null)
76+
{
77+
return nested;
78+
}
79+
80+
index++;
81+
}
82+
}
83+
finally
84+
{
85+
DisposeEnumerator(expectedEnumerator);
86+
DisposeEnumerator(actualEnumerator);
87+
}
88+
}
89+
90+
private static EquivalenceMismatch? TryGetEnumerator(IEnumerable source, bool isExpected, string path, out IEnumerator enumerator)
91+
{
92+
try
93+
{
94+
enumerator = source.GetEnumerator();
95+
return null;
96+
}
97+
catch (TargetInvocationException tie)
98+
{
99+
ThrowIfAssertException(tie.InnerException);
100+
enumerator = default!;
101+
return EquivalenceMismatch.EnumerationFailure(path, isExpected, tie.InnerException ?? tie);
102+
}
103+
catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException and not UnitTestAssertException)
104+
{
105+
enumerator = default!;
106+
return EquivalenceMismatch.EnumerationFailure(path, isExpected, ex);
107+
}
108+
}
109+
110+
private static EquivalenceMismatch? TryMoveNext(IEnumerator enumerator, bool isExpected, string path, out bool hasNext)
111+
{
112+
try
113+
{
114+
hasNext = enumerator.MoveNext();
115+
return null;
116+
}
117+
catch (TargetInvocationException tie)
118+
{
119+
ThrowIfAssertException(tie.InnerException);
120+
hasNext = false;
121+
return EquivalenceMismatch.EnumerationFailure(path, isExpected, tie.InnerException ?? tie);
122+
}
123+
catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException and not UnitTestAssertException)
124+
{
125+
hasNext = false;
126+
return EquivalenceMismatch.EnumerationFailure(path, isExpected, ex);
127+
}
128+
}
129+
130+
private static EquivalenceMismatch? TryGetCurrent(IEnumerator enumerator, bool isExpected, string path, out object? current)
131+
{
132+
try
133+
{
134+
current = enumerator.Current;
135+
return null;
136+
}
137+
catch (TargetInvocationException tie)
138+
{
139+
ThrowIfAssertException(tie.InnerException);
140+
current = default;
141+
return EquivalenceMismatch.EnumerationFailure(path, isExpected, tie.InnerException ?? tie);
142+
}
143+
catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException and not UnitTestAssertException)
144+
{
145+
current = default;
146+
return EquivalenceMismatch.EnumerationFailure(path, isExpected, ex);
147+
}
148+
}
149+
150+
private static EquivalenceMismatch? TryGetEnumerableCount(IEnumerator enumerator, bool hasCurrent, bool isExpected, string path, int matchedItemCount, out int count)
151+
{
152+
count = matchedItemCount;
153+
if (!hasCurrent)
154+
{
155+
return null;
156+
}
157+
158+
EquivalenceMismatch? failure = TryGetCurrent(enumerator, isExpected, path, out _);
159+
if (failure is not null)
160+
{
161+
count = 0;
162+
return failure;
163+
}
164+
165+
count++;
166+
while (true)
167+
{
168+
failure = TryMoveNext(enumerator, isExpected, path, out bool hasNext);
169+
if (failure is not null)
170+
{
171+
count = 0;
172+
return failure;
173+
}
174+
175+
if (!hasNext)
176+
{
177+
return null;
178+
}
179+
180+
failure = TryGetCurrent(enumerator, isExpected, path, out _);
181+
if (failure is not null)
182+
{
183+
count = 0;
184+
return failure;
185+
}
186+
187+
count++;
188+
}
189+
}
190+
191+
private static void DisposeEnumerator(IEnumerator enumerator)
192+
{
193+
if (enumerator is IDisposable disposable)
194+
{
195+
disposable.Dispose();
196+
}
197+
}
198+
}
199+
}

0 commit comments

Comments
 (0)