Skip to content

Commit 31e1cbf

Browse files
EvangelinkCopilot
andauthored
Cache MSTest MTP node properties (#10694)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 72a8ce4e-80d7-4909-9b4a-f9e4223af32d
1 parent 25010a3 commit 31e1cbf

3 files changed

Lines changed: 345 additions & 98 deletions

File tree

‎src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestTestNodeConverter.cs‎

Lines changed: 162 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -33,38 +33,20 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting;
3333
internal static class MSTestTestNodeConverter
3434
{
3535
/// <summary>
36-
/// Caches the parsed pieces of a <see cref="TestMethod"/>'s managed name.
36+
/// Caches the immutable base representation used to create every node for a test element.
3737
/// </summary>
3838
/// <remarks>
39-
/// The parse is a pure function of <see cref="TestMethod.ManagedTypeName"/> and
40-
/// <see cref="TestMethod.ManagedMethodName"/>, both immutable for the lifetime of the instance, and it scans the
41-
/// managed method signature and allocates the namespace/type substrings. The same <see cref="TestMethod"/> is
42-
/// converted several times per executed test (the in-progress node, then one result node per data row), so the
43-
/// parse is paid once per test method rather than once per node.
39+
/// A conversion still creates a distinct <see cref="TestNode"/> and <see cref="PropertyBag"/> for every message.
40+
/// Only immutable properties are shared. Properties that expose mutable arrays are materialized from private
41+
/// snapshots for each node. The weak key naturally bounds the cache to the lifetime of the element.
4442
/// <para>
45-
/// The resulting <see cref="TestMethodIdentifierProperty"/> is cached alongside the parse only for
46-
/// parameterless test methods. That type publicly exposes its
47-
/// <see cref="TestMethodIdentifierProperty.ParameterTypeFullNames"/> array, so sharing one instance is safe
48-
/// exactly when that array is empty and therefore cannot be mutated; every other field is an immutable string
49-
/// or int. A parameterized method must keep getting a fresh property carrying a fresh array copy, otherwise a
50-
/// consumer that writes to the array would corrupt every other node built from the same test method (see
51-
/// <see cref="ParsedManagedName.ToProperty"/>).
52-
/// </para>
53-
/// <para>
54-
/// The cache lives here rather than as a lazy property on <see cref="TestMethod"/> (the way
55-
/// <see cref="TestMethod.ManagedTypeName"/> caches itself) because <see cref="TestMethodIdentifierProperty"/>
56-
/// is a Microsoft.Testing.Platform type, and MSTestAdapter.PlatformServices - where <see cref="TestMethod"/>
57-
/// lives - does not reference the platform at all. Even within this assembly the platform is only reachable
58-
/// from this folder, through the file-level RS0030 suppression above (see this project's BannedSymbols.txt).
59-
/// </para>
60-
/// <para>
61-
/// The table holds only weak references to its keys, so entries disappear as soon as the
62-
/// <see cref="TestMethod"/> becomes unreachable. <c>GetValue</c> is thread-safe: concurrent misses may each run
63-
/// the factory, but a single value is published to every caller.
43+
/// Although <see cref="UnitTestElement"/> is mutable while discovery constructs it, the element is fully
44+
/// specialized before its first node is published. Data-row and source transformations create distinct element
45+
/// clones, so later lifecycle messages for one element observe the same base metadata captured here.
6446
/// </para>
6547
/// </remarks>
6648
#pragma warning disable IDE0028 // ConditionalWeakTable is not collection-expression-constructible on .NET Framework (CS9174).
67-
private static readonly ConditionalWeakTable<TestMethod, ParsedManagedName> ParsedManagedNameCache = new();
49+
private static readonly ConditionalWeakTable<UnitTestElement, BaseTestNodeData> BaseTestNodeDataCache = new();
6850
#pragma warning restore IDE0028
6951

7052
/// <summary>
@@ -103,7 +85,7 @@ public static TestNode ToEmptyResultTestNode(UnitTestElement element, bool isTrx
10385
/// </summary>
10486
public static TestNode ToResultTestNode(UnitTestElement element, FrameworkTestResult result, DateTimeOffset startTime, DateTimeOffset endTime, bool isTrxEnabled, MSTestSettings settings)
10587
{
106-
TestNode testNode = CreateBaseTestNode(element, isTrxEnabled, result.DisplayName, out TestMethodIdentifierProperty? testMethodIdentifier);
88+
TestNode testNode = CreateBaseTestNode(element, isTrxEnabled, result.DisplayName, out BaseTestNodeData baseData);
10789

10890
// Mirror TestResultExtensions.ToTestResult: the reported error message prefers the exception message and
10991
// falls back to the ignore reason; the stack trace comes straight from the framework result.
@@ -124,7 +106,7 @@ public static TestNode ToResultTestNode(UnitTestElement element, FrameworkTestRe
124106

125107
if (isTrxEnabled)
126108
{
127-
AddTrxResultProperties(testNode, element, errorMessage, errorStackTrace, testMethodIdentifier);
109+
AddTrxResultProperties(testNode, baseData, errorMessage, errorStackTrace);
128110
}
129111

130112
AddMessagesAndOutput(testNode, result, isTrxEnabled);
@@ -144,74 +126,181 @@ public static TestNode ToResultTestNode(UnitTestElement element, FrameworkTestRe
144126
return testNode;
145127
}
146128

147-
private static TestNode CreateBaseTestNode(UnitTestElement element, bool isTrxEnabled, string? displayNameOverride, out TestMethodIdentifierProperty? testMethodIdentifier)
129+
private static TestNode CreateBaseTestNode(UnitTestElement element, bool isTrxEnabled, string? displayNameOverride, out BaseTestNodeData baseData)
148130
{
149-
TestMethod testMethod = element.TestMethod;
131+
baseData = BaseTestNodeDataCache.GetValue(element, BaseTestNodeData.Create);
150132

151133
TestNode testNode = new()
152134
{
153-
Uid = new TestNodeUid(element.GetTestId().ToString()),
154-
155-
// TestMethod.DisplayName is always initialized (the constructor sets it to displayName ?? name), so
156-
// displayNameOverride is the only real fallback needed here.
157-
DisplayName = displayNameOverride ?? testMethod.DisplayName,
135+
Uid = baseData.Uid,
136+
DisplayName = displayNameOverride ?? baseData.DisplayName,
158137
};
159138

160-
AddCategoriesAndTraits(testNode, element, isTrxEnabled);
139+
baseData.AddProperties(testNode.Properties, isTrxEnabled);
140+
141+
return testNode;
142+
}
161143

162-
if (element.DeclaringFilePath is not null)
144+
private sealed class BaseTestNodeData
145+
{
146+
private readonly TestMetadataProperty[] _categoryMetadata;
147+
private readonly TestMetadataProperty[] _traitMetadata;
148+
private readonly string[]? _trxCategories;
149+
private readonly TestFileLocationProperty? _fileLocation;
150+
private readonly ParsedManagedName? _parsedManagedName;
151+
private readonly string _fullClassName;
152+
private readonly string _testMethodName;
153+
private TrxFullyQualifiedTypeNameProperty? _trxFullyQualifiedTypeNameProperty;
154+
private TrxTestDefinitionName? _trxTestDefinitionName;
155+
156+
private BaseTestNodeData(
157+
TestNodeUid uid,
158+
string displayName,
159+
TestMetadataProperty[] categoryMetadata,
160+
TestMetadataProperty[] traitMetadata,
161+
string[]? trxCategories,
162+
TestFileLocationProperty? fileLocation,
163+
ParsedManagedName? parsedManagedName,
164+
string fullClassName,
165+
string testMethodName)
163166
{
164-
var position = new LinePosition(element.DeclaringLineNumber ?? -1, -1);
165-
testNode.Properties.Add(new TestFileLocationProperty(element.DeclaringFilePath, new(position, position)));
167+
Uid = uid;
168+
DisplayName = displayName;
169+
_categoryMetadata = categoryMetadata;
170+
_traitMetadata = traitMetadata;
171+
_trxCategories = trxCategories;
172+
_fileLocation = fileLocation;
173+
_parsedManagedName = parsedManagedName;
174+
_fullClassName = fullClassName;
175+
_testMethodName = testMethodName;
166176
}
167177

168-
testMethodIdentifier = AddTestMethodIdentifier(testNode, testMethod);
178+
public TestNodeUid Uid { get; }
169179

170-
return testNode;
171-
}
180+
public string DisplayName { get; }
172181

173-
private static void AddCategoriesAndTraits(TestNode testNode, UnitTestElement element, bool isTrxEnabled)
174-
{
175-
if (element.TestCategory is { Length: > 0 } categories)
182+
public static BaseTestNodeData Create(UnitTestElement element)
176183
{
177-
if (isTrxEnabled)
184+
TestMethod testMethod = element.TestMethod;
185+
186+
string[]? categories = element.TestCategory is { Length: > 0 } testCategories
187+
? [.. testCategories]
188+
: null;
189+
TestMetadataProperty[] categoryMetadata;
190+
if (categories is null)
178191
{
179-
testNode.Properties.Add(new TrxCategoriesProperty(categories));
192+
categoryMetadata = [];
193+
}
194+
else
195+
{
196+
categoryMetadata = new TestMetadataProperty[categories.Length];
197+
for (int i = 0; i < categoryMetadata.Length; i++)
198+
{
199+
categoryMetadata[i] = new TestMetadataProperty(categories[i], string.Empty);
200+
}
180201
}
181202

182-
foreach (string category in categories)
203+
TestTrait[]? traits = element.Traits;
204+
TestMetadataProperty[] traitMetadata;
205+
if (traits is null)
206+
{
207+
traitMetadata = [];
208+
}
209+
else
183210
{
184-
testNode.Properties.Add(new TestMetadataProperty(category, string.Empty));
211+
traitMetadata = new TestMetadataProperty[traits.Length];
212+
for (int i = 0; i < traitMetadata.Length; i++)
213+
{
214+
traitMetadata[i] = new TestMetadataProperty(traits[i].Name, traits[i].Value);
215+
}
185216
}
217+
218+
TestFileLocationProperty? fileLocation = null;
219+
if (element.DeclaringFilePath is not null)
220+
{
221+
var position = new LinePosition(element.DeclaringLineNumber ?? -1, -1);
222+
fileLocation = new TestFileLocationProperty(element.DeclaringFilePath, new(position, position));
223+
}
224+
225+
ParsedManagedName? parsedManagedName = GetParsedManagedName(testMethod);
226+
return new BaseTestNodeData(
227+
new TestNodeUid(element.GetTestId().ToString()),
228+
testMethod.DisplayName,
229+
categoryMetadata,
230+
traitMetadata,
231+
categories,
232+
fileLocation,
233+
parsedManagedName,
234+
testMethod.FullClassName,
235+
testMethod.Name);
186236
}
187237

188-
if (element.Traits is { Length: > 0 } traits)
238+
public void AddProperties(PropertyBag properties, bool isTrxEnabled)
189239
{
190-
foreach (TestTrait trait in traits)
240+
if (isTrxEnabled && _trxCategories is not null)
241+
{
242+
properties.Add(new TrxCategoriesProperty([.. _trxCategories]));
243+
}
244+
245+
for (int i = 0; i < _categoryMetadata.Length; i++)
246+
{
247+
properties.Add(_categoryMetadata[i]);
248+
}
249+
250+
for (int i = 0; i < _traitMetadata.Length; i++)
191251
{
192-
testNode.Properties.Add(new TestMetadataProperty(trait.Name, trait.Value));
252+
properties.Add(_traitMetadata[i]);
253+
}
254+
255+
if (_fileLocation is not null)
256+
{
257+
properties.Add(_fileLocation);
258+
}
259+
260+
if (_parsedManagedName is not null)
261+
{
262+
properties.Add(_parsedManagedName.ToProperty());
193263
}
194264
}
195-
}
196265

197-
private static TestMethodIdentifierProperty? AddTestMethodIdentifier(TestNode testNode, TestMethod testMethod)
198-
{
199-
// NOTE: ManagedMethodName, in case of MSTest, carries the parameter types, so we prefer it to display the
200-
// parameter types in Test Explorer. This mirrors what the VSTest bridge did in AddAdditionalProperties.
201-
if (!testMethod.HasManagedMethodAndTypeProperties || StringEx.IsNullOrEmpty(testMethod.ManagedTypeName))
266+
public TrxTestDefinitionName GetTrxTestDefinitionName()
202267
{
203-
return null;
268+
if (_trxTestDefinitionName is { } cached)
269+
{
270+
return cached;
271+
}
272+
273+
var created = new TrxTestDefinitionName(DisplayName);
274+
return Interlocked.CompareExchange(ref _trxTestDefinitionName, created, null) ?? created;
204275
}
205276

206-
// The method group conversion is cached by the compiler, so the lookup does not allocate a delegate.
207-
TestMethodIdentifierProperty testMethodIdentifier = ParsedManagedNameCache.GetValue(testMethod, ParsedManagedName.Parse).ToProperty();
208-
testNode.Properties.Add(testMethodIdentifier);
209-
return testMethodIdentifier;
277+
public TrxFullyQualifiedTypeNameProperty GetTrxFullyQualifiedTypeNameProperty()
278+
{
279+
if (_trxFullyQualifiedTypeNameProperty is { } cached)
280+
{
281+
return cached;
282+
}
283+
284+
string fullyQualifiedTypeName = _parsedManagedName is not null
285+
? _parsedManagedName.FullyQualifiedTypeName
286+
: !StringEx.IsNullOrEmpty(_fullClassName)
287+
? _fullClassName
288+
: throw new InvalidOperationException($"The test method '{_testMethodName}' does not have a fully qualified class name.");
289+
290+
var created = new TrxFullyQualifiedTypeNameProperty(fullyQualifiedTypeName);
291+
return Interlocked.CompareExchange(ref _trxFullyQualifiedTypeNameProperty, created, null) ?? created;
292+
}
210293
}
211294

295+
// ManagedMethodName carries the parameter types, so prefer it to match the VSTest bridge's test identity.
296+
private static ParsedManagedName? GetParsedManagedName(TestMethod testMethod)
297+
=> !testMethod.HasManagedMethodAndTypeProperties || StringEx.IsNullOrEmpty(testMethod.ManagedTypeName)
298+
? null
299+
: ParsedManagedName.Parse(testMethod);
300+
212301
/// <summary>
213-
/// The parsed pieces of a <see cref="TestMethod"/>'s managed type and method names, cached by
214-
/// <see cref="ParsedManagedNameCache"/>.
302+
/// The parsed pieces of a <see cref="TestMethod"/>'s managed type and method names, retained by
303+
/// <see cref="BaseTestNodeData"/>.
215304
/// </summary>
216305
private sealed class ParsedManagedName
217306
{
@@ -263,8 +352,8 @@ public TestMethodIdentifierProperty ToProperty()
263352
{
264353
// A parameterless property is fully immutable - every field is a string or int, and the empty array
265354
// cannot be mutated - so the same instance is handed to every node. This is the common case, and the
266-
// ParsedManagedName is cached per TestMethod, so the several nodes one executed test produces (the
267-
// in-progress node, then one result node per data row and per in-process retry attempt) share it.
355+
// ParsedManagedName is retained by the element's base descriptor, so the several nodes one executed
356+
// test produces (the in-progress node, then one result node per data row and retry attempt) share it.
268357
if (_parameterlessProperty is not null)
269358
{
270359
return _parameterlessProperty;
@@ -276,6 +365,9 @@ public TestMethodIdentifierProperty ToProperty()
276365
return new TestMethodIdentifierProperty(
277366
assemblyFullName: string.Empty, _namespace, _typeName, _methodName, _arity, [.. _parameterTypeFullNames], returnTypeFullName: string.Empty);
278367
}
368+
369+
public string FullyQualifiedTypeName
370+
=> StringEx.IsNullOrEmpty(_namespace) ? _typeName : $"{_namespace}.{_typeName}";
279371
}
280372

281373
private static void AddOutcome(TestNode testNode, TestOutcome outcome, string? errorMessage, string? errorStackTrace)
@@ -306,35 +398,15 @@ private static void AddOutcome(TestNode testNode, TestOutcome outcome, string? e
306398
}
307399
}
308400

309-
private static void AddTrxResultProperties(TestNode testNode, UnitTestElement element, string? errorMessage, string? errorStackTrace, TestMethodIdentifierProperty? testMethodIdentifierProperty)
401+
private static void AddTrxResultProperties(TestNode testNode, BaseTestNodeData baseData, string? errorMessage, string? errorStackTrace)
310402
{
311403
if (!StringEx.IsNullOrEmpty(errorMessage) || !StringEx.IsNullOrEmpty(errorStackTrace))
312404
{
313405
testNode.Properties.Add(new TrxExceptionProperty(errorMessage, errorStackTrace));
314406
}
315407

316-
TestMethod testMethod = element.TestMethod;
317-
318-
// TestMethod.DisplayName is always initialized (constructor sets it to displayName ?? name).
319-
testNode.Properties.Add(new TrxTestDefinitionName(testMethod.DisplayName));
320-
321-
if (testMethodIdentifierProperty is not null)
322-
{
323-
testNode.Properties.Add(new TrxFullyQualifiedTypeNameProperty(
324-
StringEx.IsNullOrEmpty(testMethodIdentifierProperty.Namespace)
325-
? testMethodIdentifierProperty.TypeName
326-
: $"{testMethodIdentifierProperty.Namespace}.{testMethodIdentifierProperty.TypeName}"));
327-
}
328-
else if (!StringEx.IsNullOrEmpty(testMethod.FullClassName))
329-
{
330-
// FullClassName is the source of truth for the type name, so use it directly instead of re-parsing it out
331-
// of a "FullClassName.Name" string.
332-
testNode.Properties.Add(new TrxFullyQualifiedTypeNameProperty(testMethod.FullClassName));
333-
}
334-
else
335-
{
336-
throw new InvalidOperationException($"The test method '{testMethod.Name}' does not have a fully qualified class name.");
337-
}
408+
testNode.Properties.Add(baseData.GetTrxTestDefinitionName());
409+
testNode.Properties.Add(baseData.GetTrxFullyQualifiedTypeNameProperty());
338410
}
339411

340412
private static void AddMessagesAndOutput(TestNode testNode, FrameworkTestResult result, bool isTrxEnabled)

‎src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,9 @@ internal UnitTestElement Clone()
135135
{
136136
var clone = (UnitTestElement)MemberwiseClone();
137137
clone.TestMethod = TestMethod.Clone();
138+
// Discovery specializes clones into individual data rows after cloning. Clear the cached id so changes to
139+
// DataType/TestCaseIndex cannot reuse the parent test's identity when the parent was converted first.
140+
clone.CachedTestNodeUid = null;
138141
return clone;
139142
}
140143

0 commit comments

Comments
 (0)