From df6fc6ef3519f2160e0f9f9b0b06d6d462eaa6ef Mon Sep 17 00:00:00 2001 From: Agent Driver Date: Fri, 27 Nov 2026 14:50:14 -0500 Subject: [PATCH] Build xUnit and NUnit test containers through ModuleTestComposition ModuleTestCase and ModuleTestCommand now call ModuleTestComposition.BuildAsync and dispose the returned ModuleTestContainer. Their copies of the build steps are removed. Each runner keeps its TestCaseInfo registration and the list of modules from [ModuleTest] and the module attributes. Co-Authored-By: Claude Opus 5.5 --- .../Impl/ModuleTestCommand.cs | 213 ++--------------- .../Impl/ModuleTestCase.XunitMajor.cs | 4 +- .../Impl/ModuleTestCase.cs | 221 +++--------------- 3 files changed, 63 insertions(+), 375 deletions(-) diff --git a/src/DependencyModules.NUnit/Impl/ModuleTestCommand.cs b/src/DependencyModules.NUnit/Impl/ModuleTestCommand.cs index 6f5ded8..11a6114 100644 --- a/src/DependencyModules.NUnit/Impl/ModuleTestCommand.cs +++ b/src/DependencyModules.NUnit/Impl/ModuleTestCommand.cs @@ -1,6 +1,5 @@ using System.Reflection; using DependencyModules.NUnit.Attributes; -using DependencyModules.Runtime.Helpers; using DependencyModules.Runtime.Interfaces; using DependencyModules.Testing.Attributes.Interfaces; using DependencyModules.Testing.Impl; @@ -51,98 +50,36 @@ public override TestResult Execute(TestExecutionContext context) var serviceCollection = new ServiceCollection(); - // One resolver per container. A repeated test builds both again for every iteration. - var resolver = new TestParameterResolver(moduleContext); - SetupTestCaseInfo(serviceCollection, testMethod, knownAttributes); - // Before the modules, so anything driving the application can take one through ordinary - // constructor injection. It answers nothing until the container below exists to take pinned - // instances from, which is why it is handed its composition rather than given it here. - var containerSource = new TestContainerSource(); - - serviceCollection.AddSingleton(containerSource); - - SeedEnvironment(serviceCollection, method, knownAttributes); - - SetupModules(serviceCollection, method, knownAttributes); - - SetupServiceSetupAttributes(moduleContext, serviceCollection, knownAttributes); - - // Last, for the reason the xUnit host records at the same point: a [Mock] on a parameter - // beats a [TestExport] naming the same service. - resolver.SetupServiceCollection(serviceCollection); - - var serviceProvider = BuildServiceProvider( - moduleContext, - serviceCollection, - knownAttributes - ); - - // Every container the case built, the first and any the source was asked for, disposed - // together in the finally below. - var providers = new List { serviceProvider }; + // NUnit's command chain is synchronous. TestCommand.Execute has no async form. + var container = ModuleTestComposition + .BuildAsync( + services: serviceCollection, + modules: CollectModules(method, knownAttributes), + testMethod: moduleContext, + overrides: [], + currentTest: null, + parent: null + ) + .AsTask() + .GetAwaiter() + .GetResult(); try { - Start(moduleContext, knownAttributes, serviceProvider); - - // Named throughout: three of these are delegates of shapes that would happily bind to - // one another. - containerSource.Initialize( - services: serviceCollection, - pinned: serviceProvider, - pinnedServices: SharedRegistrations.Collect(method, knownAttributes), - namedServices: SharedRegistrations.CollectNamed(method, knownAttributes), - build: services => BuildServiceProvider(moduleContext, services, knownAttributes), - start: built => - { - Start(moduleContext, knownAttributes, built); - - return ValueTask.CompletedTask; - }, - track: providers.Add - ); - - var arguments = resolver - .ResolveArgumentsAsync(serviceProvider, RowArguments(testMethod)) + var arguments = container + .ResolveArgumentsAsync(RowArguments(testMethod)) .GetAwaiter() .GetResult(); - PublishArguments(testMethod, serviceProvider, arguments); + PublishArguments(testMethod, container.Services, arguments); return innerCommand.Execute(context); } finally { - // Backwards, so a container the source built goes before the one holding the instances - // it was handed. - for (var i = providers.Count - 1; i >= 0; i--) - { - DisposeProvider(providers[i]); - } - } - } - - /// - /// Runs the test's startup attributes against one container. - /// - /// - /// Every container, not only the first. A framework whose startup installs middleware or a filter - /// provider would otherwise answer through a chain that was never assembled. - /// - /// NUnit's command chain is synchronous - TestCommand.Execute has no async form - so an async - /// hook is awaited here rather than up the stack. - /// - private static void Start( - ITestMethodContext context, - Attribute[] knownAttributes, - IServiceProvider provider - ) - { - foreach (var startupAttribute in knownAttributes.OfType()) - { - startupAttribute.StartupAsync(context, provider).GetAwaiter().GetResult(); + container.DisposeAsync().AsTask().GetAwaiter().GetResult(); } } @@ -191,135 +128,35 @@ Attribute[] knownAttributes )); } - /// - /// Last rather than first: is widest scope first — assembly, - /// then declaring type, then the method — so the last one is the narrowest, and a builder on the - /// method beats one on the class beats one on the assembly. Taking the first would have let an - /// assembly-level builder silently win over the method that asked for a different container, - /// which is the reverse of how every other attribute here resolves. - /// - private static IServiceProvider BuildServiceProvider( - ITestMethodContext context, - IServiceCollection serviceCollection, - Attribute[] knownAttributes - ) - { - var serviceProviderBuilderAttribute = knownAttributes - .OfType() - .LastOrDefault(); - - if (serviceProviderBuilderAttribute != null) - { - return serviceProviderBuilderAttribute.BuildServiceProvider(context, serviceCollection); - } - - return serviceCollection.BuildServiceProvider(); - } - - /// - /// The whole pass runs after the parameter value providers, so a [TestExport] overrides a - /// [Mock] of the same service rather than the other way round. - /// - /// Mock support goes first within the pass, everything else keeping its declared order behind it. - /// A mock is the stand-in a test falls back to, so naming a real implementation has to beat it — - /// and has to beat it whether [MoqSupport] sits on the assembly, the class or the method, - /// which relying on attribute order alone would not guarantee. - /// - private static void SetupServiceSetupAttributes( - ITestMethodContext context, - IServiceCollection serviceCollection, - Attribute[] knownAttributes - ) - { - var setupAttributes = knownAttributes - .OfType() - .OrderBy(attribute => attribute is IMockSupportAttribute ? 0 : 1); - - foreach (var setupAttribute in setupAttributes) - { - setupAttribute.SetupServiceCollection(context, serviceCollection); - } - } - /// - /// Registers the environment the test's attributes declare, ahead of the modules - the same - /// seeding the xUnit integration does, for the reason recorded there: conditions are answered - /// from the environment already in the collection as each module is applied, and the - /// service-setup pass runs too late to supply it. + /// The modules in declaration order: those of [ModuleTest] first, then the module + /// attributes, widest scope first. reverses them. /// - private static void SeedEnvironment( - IServiceCollection serviceCollection, + private static IReadOnlyList CollectModules( MethodInfo method, Attribute[] knownAttributes ) - { - IModuleEnvironment? environment = null; - - foreach (var provider in knownAttributes.OfType()) - { - environment = provider.ProvideEnvironment(method) ?? environment; - } - - if (environment != null) - { - serviceCollection.Add(new ServiceDescriptor(typeof(IModuleEnvironment), environment)); - } - } - - /// - /// The same loading the xUnit integration does, reading so - /// neither names the other's attribute. It is not shared code because it needs both - /// DependencyModules.Runtime and DependencyModules.Testing, and the only assembly - /// both integrations share is Testing — which the three mocking packages reference precisely - /// because it does not drag the runtime in behind it. - /// - private static void SetupModules( - IServiceCollection serviceCollection, - MethodInfo method, - IEnumerable knownAttributes - ) { var modules = new List(); - foreach (var loadModuleAttribute in knownAttributes.OfType()) - { - modules.Add(loadModuleAttribute.GetModule()); - } - var testAttribute = method.GetTestAttribute(); if (testAttribute != null) { - var count = 0; foreach (var moduleType in testAttribute.ModuleTypes) { if (Activator.CreateInstance(moduleType, []) is IDependencyModule moduleInstance) { - modules.Insert(count++, moduleInstance); + modules.Add(moduleInstance); } } } - modules.Reverse(); - - DependencyRegistry.LoadModules(serviceCollection, modules.ToArray()); - } - - /// - /// Asynchronous disposal is preferred where the provider offers it, because a service that only - /// implements makes ServiceProvider.Dispose throw rather - /// than fall back. - /// - private static void DisposeProvider(IServiceProvider serviceProvider) - { - switch (serviceProvider) + foreach (var loadModuleAttribute in knownAttributes.OfType()) { - case IAsyncDisposable asyncDisposable: - asyncDisposable.DisposeAsync().AsTask().GetAwaiter().GetResult(); - break; - case IDisposable disposable: - disposable.Dispose(); - break; + modules.Add(loadModuleAttribute.GetModule()); } + + return modules; } } diff --git a/src/DependencyModules.xUnit/Impl/ModuleTestCase.XunitMajor.cs b/src/DependencyModules.xUnit/Impl/ModuleTestCase.XunitMajor.cs index f502ed2..a18e199 100644 --- a/src/DependencyModules.xUnit/Impl/ModuleTestCase.XunitMajor.cs +++ b/src/DependencyModules.xUnit/Impl/ModuleTestCase.XunitMajor.cs @@ -49,7 +49,7 @@ FixtureMappingManager methodFixtureMappings } finally { - await DisposeProviders(); + await DisposeContainers(); } } #else @@ -86,7 +86,7 @@ CancellationTokenSource cancellationTokenSource } finally { - await DisposeProviders(); + await DisposeContainers(); } } #endif diff --git a/src/DependencyModules.xUnit/Impl/ModuleTestCase.cs b/src/DependencyModules.xUnit/Impl/ModuleTestCase.cs index cf0fd70..ad65257 100644 --- a/src/DependencyModules.xUnit/Impl/ModuleTestCase.cs +++ b/src/DependencyModules.xUnit/Impl/ModuleTestCase.cs @@ -1,5 +1,3 @@ -using System.Reflection; -using DependencyModules.Runtime.Helpers; using DependencyModules.Runtime.Interfaces; using DependencyModules.Testing.Attributes.Interfaces; using DependencyModules.Testing.Impl; @@ -28,7 +26,7 @@ public partial class ModuleTestCase : XunitTestCase, ISelfExecutingXunitTestCase /// One per container this case built: one for a plain test, one per row for a data-driven /// one. Runtime state only, never serialized with the case. /// - private readonly List _providers = []; + private readonly List _containers = []; // Here as well as on ModuleTestAttribute, because an attribute of another library can name // ModuleTestDiscoverer, and then this is the first of the package's types that xUnit creates. @@ -90,9 +88,10 @@ public ModuleTestCase( /// public override void PreInvoke() { } - private record StartupValues(IServiceProvider ServiceProvider, TestParameterResolver Resolver); - - private async Task SetupServiceCollection() + /// + /// Builds one container for this case. A data-driven test builds one for every row. + /// + private async Task BuildContainerAsync() { var serviceCollection = new ServiceCollection(); @@ -100,72 +99,22 @@ private async Task SetupServiceCollection() var context = new XunitTestMethodContext(TestMethod, knownAttributes); - // One resolver per container. A data-driven test builds both again for every row. - var resolver = new TestParameterResolver(context); - SetupTestCaseInfo(serviceCollection, knownAttributes); - // Before the modules, so anything driving the application can take one through ordinary - // constructor injection. It answers nothing until the container below exists to take pinned - // instances from, which is why it is handed its composition rather than given it here. - var containerSource = new TestContainerSource(); - - serviceCollection.AddSingleton(containerSource); - - SeedEnvironment(serviceCollection, knownAttributes); - - SetupModules(serviceCollection, knownAttributes); - - SetupServiceSetupAttributes(context, serviceCollection, knownAttributes); - - // Last, so a [Mock] on a parameter beats a [TestExport] naming the same service. A - // parameter attribute is the narrowest thing a test can say and the only one that names a - // single argument, so it decides for that argument - the class or assembly sets the default - // and this is the one test opting out of it. A [Mock] stands aside where the mock library - // registers the type itself, which is what keeps [Mock] IFoo and Mock one pair. - resolver.SetupServiceCollection(serviceCollection); - - var provider = BuildServiceProvider(context, serviceCollection, knownAttributes); + var container = await ModuleTestComposition.BuildAsync( + services: serviceCollection, + modules: CollectModules(knownAttributes), + testMethod: context, + overrides: [], + currentTest: null, + parent: null + ); // Kept here rather than handed to DisposalTracker, which xUnit empties at the end of the // run; see the remarks on the class. - _providers.Add(provider); + _containers.Add(container); - await StartAsync(context, knownAttributes, provider); - - // Named throughout, for the reason the base constructor above gives: three of these are - // delegates of shapes that would happily bind to one another. - containerSource.Initialize( - services: serviceCollection, - pinned: provider, - pinnedServices: SharedRegistrations.Collect(TestMethod.Method, knownAttributes), - namedServices: SharedRegistrations.CollectNamed(TestMethod.Method, knownAttributes), - build: services => BuildServiceProvider(context, services, knownAttributes), - start: built => StartAsync(context, knownAttributes, built), - track: _providers.Add - ); - - return new StartupValues(provider, resolver); - } - - /// - /// Runs the test's startup attributes against one container. - /// - /// - /// Every container, not only the first. A framework whose startup installs middleware or a filter - /// provider would otherwise answer through a chain that was never assembled, which is a container - /// that looks composed and is not. - /// - private static async ValueTask StartAsync( - ITestMethodContext context, - Attribute[] knownAttributes, - IServiceProvider provider - ) - { - foreach (var startupAttribute in knownAttributes.OfType()) - { - await startupAttribute.StartupAsync(context, provider); - } + return container; } private void SetupTestCaseInfo(ServiceCollection serviceCollection, Attribute[] knownAttributes) @@ -180,139 +129,45 @@ private void SetupTestCaseInfo(ServiceCollection serviceCollection, Attribute[] )); } - /// - /// Last rather than first: is widest scope first — assembly, - /// then declaring type, then the method — so the last one is the narrowest, and a builder on the - /// method beats one on the class beats one on the assembly. Taking the first would have let an - /// assembly-level builder silently win over the method that asked for a different container, - /// which is the reverse of how every other attribute here resolves. - /// - private IServiceProvider BuildServiceProvider( - ITestMethodContext context, - IServiceCollection serviceCollection, - Attribute[] knownAttributes - ) - { - var serviceProviderBuilderAttribute = knownAttributes - .OfType() - .LastOrDefault(); - - if (serviceProviderBuilderAttribute != null) - { - return serviceProviderBuilderAttribute.BuildServiceProvider(context, serviceCollection); - } - - return serviceCollection.BuildServiceProvider(); - } - - /// - /// The whole pass runs before the parameter value providers, so a [Mock] on a - /// parameter overrides a [TestExport] naming the same service. These attributes apply to - /// a method, a class or an assembly; a parameter attribute names one argument, and that is the - /// narrowest thing a test can say, so it is the one that decides. - /// - /// Mock support goes first within the pass, everything else keeping its declared order behind it. - /// A mock is the stand-in a test falls back to, so naming a real implementation has to beat it — - /// and has to beat it whether [MoqSupport] sits on the assembly, the class or the method, - /// which relying on attribute order alone would not guarantee. A Mock<T> parameter - /// goes through this pass rather than the parameter one, so it does not override a - /// [TestExport]: asking for the mock object is not the same as declaring the service - /// mocked, which is what [Mock] is for. - /// - private void SetupServiceSetupAttributes( - ITestMethodContext context, - IServiceCollection serviceCollection, - Attribute[] knownAttributes - ) - { - var setupAttributes = knownAttributes - .OfType() - .OrderBy(attribute => attribute is IMockSupportAttribute ? 0 : 1); - - foreach (var setupAttribute in setupAttributes) - { - setupAttribute.SetupServiceCollection(context, serviceCollection); - } - } - /// - /// Registers the environment the test's attributes declare, ahead of the modules. + /// The modules in declaration order: those of [ModuleTest] first, then the module + /// attributes, widest scope first. reverses them. /// - /// - /// Before , because module registrations are conditioned as they are - /// applied: LoadModules answers [IfEnvironment] from the - /// already in the collection, or a process default when there - /// is none. The service-setup pass runs after the modules by design - a test registration - /// beats an application one - so an environment registered there arrived after every condition - /// had been decided against the default. Widest scope first, so the narrowest attribute that - /// answers decides, matching how every other attribute here resolves. - /// - private void SeedEnvironment(IServiceCollection serviceCollection, Attribute[] knownAttributes) - { - IModuleEnvironment? environment = null; - - foreach (var provider in knownAttributes.OfType()) - { - environment = provider.ProvideEnvironment(TestMethod.Method) ?? environment; - } - - if (environment != null) - { - serviceCollection.Add(new ServiceDescriptor(typeof(IModuleEnvironment), environment)); - } - } - - private void SetupModules( - ServiceCollection serviceCollection, - IEnumerable knownAttributes - ) + private IReadOnlyList CollectModules(Attribute[] knownAttributes) { var modules = new List(); - foreach (var loadModuleAttribute in knownAttributes.OfType()) - { - var moduleTypes = loadModuleAttribute.GetModule(); - - modules.Add(moduleTypes); - } - // The interface rather than ModuleTestAttribute, so this reads the same for any integration. var testAttribute = TestMethod.Method.GetTestAttribute(); if (testAttribute != null) { - var count = 0; foreach (var moduleType in testAttribute.ModuleTypes) { if (Activator.CreateInstance(moduleType, []) is IDependencyModule moduleInstance) { - modules.Insert(count++, moduleInstance); + modules.Add(moduleInstance); } } } - modules.Reverse(); + foreach (var loadModuleAttribute in knownAttributes.OfType()) + { + modules.Add(loadModuleAttribute.GetModule()); + } - DependencyRegistry.LoadModules(serviceCollection, modules.ToArray()); + return modules; } - private async ValueTask DisposeProviders() + private async ValueTask DisposeContainers() { - var providers = _providers.ToArray(); + var containers = _containers.ToArray(); - _providers.Clear(); + _containers.Clear(); - foreach (var provider in providers) + foreach (var container in containers) { - switch (provider) - { - case IAsyncDisposable asyncDisposable: - await asyncDisposable.DisposeAsync(); - break; - case IDisposable disposable: - disposable.Dispose(); - break; - } + await container.DisposeAsync(); } } @@ -383,7 +238,7 @@ IDataAttribute[] dataAttributes { var data = theoryDataRow.GetData(); - var startupValues = await SetupServiceCollection(); + var container = await BuildContainerAsync(); unitTests.Add( CreateTest( @@ -403,7 +258,7 @@ IDataAttribute[] dataAttributes .GetTraits(TestMethod, theoryDataRow) .ToReadOnlyTraits(), timeout: theoryDataRow.Timeout ?? Timeout, - testMethodArguments: await ResolveArguments(data, startupValues), + testMethodArguments: await ResolveArguments(data, container), row: theoryDataRow, dataAttribute: dataAttribute ) @@ -472,7 +327,7 @@ private string GetRowDisplayName(Xunit.ITheoryDataRow theoryDataRow, object?[] d private async Task> UnitTestWithNoDataAttributes() { - var startupValues = await SetupServiceCollection(); + var container = await BuildContainerAsync(); return [ @@ -485,7 +340,7 @@ private async Task> UnitTestWithNoDataAttributes testIndex: 0, traits: Traits.ToReadOnlyTraits(), timeout: Timeout, - testMethodArguments: await ResolveArguments([], startupValues), + testMethodArguments: await ResolveArguments([], container), row: null, dataAttribute: null ), @@ -498,16 +353,12 @@ private async Task> UnitTestWithNoDataAttributes /// private static async Task ResolveArguments( object?[] data, - StartupValues startupValues + ModuleTestContainer container ) { - var arguments = await startupValues.Resolver.ResolveArgumentsAsync( - startupValues.ServiceProvider, - data - ); + var arguments = await container.ResolveArgumentsAsync(data); - startupValues.ServiceProvider.GetRequiredService().TestMethodArguments = - arguments; + container.Services.GetRequiredService().TestMethodArguments = arguments; return arguments; }