Skip to content

Commit 27c7271

Browse files
EvangelinkCopilot
andcommitted
Backport metadata-first fixture discovery to rel/4.5
Adapt #12269 (127798d) while retaining release target assets and package dependencies. Include the same binding/loading regressions and verified release red/green evidence. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent a39964c commit 27c7271

10 files changed

Lines changed: 1499 additions & 44 deletions

File tree

‎Directory.Packages.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@
102102
<PackageVersion Include="OpenTelemetry" Version="1.19.1" />
103103
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.19.1" />
104104
<PackageVersion Include="System.Memory" Version="$(SystemMemoryVersion)" />
105+
<PackageVersion Include="System.Reflection.Metadata" Version="8.0.0" />
105106
<PackageVersion Include="System.Text.Json" Version="10.0.12" />
106107
<PackageVersion Include="System.Threading.Tasks.Extensions" Version="$(SystemThreadingTasksExtensionsVersion)" />
107108
</ItemGroup>

‎docs/decisions/assembly-fixture-provider-discovery.md‎

Lines changed: 329 additions & 0 deletions
Large diffs are not rendered by default.

‎docs/glossary.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,11 @@ A shared static helper compiled into MTP extensions via file linking (no NuGet s
3737

3838
### AssemblyFixtureProviderAttribute
3939

40-
An MSTest assembly-level attribute (`[assembly: AssemblyFixtureProvider(typeof(T))]`) in `Microsoft.VisualStudio.TestTools.UnitTesting` that enables cross-assembly assembly fixtures. When applied to a library assembly, it causes any `[AssemblyInitialize]` and `[AssemblyCleanup]` methods on the specified `FixtureType` to be discovered and executed once per consuming test assembly that loads the library at runtime. This allows shared test infrastructure (e.g., database setup, container lifecycle) to be co-located in a test-helper library rather than repeated across every test project. Local `[AssemblyInitialize]`/`[AssemblyCleanup]` declarations always take precedence over provider-contributed ones; the attribute may be applied multiple times on the same assembly to expose multiple fixture types; and it can also be applied on the consuming test assembly to opt into fixtures from a third-party library. Introduced in [PR #8677](https://github.com/microsoft/testfx/pull/8677).
40+
An MSTest assembly-level attribute (`[assembly: AssemblyFixtureProvider(typeof(T))]`) in `Microsoft.VisualStudio.TestTools.UnitTesting` that enables cross-assembly assembly fixtures. Introduced in MSTest 4.3.0 by [PR #8677](https://github.com/microsoft/testfx/pull/8677), it exposes `[AssemblyInitialize]` and `[AssemblyCleanup]` methods on `FixtureType` once per consuming test assembly with a direct or transitive compiled reference to the marked library. The consumer need not execute a call into that library; an otherwise-unused project/package reference omitted by the compiler is insufficient. The attribute opts into **supplying** fixtures, not into **discovering** them.
41+
42+
Local hooks take precedence independently, and providers fill only missing slots. Both local hooks bypass provider discovery; one local hook does not. Multiple markers are supported, but multiple eligible methods for the same unfilled slot produce the existing duplicate-fixture diagnostic rather than a pipeline. The consumer can also apply the marker to expose fixtures from an unmodifiable library. Shared providers are unsupported when dynamic code is unavailable; the AOT guard and MSTEST0072 were added in 4.4.
43+
44+
The original discovery implementation, confirmed in 4.3.0 and 4.5.2, eagerly loads transitive unmarked references, changing `AppDomain.GetAssemblies()` and potentially locking DLLs on Windows/.NET Framework. The metadata-first correction on main avoids those loads for resolvable file-backed references, while retaining runtime-resolution fallback for opaque or ambiguous bindings. There is no dedicated discovery opt-out. Empty local hooks are a historical workaround, not required MSTest boilerplate. See [the discovery decision and validation record](decisions/assembly-fixture-provider-discovery.md) for the exact compatibility limits and servicing status; no released fixed version is implied.
4145

4246
### Assert.Scope (soft assertions)
4347

‎src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ $(CommonProductDescription)]]></PackageDescription>
9898
that reference is suppressed above, so they are referenced explicitly here. -->
9999
<PackageReference Include="System.Threading.Tasks.Extensions" Condition=" '$(TargetFramework)' == '$(NetFrameworkMinimum)' OR '$(TargetFramework)' == '$(UwpMinimum)' " />
100100
<PackageReference Include="System.Memory" Condition=" '$(TargetFramework)' == '$(NetFrameworkMinimum)' OR '$(TargetFramework)' == '$(UwpMinimum)' " />
101+
<PackageReference Include="System.Reflection.Metadata" Condition=" '$(TargetFramework)' == '$(NetFrameworkMinimum)' OR '$(TargetFramework)' == '$(UwpMinimum)' " />
101102

102103
<!-- The adapter's VSTest-facing code (VSTestAdapter\*, AdapterTestProperties) and the native Microsoft.Testing.Platform
103104
integration (TestingPlatformAdapter\MSTestFilterContext) use the VSTest object model directly. It used to flow
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+
using System.Reflection.Metadata;
5+
using System.Reflection.PortableExecutable;
6+
using System.Security;
7+
#if NET && !WINDOWS_UWP
8+
using System.Runtime.Loader;
9+
#endif
10+
11+
using Microsoft.VisualStudio.TestTools.UnitTesting;
12+
13+
namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution;
14+
15+
internal sealed partial class TypeCache
16+
{
17+
private static bool TryReadProviderMetadata(string path, out bool hasMarker, out AssemblyName[] references)
18+
{
19+
hasMarker = false;
20+
references = [];
21+
try
22+
{
23+
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
24+
using var peReader = new PEReader(stream, PEStreamOptions.PrefetchMetadata);
25+
MetadataReader reader = peReader.GetMetadataReader();
26+
AssemblyDefinition definition = reader.GetAssemblyDefinition();
27+
foreach (CustomAttributeHandle handle in definition.GetCustomAttributes())
28+
{
29+
EntityHandle constructor = reader.GetCustomAttribute(handle).Constructor;
30+
EntityHandle type = constructor.Kind switch
31+
{
32+
HandleKind.MemberReference => reader.GetMemberReference((MemberReferenceHandle)constructor).Parent,
33+
HandleKind.MethodDefinition => reader.GetMethodDefinition((MethodDefinitionHandle)constructor).GetDeclaringType(),
34+
_ => default,
35+
};
36+
if (type.Kind == HandleKind.TypeReference)
37+
{
38+
TypeReference attribute = reader.GetTypeReference((TypeReferenceHandle)type);
39+
hasMarker = reader.StringComparer.Equals(attribute.Name, nameof(AssemblyFixtureProviderAttribute))
40+
&& reader.StringComparer.Equals(attribute.Namespace, typeof(AssemblyFixtureProviderAttribute).Namespace!);
41+
}
42+
else if (type.Kind == HandleKind.TypeDefinition)
43+
{
44+
TypeDefinition attribute = reader.GetTypeDefinition((TypeDefinitionHandle)type);
45+
hasMarker = reader.StringComparer.Equals(attribute.Name, nameof(AssemblyFixtureProviderAttribute))
46+
&& reader.StringComparer.Equals(attribute.Namespace, typeof(AssemblyFixtureProviderAttribute).Namespace!);
47+
}
48+
49+
if (hasMarker)
50+
{
51+
break;
52+
}
53+
}
54+
55+
references = reader.AssemblyReferences.Select(handle => reader.GetAssemblyReference(handle).GetAssemblyName()).ToArray();
56+
return true;
57+
}
58+
catch (Exception ex) when (ex is IOException or BadImageFormatException or UnauthorizedAccessException or SecurityException)
59+
{
60+
if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsWarningEnabled)
61+
{
62+
PlatformServiceProvider.Instance.AdapterTraceLogger.Warning(
63+
"TypeCache: Could not read assembly metadata from {0}; using runtime resolution for AssemblyFixtureProvider discovery. {1}",
64+
path,
65+
ex);
66+
}
67+
68+
return false;
69+
}
70+
}
71+
72+
private sealed class ProviderDiscoveryMetadataResolver
73+
{
74+
#if NET && !WINDOWS_UWP
75+
private Dictionary<string, string?>? _trustedAssemblyPaths;
76+
#endif
77+
#if NETFRAMEWORK
78+
private bool? _hasCodeBaseOverrides;
79+
#endif
80+
81+
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "The resolver caches runtime-specific metadata paths on other target frameworks.")]
82+
public string? Resolve(Assembly referrer, AssemblyName referenceName)
83+
{
84+
try
85+
{
86+
#if NET && !WINDOWS_UWP
87+
AssemblyLoadContext context = AssemblyLoadContext.GetLoadContext(referrer) ?? AssemblyLoadContext.Default;
88+
// A component's deps/adjacent files do not describe Default's binding policy.
89+
// A later-loaded consumer may instead bind through Default.Resolving.
90+
if (context != AssemblyLoadContext.Default || context.Assemblies.Any(assembly =>
91+
string.Equals(assembly.GetName().Name, referenceName.Name, StringComparison.OrdinalIgnoreCase)))
92+
{
93+
return null;
94+
}
95+
96+
_trustedAssemblyPaths ??= ReadTrustedAssemblyPaths();
97+
return _trustedAssemblyPaths.TryGetValue(referenceName.Name!, out string? path)
98+
&& path is not null
99+
&& HasMatchingProviderDiscoveryIdentity(referenceName, path) ? path : null;
100+
#elif NETFRAMEWORK
101+
_ = referrer;
102+
AppDomain domain = AppDomain.CurrentDomain;
103+
AppDomainSetup setup = domain.SetupInformation;
104+
// Fusion can select a loaded image or the GAC before probing the application base.
105+
// Keep those bindings, culture probing, redirects and host overrides authoritative.
106+
if (domain.GetAssemblies().Any(assembly =>
107+
string.Equals(assembly.GetName().Name, referenceName.Name, StringComparison.OrdinalIgnoreCase))
108+
|| referenceName.GetPublicKeyToken() is { Length: > 0 }
109+
|| !string.IsNullOrEmpty(referenceName.CultureName)
110+
|| setup.DisallowApplicationBaseProbing
111+
|| setup.PrivateBinPathProbe is not null
112+
|| setup.GetConfigurationBytes() is { Length: > 0 }
113+
|| !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DEVPATH"))
114+
|| !string.Equals(domain.ApplyPolicy(referenceName.FullName), referenceName.FullName, StringComparison.Ordinal)
115+
|| (_hasCodeBaseOverrides ??= HasCodeBaseOverrides()))
116+
{
117+
return null;
118+
}
119+
120+
foreach (string extension in new[] { ".dll", ".exe" })
121+
{
122+
string path = Path.Combine(domain.BaseDirectory, referenceName.Name + extension);
123+
if (File.Exists(path))
124+
{
125+
return HasMatchingProviderDiscoveryIdentity(referenceName, path) ? path : null;
126+
}
127+
}
128+
#else
129+
_ = referrer;
130+
_ = referenceName;
131+
#endif
132+
}
133+
catch (Exception ex) when (ex is IOException or BadImageFormatException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or SecurityException or XmlException)
134+
{
135+
if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsWarningEnabled)
136+
{
137+
PlatformServiceProvider.Instance.AdapterTraceLogger.Warning(
138+
"TypeCache: Could not resolve a metadata path for {0}; using runtime resolution for AssemblyFixtureProvider discovery. {1}",
139+
referenceName.FullName,
140+
ex);
141+
}
142+
}
143+
144+
return null;
145+
}
146+
147+
#if NET && !WINDOWS_UWP
148+
private static Dictionary<string, string?> ReadTrustedAssemblyPaths()
149+
{
150+
Dictionary<string, string?> paths = [with(StringComparer.OrdinalIgnoreCase)];
151+
if (AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") is not string trustedPaths)
152+
{
153+
return paths;
154+
}
155+
156+
foreach (string path in trustedPaths.Split(Path.PathSeparator))
157+
{
158+
if (string.IsNullOrEmpty(path))
159+
{
160+
continue;
161+
}
162+
163+
string name = Path.GetFileNameWithoutExtension(path);
164+
paths[name] = paths.TryGetValue(name, out string? previous)
165+
&& !string.Equals(previous, path, StringComparison.Ordinal) ? null : path;
166+
}
167+
168+
return paths;
169+
}
170+
#endif
171+
172+
#if NETFRAMEWORK || (NET && !WINDOWS_UWP)
173+
private static bool HasMatchingProviderDiscoveryIdentity(AssemblyName referenceName, string path)
174+
=> string.Equals(referenceName.FullName, AssemblyName.GetAssemblyName(path).FullName, StringComparison.Ordinal);
175+
#endif
176+
177+
#if NETFRAMEWORK
178+
private static bool HasCodeBaseOverrides()
179+
{
180+
string configurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
181+
if (!File.Exists(configurationFile))
182+
{
183+
return false;
184+
}
185+
186+
using var reader = XmlReader.Create(configurationFile, new XmlReaderSettings { XmlResolver = null, DtdProcessing = DtdProcessing.Prohibit });
187+
while (reader.Read())
188+
{
189+
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "codeBase")
190+
{
191+
return true;
192+
}
193+
}
194+
195+
return false;
196+
}
197+
#endif
198+
}
199+
}

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.ProviderDiscovery.cs‎

Lines changed: 51 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -221,70 +221,80 @@ internal static void CollectFixtureMethodsFromProviderType(
221221

222222
private static IEnumerable<Assembly> EnumerateCandidateAssemblies(Assembly currentAssembly)
223223
{
224-
// BFS over the consumer assembly's reference graph. This bounds the work to assemblies that
225-
// are recorded in the metadata reference table (the runtime reference graph), instead of
226-
// scanning the entire AppDomain. Note that a bare project / PackageReference is NOT
227-
// sufficient: the C# compiler omits references that the compiled IL never uses, so a
228-
// provider library only shows up here if its types are actually touched by the consumer
229-
// (or a `[assembly: TypeForwardedTo]` / similar pulls the reference in). The acceptance
230-
// asset for this feature accordingly calls into the provider library to materialize the
231-
// reference.
232-
//
233-
// Dedup uses AssemblyName.FullName (name + version + culture + public-key-token) so multi-version
234-
// / multi-token references with the same simple name are not collapsed.
235224
var visited = new HashSet<string>(StringComparer.Ordinal);
236-
var queue = new Queue<Assembly>();
237-
225+
var queue = new Queue<ProviderDiscoveryNode>();
226+
var metadataResolver = new ProviderDiscoveryMetadataResolver();
238227
visited.Add(currentAssembly.FullName ?? string.Empty);
239228

240-
// The consumer assembly itself is yielded first so users may also place the marker on the
241-
// test project (handy escape hatch when the library author cannot ship the attribute themselves).
242-
queue.Enqueue(currentAssembly);
229+
// A consumer can register fixtures itself. For references, inspect PE metadata first:
230+
// loading an unmarked library just to read its references changes user-visible runtime state.
231+
yield return currentAssembly;
232+
queue.Enqueue(new(currentAssembly, GetProviderDiscoveryReferences(currentAssembly)));
243233

244234
while (queue.Count > 0)
245235
{
246-
Assembly current = queue.Dequeue();
247-
yield return current;
248-
249-
AssemblyName[] references;
250-
try
236+
ProviderDiscoveryNode node = queue.Dequeue();
237+
Assembly referrer = node.Referrer;
238+
foreach (AssemblyName referenceName in node.References)
251239
{
252-
references = current.GetReferencedAssemblies();
253-
}
254-
catch (Exception ex)
255-
{
256-
if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsWarningEnabled)
240+
string? name = referenceName.Name;
241+
if (name is null || IsFrameworkAssemblyName(name) || !visited.Add(referenceName.FullName))
257242
{
258-
PlatformServiceProvider.Instance.AdapterTraceLogger.Warning(
259-
"TypeCache: Exception occurred while enumerating referenced assemblies of {0} for AssemblyFixtureProvider discovery. {1}",
260-
SafeGetAssemblyName(current),
261-
ex);
243+
continue;
262244
}
263245

264-
continue;
265-
}
266-
267-
foreach (AssemblyName referenceName in references)
268-
{
269-
string? name = referenceName.Name;
270-
if (name is null || IsFrameworkAssemblyName(name))
246+
string? path = metadataResolver.Resolve(referrer, referenceName);
247+
if (path is not null && TryReadProviderMetadata(path, out bool hasMarker, out AssemblyName[] metadataReferences) && !hasMarker)
271248
{
249+
// Keep the nearest runtime referrer for eventual provider loading, but walk
250+
// unmarked intermediaries using only their metadata.
251+
queue.Enqueue(new(referrer, metadataReferences));
272252
continue;
273253
}
274254

275-
if (!visited.Add(referenceName.FullName))
255+
if (path is null && PlatformServiceProvider.Instance.AdapterTraceLogger.IsInfoEnabled)
276256
{
277-
continue;
257+
PlatformServiceProvider.Instance.AdapterTraceLogger.Info(
258+
"TypeCache: No metadata path for referenced assembly {0}; using runtime resolution for AssemblyFixtureProvider discovery.",
259+
referenceName.FullName);
278260
}
279261

280-
Assembly? referenced = TryLoadReferencedAssembly(current, referenceName);
262+
Assembly? referenced = TryLoadReferencedAssembly(referrer, referenceName);
281263
if (referenced is null || referenced.IsDynamic)
282264
{
283265
continue;
284266
}
285267

286-
queue.Enqueue(referenced);
268+
yield return referenced;
269+
queue.Enqueue(new(referenced, GetProviderDiscoveryReferences(referenced)));
270+
}
271+
}
272+
}
273+
274+
private readonly struct ProviderDiscoveryNode(Assembly referrer, AssemblyName[] references)
275+
{
276+
public Assembly Referrer { get; } = referrer;
277+
278+
public AssemblyName[] References { get; } = references;
279+
}
280+
281+
private static AssemblyName[] GetProviderDiscoveryReferences(Assembly assembly)
282+
{
283+
try
284+
{
285+
return assembly.GetReferencedAssemblies();
286+
}
287+
catch (Exception ex)
288+
{
289+
if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsWarningEnabled)
290+
{
291+
PlatformServiceProvider.Instance.AdapterTraceLogger.Warning(
292+
"TypeCache: Exception occurred while enumerating referenced assemblies of {0} for AssemblyFixtureProvider discovery. {1}",
293+
SafeGetAssemblyName(assembly),
294+
ex);
287295
}
296+
297+
return [];
288298
}
289299
}
290300

‎src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
</ItemGroup>
3939

4040
<ItemGroup>
41+
<PackageReference Include="System.Reflection.Metadata" Condition=" '$(TargetFramework)' == 'netstandard2.0' OR '$(TargetFramework)' == '$(NetFrameworkMinimum)' OR '$(TargetFramework)' == '$(UwpMinimum)' " />
4142
<PackageReference Include="System.Threading.Tasks.Extensions" Condition=" '$(TargetFramework)' == 'netstandard2.0' OR '$(TargetFramework)' == '$(NetFrameworkMinimum)' OR '$(TargetFramework)' == '$(UwpMinimum)' " />
4243
<!-- Span/MemoryMarshal used by the linked XxHash code below, and Span<T>.Fill used by
4344
Execution\TestDependencyGraph.*, live in System.Memory on these TFMs.

0 commit comments

Comments
 (0)