From 588614adb6f81fedb72be2b04546295fa7ddf99c Mon Sep 17 00:00:00 2001 From: Agent Driver Date: Fri, 27 Nov 2026 14:25:21 -0500 Subject: [PATCH] Add ModuleTestComposition to DependencyModules.Testing ModuleTestComposition.BuildAsync builds a test's container in the steps that ModuleTestCase and ModuleTestCommand take, plus a current-test registration, the services shared from a parent, and overrides registered after the setup attributes. BuildScopeAsync builds the parent of a class or an assembly. DependencyModules.Testing now references DependencyModules.Runtime and Microsoft.Extensions.DependencyInjection. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + .../Interfaces/IModuleEnvironmentProvider.cs | 7 +- .../Attributes/TestExportAttribute.cs | 4 +- .../DependencyModules.Testing.csproj | 16 +- .../Impl/ModuleTestComposition.cs | 278 +++++ .../Impl/ModuleTestContainer.cs | 252 ++++ .../Impl/TestMethodContext.cs | 23 + .../Impl/TestParameterResolver.cs | 119 +- .../Impl/TestServiceOverride.cs | 16 + .../PublicApiTests.TestingApi.verified.txt | 27 + .../ModuleTestCompositionTests.cs | 1055 +++++++++++++++++ 11 files changed, 1780 insertions(+), 26 deletions(-) create mode 100644 src/DependencyModules.Testing/Impl/ModuleTestComposition.cs create mode 100644 src/DependencyModules.Testing/Impl/ModuleTestContainer.cs create mode 100644 src/DependencyModules.Testing/Impl/TestMethodContext.cs create mode 100644 src/DependencyModules.Testing/Impl/TestServiceOverride.cs create mode 100644 tests/DependencyModules.Specs/TestingTests/ModuleTestCompositionTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index c26d4ca..f6cff56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 (#132) - `GlueSourceGenerator` in the `DependencyModules.SourceGenerator.Impl` package, for the source generator of a framework. (#132) +- `ModuleTestComposition` in DependencyModules.Testing. `BuildAsync` builds the service provider + of a test from modules, test attributes, and `TestServiceOverride` instances, in the same steps + as DependencyModules.xUnit and DependencyModules.NUnit. An override replaces a `[TestExport]` for + the same service. `BuildScopeAsync` builds a shared parent for a class or an assembly. + `ModuleTestContainer` holds the result and disposes each service provider that it built. + `TestMethodContext` is a plain `ITestMethodContext`. ### Changed @@ -39,6 +45,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `IDependencyModule` has the new member `InternalApplyGlue`, with a default implementation. The load of the modules has a last step that adds the collections and the `Func` registrations. (#132) +- `DependencyModules.Testing` depends on `DependencyModules.Runtime` and on + `Microsoft.Extensions.DependencyInjection`: version 8.0.1 for `net8.0` and version 10.0.0 for + `net10.0`. Before, it depended on `Microsoft.Extensions.DependencyInjection.Abstractions` only. ## [1.7.0] - 2026-09-25 diff --git a/src/DependencyModules.Runtime/Interfaces/IModuleEnvironmentProvider.cs b/src/DependencyModules.Runtime/Interfaces/IModuleEnvironmentProvider.cs index f5b79ca..1ff377c 100644 --- a/src/DependencyModules.Runtime/Interfaces/IModuleEnvironmentProvider.cs +++ b/src/DependencyModules.Runtime/Interfaces/IModuleEnvironmentProvider.cs @@ -17,10 +17,9 @@ namespace DependencyModules.Runtime.Interfaces; /// integrations consult this before loading any module, which is the whole difference. /// /// -/// Beside rather than in the Testing package, for the -/// same reason the module loading it feeds lives in each integration: it returns a Runtime -/// type, and Testing deliberately does not reference Runtime. The parameter is a -/// rather than a test-method context for the same reason. +/// The parameter is a rather than a test-method context, because +/// this interface is in Runtime and the test-method context is in the Testing package, which +/// references Runtime. /// /// /// Attributes are consulted widest scope first - assembly, then class, then method - and the diff --git a/src/DependencyModules.Testing/Attributes/TestExportAttribute.cs b/src/DependencyModules.Testing/Attributes/TestExportAttribute.cs index 4122e53..2366659 100644 --- a/src/DependencyModules.Testing/Attributes/TestExportAttribute.cs +++ b/src/DependencyModules.Testing/Attributes/TestExportAttribute.cs @@ -125,7 +125,9 @@ public TestExportAttribute(Type service) public void SetupServiceCollection( ITestMethodContext testMethod, IServiceCollection serviceCollection - ) + ) => Register(serviceCollection); + + internal void Register(IServiceCollection serviceCollection) { var implementation = Implementation ?? Service; diff --git a/src/DependencyModules.Testing/DependencyModules.Testing.csproj b/src/DependencyModules.Testing/DependencyModules.Testing.csproj index 049b4d6..a0157aa 100644 --- a/src/DependencyModules.Testing/DependencyModules.Testing.csproj +++ b/src/DependencyModules.Testing/DependencyModules.Testing.csproj @@ -6,19 +6,27 @@ enable True DependencyModules.Testing - The test attributes and interfaces of DependencyModules: [Mock], [InjectValues], [Shared], [TestExport], and the interfaces for mock libraries and test attributes. It also contains the helpers that find the attributes of a test on the method, the class, and the assembly. CurrentTest gives the test that runs. TestOutputLoggerProvider writes log entries to the output of the test that runs. It does not depend on a test framework. The DependencyModules.xUnit, DependencyModules.xUnit4, and DependencyModules.NUnit packages use this package. Add one of those packages to a test project. + The test attributes and interfaces of DependencyModules: [Mock], [InjectValues], [Shared], [TestExport], and the interfaces for mock libraries and test attributes. It also contains the helpers that find the attributes of a test on the method, the class, and the assembly. CurrentTest gives the test that runs. TestOutputLoggerProvider writes log entries to the output of the test that runs. ModuleTestComposition builds the service provider of a test from modules and test attributes, for each test runner. It does not depend on a test framework. The DependencyModules.xUnit, DependencyModules.xUnit4, and DependencyModules.NUnit packages use this package. Add one of those packages to a test project. true - + - + - + + + + + diff --git a/src/DependencyModules.Testing/Impl/ModuleTestComposition.cs b/src/DependencyModules.Testing/Impl/ModuleTestComposition.cs new file mode 100644 index 0000000..09e88bb --- /dev/null +++ b/src/DependencyModules.Testing/Impl/ModuleTestComposition.cs @@ -0,0 +1,278 @@ +using System.Reflection; +using DependencyModules.Runtime.Helpers; +using DependencyModules.Runtime.Interfaces; +using DependencyModules.Testing.Attributes; +using DependencyModules.Testing.Attributes.Interfaces; +using Microsoft.Extensions.DependencyInjection; + +namespace DependencyModules.Testing.Impl; + +/// +/// Builds a test's container from modules and testing attributes, the same way for every runner. +/// +public static class ModuleTestComposition +{ + /// + /// Builds the container of one test. + /// + /// + /// The steps, in order: + /// + /// Register an . + /// Register when it is not null. + /// Register the environment from the narrowest that answers. + /// Load , reversed. + /// Run the s, the s first. + /// When is set, register the parent's instances of the shared services. + /// Run for each parameter that no override names. + /// Register as instances. + /// Build with the narrowest , or BuildServiceProvider(). + /// Run the s. + /// Initialize the . + /// + /// + /// When a step throws, every container built so far is disposed and the exception is rethrown. + /// + /// + /// + /// The collection to build into. A runner registers its own services in it first. + /// + /// + /// The modules in declaration order: the runner's own modules first, then the module attributes, + /// widest scope first. + /// + /// The test method and its attribute instances, widest scope first. + /// The instances that replace services, such as mocks. + /// + /// Registered as the container's when it is not null. + /// is not changed. + /// + /// + /// A class or assembly container from , or null. + /// + /// + /// The instance of an override is not assignable to its service type. + /// + public static async ValueTask BuildAsync( + IServiceCollection services, + IReadOnlyList modules, + ITestMethodContext testMethod, + IReadOnlyList overrides, + ICurrentTestProvider? currentTest, + ModuleTestContainer? parent + ) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(modules); + ArgumentNullException.ThrowIfNull(testMethod); + ArgumentNullException.ThrowIfNull(overrides); + + foreach (var entry in overrides) + { + if (!entry.ServiceType.IsInstanceOfType(entry.Instance)) + { + throw new ArgumentException( + $"The override for {entry.ServiceType} is a {entry.Instance.GetType()}, which is " + + $"not a {entry.ServiceType}.", + nameof(overrides) + ); + } + } + + var attributes = testMethod.Attributes; + var resolver = new TestParameterResolver( + testMethod, + parameter => IsOverridden(parameter, overrides) + ); + var container = new ModuleTestContainer(resolver, attributes); + + try + { + var containerSource = new TestContainerSource(); + + services.AddSingleton(containerSource); + + if (currentTest != null) + { + services.AddSingleton(currentTest); + } + + SeedEnvironment(services, testMethod.Method, attributes); + + LoadModules(services, modules); + + SetupServiceSetupAttributes(testMethod, services, attributes); + + parent?.RegisterSharedServices(services, testMethod); + + resolver.SetupServiceCollection(services); + + foreach (var entry in overrides) + { + services.Add( + entry.ServiceKey == null + ? new ServiceDescriptor(entry.ServiceType, entry.Instance) + : new ServiceDescriptor(entry.ServiceType, entry.ServiceKey, entry.Instance) + ); + } + + var provider = BuildServiceProvider(testMethod, services, attributes); + + container.SetServices(provider); + + await StartAsync(testMethod, attributes, provider); + + containerSource.Initialize( + services: services, + pinned: provider, + pinnedServices: SharedRegistrations.Collect(testMethod.Method, attributes), + namedServices: SharedRegistrations.CollectNamed(testMethod.Method, attributes), + build: built => BuildServiceProvider(testMethod, built, attributes), + start: built => StartAsync(testMethod, attributes, built), + track: container.Track + ); + + return container; + } + catch + { + try + { + await container.DisposeAsync(); + } + catch + { + // The exception of the step that failed says more than one from the disposal. + } + + throw; + } + } + + /// + /// Builds the shared container of a class or an assembly, which takes + /// as its parent. + /// + /// + /// It loads , reversed, with the default environment. It registers + /// each [TestExport(Shared = true)] in and builds with + /// BuildServiceProvider(). It runs nothing that needs a test method. + /// + /// The collection to build into. + /// The modules in declaration order, as for . + /// The attribute instances of the class or the assembly, widest scope first. + public static ValueTask BuildScopeAsync( + IServiceCollection services, + IReadOnlyList modules, + IReadOnlyList scopeAttributes + ) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(modules); + ArgumentNullException.ThrowIfNull(scopeAttributes); + + LoadModules(services, modules); + + foreach (var export in scopeAttributes.OfType()) + { + if (export.Shared) + { + export.Register(services); + } + } + + var container = new ModuleTestContainer(null, scopeAttributes); + + container.SetServices(services.BuildServiceProvider()); + + return new ValueTask(container); + } + + private static bool IsOverridden( + ParameterInfo parameter, + IReadOnlyList overrides + ) + { + var key = parameter.GetCustomAttribute()?.Key; + + return overrides.Any(entry => + entry.ServiceType == parameter.ParameterType && Equals(entry.ServiceKey, key) + ); + } + + /// + /// Before the modules, because LoadModules decides [IfEnvironment] from the + /// already in the collection. + /// + private static void SeedEnvironment( + IServiceCollection services, + MethodInfo method, + IReadOnlyList attributes + ) + { + IModuleEnvironment? environment = null; + + foreach (var provider in attributes.OfType()) + { + environment = provider.ProvideEnvironment(method) ?? environment; + } + + if (environment != null) + { + services.Add(new ServiceDescriptor(typeof(IModuleEnvironment), environment)); + } + } + + private static void LoadModules( + IServiceCollection services, + IReadOnlyList modules + ) + { + var reversed = modules.ToArray(); + + Array.Reverse(reversed); + + DependencyRegistry.LoadModules(services, reversed); + } + + private static void SetupServiceSetupAttributes( + ITestMethodContext testMethod, + IServiceCollection services, + IReadOnlyList attributes + ) + { + var setupAttributes = attributes + .OfType() + .OrderBy(attribute => attribute is IMockSupportAttribute ? 0 : 1); + + foreach (var setupAttribute in setupAttributes) + { + setupAttribute.SetupServiceCollection(testMethod, services); + } + } + + private static IServiceProvider BuildServiceProvider( + ITestMethodContext testMethod, + IServiceCollection services, + IReadOnlyList attributes + ) + { + var builder = attributes.OfType().LastOrDefault(); + + return builder != null + ? builder.BuildServiceProvider(testMethod, services) + : services.BuildServiceProvider(); + } + + private static async ValueTask StartAsync( + ITestMethodContext testMethod, + IReadOnlyList attributes, + IServiceProvider provider + ) + { + foreach (var startupAttribute in attributes.OfType()) + { + await startupAttribute.StartupAsync(testMethod, provider); + } + } +} diff --git a/src/DependencyModules.Testing/Impl/ModuleTestContainer.cs b/src/DependencyModules.Testing/Impl/ModuleTestContainer.cs new file mode 100644 index 0000000..057658c --- /dev/null +++ b/src/DependencyModules.Testing/Impl/ModuleTestContainer.cs @@ -0,0 +1,252 @@ +using System.Reflection; +using System.Runtime.ExceptionServices; +using DependencyModules.Testing.Attributes; +using DependencyModules.Testing.Attributes.Interfaces; +using Microsoft.Extensions.DependencyInjection; + +namespace DependencyModules.Testing.Impl; + +/// +/// A built test container, and every container its built. +/// +/// +/// and +/// create it. disposes every container it tracks, the last one built +/// first. +/// +public sealed class ModuleTestContainer : IAsyncDisposable +{ + private readonly object _gate = new(); + private readonly List _providers = []; + private readonly Dictionary<(Type, object?), object?> _sharedInstances = new(); + private readonly TestParameterResolver? _resolver; + private readonly IReadOnlyList _scopeAttributes; + private IServiceProvider? _services; + + internal ModuleTestContainer( + TestParameterResolver? resolver, + IReadOnlyList scopeAttributes + ) + { + _resolver = resolver; + _scopeAttributes = scopeAttributes; + } + + /// + /// The test's container. + /// + public IServiceProvider Services => + _services ?? throw new InvalidOperationException("The container is not built yet."); + + /// + /// The arguments for the whole method, as the xUnit and NUnit packages resolve them. + /// + /// + /// The values of a data row, for the leading parameters. Empty for a test with no data. + /// + /// One argument per parameter, in declaration order. + /// + /// The container came from , which has no test + /// method. + /// + public Task ResolveArgumentsAsync(object?[] data) => + Resolver().ResolveArgumentsAsync(Services, data); + + /// + /// The value of the attributes on the parameter, or + /// null when none answers. + /// + /// + /// Null for a parameter that a supplies, because its + /// attributes do not run. + /// + /// A parameter of the test method. + /// + /// The container came from , which has no test + /// method. + /// + public Task GetParameterValueAsync(ParameterInfo parameter) => + Resolver().GetParameterValueAsync(parameter, Services); + + /// + /// , a keyed service, a registered service, or an unregistered + /// non-abstract class built with its [InjectValues]. Null when none applies. + /// + /// + /// A parameter with gets the keyed service only. + /// + /// The parameter to resolve. + public object? Resolve(ParameterInfo parameter) + { + if (parameter.ParameterType == typeof(IServiceProvider)) + { + return Services; + } + + return TestParameterResolver.ResolveFromContainer(parameter, Services, constructAny: false); + } + + /// + /// A keyed or unkeyed registered service, or null. + /// + /// The service type. + /// The service key, or null for the unkeyed service. + public object? Resolve(Type serviceType, object? serviceKey) + { + if (serviceKey == null) + { + return Services.GetService(serviceType); + } + + return Services is IKeyedServiceProvider keyed + ? keyed.GetKeyedService(serviceType, serviceKey) + : null; + } + + /// + /// Disposes every container that this container tracks, the last one built first. + /// + /// + /// Each container is disposed when another one throws. One exception is rethrown as it is, and + /// more than one are thrown as an . + /// + public async ValueTask DisposeAsync() + { + IServiceProvider[] providers; + + lock (_gate) + { + providers = _providers.ToArray(); + _providers.Clear(); + } + + List? exceptions = null; + + for (var i = providers.Length - 1; i >= 0; i--) + { + try + { + switch (providers[i]) + { + case IAsyncDisposable asyncDisposable: + await asyncDisposable.DisposeAsync(); + break; + case IDisposable disposable: + disposable.Dispose(); + break; + } + } + catch (Exception exception) + { + (exceptions ??= []).Add(exception); + } + } + + if (exceptions is [var single]) + { + ExceptionDispatchInfo.Capture(single).Throw(); + } + + if (exceptions != null) + { + throw new AggregateException(exceptions); + } + } + + internal void SetServices(IServiceProvider services) + { + Track(services); + _services = services; + } + + internal void Track(IServiceProvider provider) + { + lock (_gate) + { + _providers.Add(provider); + } + } + + /// + /// Registers into a child's collection this container's instances of the services that the + /// child shares with it. + /// + /// + /// The shared services are the type of each parameter with , and the + /// of each [TestExport(Shared = true)] in this + /// container's scope attributes. A type that an + /// names is not shared. Each instance is + /// resolved once and kept, so every child gets the same one. + /// + internal void RegisterSharedServices(IServiceCollection services, ITestMethodContext child) + { + var isolated = new HashSet { typeof(IServiceProvider) }; + + foreach ( + var registration in child + .Attributes.Concat(_scopeAttributes) + .OfType() + ) + { + isolated.UnionWith(registration.IsolatedServices(child.Method)); + } + + var shared = new List<(Type Type, object? Key)>(); + + foreach (var parameter in child.Method.GetParameters()) + { + if (parameter.IsDefined(typeof(SharedAttribute), inherit: false)) + { + shared.Add( + ( + parameter.ParameterType, + parameter.GetCustomAttribute()?.Key + ) + ); + } + } + + foreach (var export in _scopeAttributes.OfType()) + { + if (export.Shared) + { + shared.Add((export.Service, null)); + } + } + + foreach (var (type, key) in shared.Distinct()) + { + if (isolated.Contains(type) || SharedInstance(type, key) is not { } instance) + { + continue; + } + + services.Add( + key == null + ? new ServiceDescriptor(type, instance) + : new ServiceDescriptor(type, key, instance) + ); + } + } + + private object? SharedInstance(Type type, object? key) + { + lock (_gate) + { + if (!_sharedInstances.TryGetValue((type, key), out var instance)) + { + instance = Resolve(type, key); + _sharedInstances[(type, key)] = instance; + } + + return instance; + } + } + + private TestParameterResolver Resolver() => + _resolver + ?? throw new InvalidOperationException( + $"This container was built by {nameof(ModuleTestComposition.BuildScopeAsync)} for a class " + + "or an assembly. It has no test method, so it has no parameters to supply." + ); +} diff --git a/src/DependencyModules.Testing/Impl/TestMethodContext.cs b/src/DependencyModules.Testing/Impl/TestMethodContext.cs new file mode 100644 index 0000000..4baeed4 --- /dev/null +++ b/src/DependencyModules.Testing/Impl/TestMethodContext.cs @@ -0,0 +1,23 @@ +using System.Reflection; +using DependencyModules.Testing.Attributes.Interfaces; + +namespace DependencyModules.Testing.Impl; + +/// +/// The plain , for a runner that has no test-method model of its own. +/// +/// The test method. +/// +/// The attribute instances of the test, widest scope first: the assembly, then the class, then the +/// method. +/// +public sealed class TestMethodContext(MethodInfo method, IReadOnlyList attributes) + : ITestMethodContext +{ + /// + public MethodInfo Method { get; } = method ?? throw new ArgumentNullException(nameof(method)); + + /// + public IReadOnlyList Attributes { get; } = + attributes ?? throw new ArgumentNullException(nameof(attributes)); +} diff --git a/src/DependencyModules.Testing/Impl/TestParameterResolver.cs b/src/DependencyModules.Testing/Impl/TestParameterResolver.cs index afe69fc..a602000 100644 --- a/src/DependencyModules.Testing/Impl/TestParameterResolver.cs +++ b/src/DependencyModules.Testing/Impl/TestParameterResolver.cs @@ -25,6 +25,7 @@ public sealed class TestParameterResolver private readonly ITestMethodContext _testMethod; private readonly Dictionary> _valueProviders = new(); + private readonly Func? _skip; private bool _setupRan; /// @@ -36,6 +37,16 @@ public TestParameterResolver(ITestMethodContext testMethod) _testMethod = testMethod; } + /// + /// Creates a resolver whose parameters run no value provider in either + /// phase. skips the parameters that an override supplies. + /// + internal TestParameterResolver(ITestMethodContext testMethod, Func skip) + : this(testMethod) + { + _skip = skip; + } + /// /// Lets every parameter register what it needs, before the container is built. /// @@ -49,10 +60,13 @@ public void SetupServiceCollection(IServiceCollection serviceCollection) { foreach (var parameterInfo in _testMethod.Method.GetParameters()) { - var providers = parameterInfo - .GetCustomAttributes() - .OfType() - .ToList(); + var providers = + _skip != null && _skip(parameterInfo) + ? [] + : parameterInfo + .GetCustomAttributes() + .OfType() + .ToList(); _valueProviders.Add(parameterInfo, providers); @@ -90,13 +104,7 @@ public void SetupServiceCollection(IServiceCollection serviceCollection) object?[] data ) { - if (!_setupRan) - { - throw new InvalidOperationException( - $"{nameof(SetupServiceCollection)} must be called before {nameof(ResolveArgumentsAsync)}, " - + "while the service collection can still be added to." - ); - } + RequireSetup(nameof(ResolveArgumentsAsync)); var parameterList = _testMethod.Method.GetParameters(); var arguments = new List(data); @@ -107,12 +115,25 @@ public void SetupServiceCollection(IServiceCollection serviceCollection) var value = await ResolveFromParameterProviders(parameterInfo, serviceProvider); - arguments.Add(value ?? ResolveFromContainer(parameterInfo, serviceProvider)); + arguments.Add( + value ?? ResolveFromContainer(parameterInfo, serviceProvider, constructAny: true) + ); } return arguments.ToArray(); } + private void RequireSetup(string caller) + { + if (!_setupRan) + { + throw new InvalidOperationException( + $"{nameof(SetupServiceCollection)} must be called before {caller}, " + + "while the service collection can still be added to." + ); + } + } + /// /// A provider returning null stands aside for the next one, so several attributes can sit on one /// parameter with the first that answers winning. is special-cased @@ -128,7 +149,58 @@ IServiceProvider serviceProvider return serviceProvider; } - foreach (var valueProvider in _valueProviders[parameterInfo]) + return await ResolveFromValueProvidersAsync( + _valueProviders[parameterInfo], + parameterInfo, + serviceProvider + ); + } + + /// + /// The value of the attributes on one parameter, or + /// null when none answers. + /// + /// + /// is not a parameter of the test method. + /// + internal Task GetParameterValueAsync( + ParameterInfo parameterInfo, + IServiceProvider serviceProvider + ) + { + RequireSetup(nameof(GetParameterValueAsync)); + + if (!_valueProviders.TryGetValue(parameterInfo, out var providers)) + { + // A MethodInfo from another lookup can hand out other ParameterInfo objects for the + // same parameters. + providers = _valueProviders + .Where(entry => + entry.Key.Position == parameterInfo.Position + && entry.Key.Member.Equals(parameterInfo.Member) + ) + .Select(entry => entry.Value) + .FirstOrDefault(); + } + + if (providers == null) + { + throw new ArgumentException( + $"'{parameterInfo.Name}' is not a parameter of {_testMethod.Method.Name}.", + nameof(parameterInfo) + ); + } + + return ResolveFromValueProvidersAsync(providers, parameterInfo, serviceProvider); + } + + private async Task ResolveFromValueProvidersAsync( + List providers, + ParameterInfo parameterInfo, + IServiceProvider serviceProvider + ) + { + foreach (var valueProvider in providers) { var value = await valueProvider.GetParameterValueAsync( _testMethod, @@ -145,9 +217,16 @@ IServiceProvider serviceProvider return null; } - private object? ResolveFromContainer( + /// The parameter to resolve. + /// The test's container. + /// + /// False to construct only a non-abstract class, and to return null for any other type that the + /// container does not register. + /// + internal static object? ResolveFromContainer( ParameterInfo parameterInfo, - IServiceProvider serviceProvider + IServiceProvider serviceProvider, + bool constructAny ) { var keyedServicesAttribute = parameterInfo.GetCustomAttribute(); @@ -163,8 +242,14 @@ IServiceProvider serviceProvider ); } - return serviceProvider.GetService(parameterInfo.ParameterType) - ?? ConstructValueFromType(parameterInfo, serviceProvider); + var type = parameterInfo.ParameterType; + + return serviceProvider.GetService(type) + ?? ( + constructAny || (type.IsClass && !type.IsAbstract) + ? ConstructValueFromType(parameterInfo, serviceProvider) + : null + ); } /// diff --git a/src/DependencyModules.Testing/Impl/TestServiceOverride.cs b/src/DependencyModules.Testing/Impl/TestServiceOverride.cs new file mode 100644 index 0000000..2a07a93 --- /dev/null +++ b/src/DependencyModules.Testing/Impl/TestServiceOverride.cs @@ -0,0 +1,16 @@ +namespace DependencyModules.Testing.Impl; + +/// +/// An instance that the test's container returns for a service type and an optional key, such as a +/// mock. +/// +/// +/// registers each override after the modules and the +/// test's setup attributes, so an override replaces a [TestExport] for the same service. A +/// test parameter of the same type and key gets the override, and the parameter's +/// attributes do not run. +/// +/// The service type to register. +/// The instance to return. It must be assignable to . +/// The service key, or null for an unkeyed registration. +public sealed record TestServiceOverride(Type ServiceType, object Instance, object? ServiceKey); diff --git a/tests/DependencyModules.Specs/Snapshots/PublicApiTests.TestingApi.verified.txt b/tests/DependencyModules.Specs/Snapshots/PublicApiTests.TestingApi.verified.txt index 87d8791..5aae01d 100644 --- a/tests/DependencyModules.Specs/Snapshots/PublicApiTests.TestingApi.verified.txt +++ b/tests/DependencyModules.Specs/Snapshots/PublicApiTests.TestingApi.verified.txt @@ -109,6 +109,20 @@ namespace DependencyModules.Testing.Impl public static DependencyModules.Testing.Attributes.Interfaces.ICurrentTestProvider? Provider { get; set; } public static bool TryWriteLine(string message) { } } + public static class ModuleTestComposition + { + public static System.Threading.Tasks.ValueTask BuildAsync(Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.Collections.Generic.IReadOnlyList modules, DependencyModules.Testing.Attributes.Interfaces.ITestMethodContext testMethod, System.Collections.Generic.IReadOnlyList overrides, DependencyModules.Testing.Attributes.Interfaces.ICurrentTestProvider? currentTest, DependencyModules.Testing.Impl.ModuleTestContainer? parent) { } + public static System.Threading.Tasks.ValueTask BuildScopeAsync(Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.Collections.Generic.IReadOnlyList modules, System.Collections.Generic.IReadOnlyList scopeAttributes) { } + } + public sealed class ModuleTestContainer : System.IAsyncDisposable + { + public System.IServiceProvider Services { get; } + public System.Threading.Tasks.ValueTask DisposeAsync() { } + public System.Threading.Tasks.Task GetParameterValueAsync(System.Reflection.ParameterInfo parameter) { } + public object? Resolve(System.Reflection.ParameterInfo parameter) { } + public object? Resolve(System.Type serviceType, object? serviceKey) { } + public System.Threading.Tasks.Task ResolveArgumentsAsync(object?[] data) { } + } public static class SharedRegistrations { public static System.Collections.Generic.IReadOnlyCollection Collect(System.Reflection.MethodInfo method, System.Collections.Generic.IEnumerable knownAttributes) { } @@ -121,6 +135,12 @@ namespace DependencyModules.Testing.Impl public void Initialize(Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.IServiceProvider pinned, System.Collections.Generic.IReadOnlyCollection pinnedServices, System.Func build, System.Func start, System.Action track) { } public void Initialize(Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.IServiceProvider pinned, System.Collections.Generic.IReadOnlyCollection pinnedServices, System.Collections.Generic.IReadOnlyCollection namedServices, System.Func build, System.Func start, System.Action track) { } } + public sealed class TestMethodContext : DependencyModules.Testing.Attributes.Interfaces.ITestMethodContext + { + public TestMethodContext(System.Reflection.MethodInfo method, System.Collections.Generic.IReadOnlyList attributes) { } + public System.Collections.Generic.IReadOnlyList Attributes { get; } + public System.Reflection.MethodInfo Method { get; } + } public sealed class TestOutputLoggerProvider : Microsoft.Extensions.Logging.ILoggerProvider, System.IDisposable { public TestOutputLoggerProvider() { } @@ -134,4 +154,11 @@ namespace DependencyModules.Testing.Impl public System.Threading.Tasks.Task ResolveArgumentsAsync(System.IServiceProvider serviceProvider, object?[] data) { } public void SetupServiceCollection(Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection) { } } + public sealed class TestServiceOverride : System.IEquatable + { + public TestServiceOverride(System.Type ServiceType, object Instance, object? ServiceKey) { } + public object Instance { get; init; } + public object? ServiceKey { get; init; } + public System.Type ServiceType { get; init; } + } } diff --git a/tests/DependencyModules.Specs/TestingTests/ModuleTestCompositionTests.cs b/tests/DependencyModules.Specs/TestingTests/ModuleTestCompositionTests.cs new file mode 100644 index 0000000..39fca13 --- /dev/null +++ b/tests/DependencyModules.Specs/TestingTests/ModuleTestCompositionTests.cs @@ -0,0 +1,1055 @@ +using System.Reflection; +using DependencyModules.Runtime.Helpers; +using DependencyModules.Runtime.Interfaces; +using DependencyModules.Testing.Attributes; +using DependencyModules.Testing.Attributes.Interfaces; +using DependencyModules.Testing.Impl; +using Microsoft.Extensions.DependencyInjection; + +namespace DependencyModules.Specs.TestingTests; + +/// +/// Drives ModuleTestComposition against a plain ServiceCollection, with no test framework around it. +/// +public partial class ModuleTestCompositionTests +{ + [VerifyTest] + public async Task TheStepsRunInOrder() + { + var log = new Log(); + var services = new ServiceCollection(); + services.AddSingleton(log); + var builder = new BuilderAttribute(log, "build"); + + await using var container = await Build( + Context( + nameof(Samples.Supplied), + new EnvironmentAttribute(log, "Test"), + new SetupAttribute(log, "setup", s => s.AddSingleton()), + new FakeMockSupportAttribute(log), + builder, + new StartupAttribute(log) + ), + services: services, + modules: [new ServiceModule(s => s.AddSingleton(), log, "module")], + overrides: [new TestServiceOverride(typeof(IThing), new Thing(), null)], + currentTest: new FakeCurrentTest() + ); + + VerifyEquivalent( + log.ToArray(), + [ + "environment", + "module", + "mock support", + "setup", + "parameter value", + "build", + "startup", + ] + ); + + var registered = builder.Registered; + var source = registered.IndexOf(typeof(ITestContainerSource)); + var current = registered.IndexOf(typeof(ICurrentTestProvider)); + var environment = registered.IndexOf(typeof(IModuleEnvironment)); + var module = registered.IndexOf(typeof(ModuleMarker)); + var mock = registered.IndexOf(typeof(IThing)); + var setup = registered.IndexOf(typeof(SetupMarker)); + var parameter = registered.IndexOf(typeof(ParameterMarker)); + var overridden = registered.LastIndexOf(typeof(IThing)); + + Verify(source >= 0 && source < current); + Verify(current < environment); + Verify(environment < module); + Verify(module < mock); + Verify(mock < setup); + Verify(setup < parameter); + Verify(parameter < overridden); + } + + /// + /// The list is reversed before LoadModules, as ModuleTestCase does. + /// + [VerifyTest] + public async Task TheModulesAreLoadedReversed() + { + var thing = new ServiceModule(s => s.AddSingleton()); + var other = new ServiceModule(s => s.AddSingleton()); + + await using var container = await Build( + Context(nameof(Samples.NoParameters)), + modules: [thing, other] + ); + + Verify(container.Services.GetService()?.GetType() == LoadedWinner(other, thing)); + Verify(LoadedWinner(other, thing) != LoadedWinner(thing, other)); + } + + [VerifyTest] + public async Task TheNarrowestEnvironmentThatAnswersDecides() + { + var log = new Log(); + var module = new EnvironmentModule(); + + await using var container = await Build( + Context( + nameof(Samples.NoParameters), + new EnvironmentAttribute(log, "Wide"), + new EnvironmentAttribute(log, "Narrow"), + new EnvironmentAttribute(log, null) + ), + modules: [module] + ); + + Verify(module.Observed?.EnvironmentName == "Narrow"); + Verify(container.Services.GetService()?.EnvironmentName == "Narrow"); + } + + [VerifyTest] + public async Task WithNoEnvironmentProviderNoEnvironmentIsRegistered() + { + var services = new ServiceCollection(); + + await using var container = await Build( + Context(nameof(Samples.NoParameters)), + services: services + ); + + Verify(services.All(d => d.ServiceType != typeof(IModuleEnvironment))); + } + + [VerifyTest] + public async Task ATestExportBeatsAModule() + { + await using var container = await Build( + Context( + nameof(Samples.NoParameters), + new TestExportAttribute(typeof(IThing)) { Implementation = typeof(Thing) } + ), + modules: [new ServiceModule(s => s.AddSingleton())] + ); + + Verify(container.Services.GetService() is Thing); + } + + /// + /// Mock support runs first whatever its position, so a named implementation beats a mock. + /// + [VerifyTest] + public async Task MockSupportRunsBeforeTheOtherSetupAttributes() + { + await using var container = await Build( + Context( + nameof(Samples.NoParameters), + new TestExportAttribute(typeof(IThing)) { Implementation = typeof(Thing) }, + new FakeMockSupportAttribute(new Log()) + ) + ); + + Verify(container.Services.GetService() is Thing); + } + + [VerifyTest] + public async Task AnOverrideBeatsATestExport() + { + var instance = new Other(); + + await using var container = await Build( + Context( + nameof(Samples.NoParameters), + new TestExportAttribute(typeof(IThing)) { Implementation = typeof(Thing) } + ), + overrides: [new TestServiceOverride(typeof(IThing), instance, null)] + ); + + Verify(ReferenceEquals(container.Services.GetService(), instance)); + } + + [VerifyTest] + public async Task AKeyedOverrideIsRegisteredUnderItsKey() + { + var instance = new Other(); + + await using var container = await Build( + Context(nameof(Samples.NoParameters)), + overrides: [new TestServiceOverride(typeof(IThing), instance, "k")] + ); + + Verify(container.Services.GetService() is null); + Verify(ReferenceEquals(container.Resolve(typeof(IThing), "k"), instance)); + } + + /// + /// [Mock] without a mock-support attribute throws in its SetupServiceCollection. With an override + /// for the parameter, it does not run, and the parameter gets the override. + /// + [VerifyTest] + public async Task AnOverriddenParameterRunsNoValueProvider() + { + var instance = new Thing(); + + await using var container = await Build( + Context(nameof(Samples.Mocked)), + overrides: [new TestServiceOverride(typeof(IThing), instance, null)] + ); + + var arguments = await container.ResolveArgumentsAsync([]); + var parameter = MethodOf(nameof(Samples.Mocked)).GetParameters()[0]; + + Verify(ReferenceEquals(Single(arguments), instance)); + Verify(await container.GetParameterValueAsync(parameter) is null); + Verify(ReferenceEquals(container.Resolve(parameter), instance)); + } + + [VerifyTest] + public async Task AKeyedParameterIsOverriddenOnlyByItsKey() + { + var instance = new Thing(); + + await using var container = await Build( + Context(nameof(Samples.KeyedMock)), + overrides: [new TestServiceOverride(typeof(IThing), instance, "k")] + ); + + Verify(ReferenceEquals(Single(await container.ResolveArgumentsAsync([])), instance)); + + var exception = await ThrowsAsync(async () => + await Build( + Context(nameof(Samples.KeyedMock)), + overrides: [new TestServiceOverride(typeof(IThing), instance, null)] + ) + ); + + Verify(exception.Message.Contains("Mock library not found")); + } + + [VerifyTest] + public async Task AParameterWithNoOverrideRunsItsValueProvider() + { + var services = new ServiceCollection(); + services.AddSingleton(new Log()); + + await using var container = await Build( + Context(nameof(Samples.Supplied)), + services: services + ); + + var parameter = MethodOf(nameof(Samples.Supplied)).GetParameters()[0]; + + Verify((string?)Single(await container.ResolveArgumentsAsync([])) == "supplied"); + Verify((string?)await container.GetParameterValueAsync(parameter) == "supplied"); + Verify(services.Any(d => d.ServiceType == typeof(ParameterMarker))); + } + + [VerifyTest] + public async Task AnOverrideOfTheWrongTypeIsRejected() + { + var services = new ServiceCollection(); + + var exception = await ThrowsAsync(async () => + await Build( + Context(nameof(Samples.NoParameters)), + services: services, + overrides: [new TestServiceOverride(typeof(IThing), "text", null)] + ) + ); + + Verify(exception.ParamName == "overrides"); + Verify(services.Count == 0); + } + + [VerifyTest] + public async Task TheCurrentTestIsRegisteredWithoutChangingCurrentTestProvider() + { + var before = CurrentTest.Provider; + var currentTest = new FakeCurrentTest(); + + await using var container = await Build( + Context(nameof(Samples.NoParameters)), + currentTest: currentTest + ); + + Verify(ReferenceEquals(container.Services.GetService(), currentTest)); + Verify(ReferenceEquals(CurrentTest.Provider, before)); + } + + [VerifyTest] + public async Task WithNoCurrentTestNoneIsRegistered() + { + await using var container = await Build(Context(nameof(Samples.NoParameters))); + + Verify(container.Services.GetService() is null); + } + + [VerifyTest] + public async Task TheNarrowestBuilderBuildsTheContainer() + { + var log = new Log(); + + await using var container = await Build( + Context( + nameof(Samples.NoParameters), + new BuilderAttribute(log, "wide"), + new BuilderAttribute(log, "narrow") + ) + ); + + VerifyEquivalent(log.ToArray(), ["narrow"]); + } + + [VerifyTest] + public async Task StartupGetsTheBuiltContainer() + { + IServiceProvider? started = null; + + await using var container = await Build( + Context( + nameof(Samples.NoParameters), + new StartupAttribute( + new Log(), + provider => + { + started = provider; + return Task.CompletedTask; + } + ) + ) + ); + + Verify(ReferenceEquals(started, container.Services)); + } + + /// + /// The source builds with the same builder and runs the same startup, and the container tracks + /// and disposes what it builds. + /// + [VerifyTest] + public async Task TheContainerSourceBuildsLikeTheFirstContainer() + { + var log = new Log(); + var container = await Build( + Context( + nameof(Samples.NoParameters), + new BuilderAttribute(log, "build"), + new StartupAttribute(log) + ), + modules: [new ServiceModule(s => s.AddSingleton())] + ); + + var source = container.Services.GetRequiredService(); + var built = await source.CreateAsync(); + var first = container.Services.GetRequiredService(); + var second = built.GetRequiredService(); + + VerifyEquivalent(log.ToArray(), ["build", "startup", "build", "startup"]); + Verify(!ReferenceEquals(first, second)); + + await container.DisposeAsync(); + + Verify(first.Disposed); + Verify(second.Disposed); + } + + /// + /// Every parameter is pinned across the containers that the source builds, as under xUnit. + /// + [VerifyTest] + public async Task TheContainerSourceKeepsTheParameters() + { + await using var container = await Build( + Context(nameof(Samples.TakesAStore)), + modules: [new ServiceModule(s => s.AddSingleton())] + ); + + var built = await container + .Services.GetRequiredService() + .CreateAsync(); + + Verify( + ReferenceEquals( + built.GetRequiredService(), + container.Services.GetRequiredService() + ) + ); + } + + [VerifyTest] + public async Task AFailedStartupDisposesTheContainer() + { + Tracked? tracked = null; + + var exception = await ThrowsAsync(async () => + await Build( + Context( + nameof(Samples.NoParameters), + new StartupAttribute( + new Log(), + provider => + { + tracked = provider.GetRequiredService(); + throw new InvalidOperationException("startup"); + } + ) + ), + modules: [new ServiceModule(s => s.AddSingleton())] + ) + ); + + Verify(exception.Message == "startup"); + Verify(tracked is { Disposed: true }); + } + + /// + /// The exception of the failed step is the one rethrown, not the one of the disposal. + /// + [VerifyTest] + public async Task AFailedDisposalDoesNotHideTheFailure() + { + var exception = await ThrowsAsync(async () => + await Build( + Context( + nameof(Samples.NoParameters), + new ThrowingDisposalBuilderAttribute(), + new StartupAttribute( + new Log(), + _ => throw new InvalidOperationException("startup") + ) + ) + ) + ); + + Verify(exception.Message == "startup"); + } + + [VerifyTest] + public async Task AFailureBeforeTheBuildIsRethrown() + { + var exception = await ThrowsAsync(async () => + await Build( + Context( + nameof(Samples.NoParameters), + new SetupAttribute( + new Log(), + "setup", + _ => throw new InvalidOperationException("setup") + ) + ) + ) + ); + + Verify(exception.Message == "setup"); + } + + [VerifyTest] + public async Task DisposeAsyncDisposesEveryContainerWhenOneThrows() + { + var container = await Build( + Context(nameof(Samples.NoParameters), new ThrowingDisposalBuilderAttribute()) + ); + + var built = await container + .Services.GetRequiredService() + .CreateAsync(); + + var exception = await ThrowsAsync(async () => + await container.DisposeAsync() + ); + + Verify(exception.InnerExceptions.Count == 2); + Verify(((ThrowingDisposalProvider)built).DisposeCalled); + Verify(((ThrowingDisposalProvider)container.Services).DisposeCalled); + + // Everything was disposed once. A second call has nothing left to dispose. + await container.DisposeAsync(); + } + + [VerifyTest] + public async Task OneDisposalFailureIsRethrownAsItIs() + { + var container = await Build( + Context(nameof(Samples.NoParameters), new ThrowingDisposalBuilderAttribute()) + ); + + var exception = await ThrowsExactlyAsync(async () => + await container.DisposeAsync() + ); + + Verify(exception.Message == "dispose"); + } + + [VerifyTest] + public async Task ADataRowSuppliesTheLeadingParameters() + { + await using var container = await Build( + Context(nameof(Samples.Mixed)), + modules: [new ServiceModule(s => s.AddSingleton())] + ); + + var arguments = await container.ResolveArgumentsAsync([7]); + + Verify(arguments.Length == 3); + Verify((int?)arguments[0] == 7); + Verify(arguments[1] is Thing); + Verify(ReferenceEquals(arguments[2], container.Services)); + } + + [VerifyTest] + public async Task ResolveFindsServicesAndBuildsOnlyClasses() + { + var keyed = new Other(); + + await using var container = await Build( + Context(nameof(Samples.Resolvable)), + modules: + [ + new ServiceModule(s => + { + s.AddSingleton(); + s.AddKeyedSingleton("k", keyed); + }), + ] + ); + + var parameters = MethodOf(nameof(Samples.Resolvable)).GetParameters(); + + Verify(ReferenceEquals(container.Resolve(parameters[0]), container.Services)); + Verify(container.Resolve(parameters[1]) is Thing); + Verify(ReferenceEquals(container.Resolve(parameters[2]), keyed)); + var constructed = (NeedsAValue)container.Resolve(parameters[3])!; + + Verify(constructed.Text == "text"); + Verify(constructed.Thing is Thing); + Verify(container.Resolve(parameters[4]) is null); + Verify(container.Resolve(parameters[5]) is null); + + Verify(container.Resolve(typeof(IThing), null) is Thing); + Verify(ReferenceEquals(container.Resolve(typeof(IThing), "k"), keyed)); + Verify(container.Resolve(typeof(IThing), "missing") is null); + Verify(container.Resolve(typeof(IOther), null) is null); + } + + [VerifyTest] + public async Task GetParameterValueAsyncRejectsAnotherMethodsParameter() + { + await using var container = await Build(Context(nameof(Samples.NoParameters))); + + var parameter = MethodOf(nameof(Samples.Mixed)).GetParameters()[0]; + + await ThrowsAsync(async () => + await container.GetParameterValueAsync(parameter) + ); + } + + [VerifyTest] + public async Task AScopeContainerRegistersOnlyTheSharedTestExports() + { + await using var scope = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [new ServiceModule(s => s.AddSingleton())], + [ + new TestExportAttribute(typeof(IThing)) { Implementation = typeof(Thing) }, + new TestExportAttribute(typeof(Store)) { Shared = true }, + ] + ); + + Verify(scope.Services.GetService() is Other); + Verify(scope.Services.GetService() is not null); + Verify(scope.Services.GetService() is null); + } + + [VerifyTest] + public async Task AScopeContainerLoadsTheModulesReversed() + { + var thing = new ServiceModule(s => s.AddSingleton()); + var other = new ServiceModule(s => s.AddSingleton()); + + await using var scope = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [thing, other], + [] + ); + + Verify(scope.Services.GetService()?.GetType() == LoadedWinner(other, thing)); + } + + [VerifyTest] + public async Task AScopeContainerHasNoParameters() + { + await using var scope = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [], + [] + ); + + var parameter = MethodOf(nameof(Samples.Mixed)).GetParameters()[0]; + + await ThrowsAsync(async () => + await scope.ResolveArgumentsAsync([]) + ); + await ThrowsAsync(async () => + await scope.GetParameterValueAsync(parameter) + ); + Verify(scope.Resolve(parameter) is null); + } + + /// + /// A transient registration in the parent is still one instance for every child, and a child's + /// own setup attribute for the type does not replace it. + /// + [VerifyTest] + public async Task ChildrenShareTheParentsInstanceOfASharedParameter() + { + await using var parent = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [new ServiceModule(s => s.AddTransient())], + [] + ); + + var context = Context(nameof(Samples.SharedStore), new TestExportAttribute(typeof(Store))); + IReadOnlyList modules = + [ + new ServiceModule(s => s.AddTransient()), + ]; + + Store first; + Store second; + IThing firstThing; + IThing secondThing; + + await using (var child = await Build(context, modules: modules, parent: parent)) + { + var arguments = await child.ResolveArgumentsAsync([]); + first = (Store)arguments[0]!; + firstThing = (IThing)arguments[1]!; + } + + await using (var child = await Build(context, modules: modules, parent: parent)) + { + var arguments = await child.ResolveArgumentsAsync([]); + second = (Store)arguments[0]!; + secondThing = (IThing)arguments[1]!; + } + + Verify(ReferenceEquals(first, second)); + Verify(!ReferenceEquals(firstThing, secondThing)); + + // The children registered the instance, so they did not dispose it. + Verify(!first.Disposed); + } + + [VerifyTest] + public async Task ChildrenShareTheParentsSharedTestExports() + { + await using var parent = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [], + [ + new TestExportAttribute(typeof(IThing)) + { + Implementation = typeof(Thing), + Shared = true, + }, + new TestExportAttribute(typeof(IOther)) { Implementation = typeof(Other) }, + ] + ); + + await using var child = await Build( + Context(nameof(Samples.NoParameters)), + modules: [new ServiceModule(s => s.AddSingleton())], + parent: parent + ); + await using var second = await Build(Context(nameof(Samples.NoParameters)), parent: parent); + + // The export is transient, so the parent itself returns a new instance on each call. + Verify(child.Services.GetService() is Thing); + Verify( + ReferenceEquals( + child.Services.GetService(), + second.Services.GetService() + ) + ); + Verify(parent.Services.GetService() is null); + Verify(child.Services.GetService() is Other); + } + + [VerifyTest] + public async Task AKeyedSharedParameterIsSharedUnderItsKey() + { + await using var parent = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [new ServiceModule(s => s.AddKeyedTransient("k"))], + [] + ); + + await using var first = await Build( + Context(nameof(Samples.KeyedSharedStore)), + parent: parent + ); + await using var second = await Build( + Context(nameof(Samples.KeyedSharedStore)), + parent: parent + ); + + var store = Single(await first.ResolveArgumentsAsync([])); + + Verify(store is Store); + Verify(ReferenceEquals(store, Single(await second.ResolveArgumentsAsync([])))); + Verify(first.Services.GetService() is null); + } + + [VerifyTest] + public async Task AnIsolatedServiceIsNotTakenFromTheParent() + { + await using var parent = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [new ServiceModule(s => s.AddSingleton())], + [] + ); + + await using var child = await Build( + Context(nameof(Samples.SharedStore), new IsolatesAttribute(typeof(Store))), + modules: [new ServiceModule(s => s.AddSingleton())], + parent: parent + ); + + Verify( + !ReferenceEquals( + child.Services.GetService(), + parent.Services.GetService() + ) + ); + } + + [VerifyTest] + public async Task AnOverrideBeatsTheParentsInstance() + { + var instance = new Store(); + + await using var parent = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [new ServiceModule(s => s.AddSingleton())], + [] + ); + + await using var child = await Build( + Context(nameof(Samples.SharedStore)), + overrides: [new TestServiceOverride(typeof(Store), instance, null)], + parent: parent + ); + + Verify(ReferenceEquals(child.Services.GetService(), instance)); + } + + [VerifyTest] + public async Task ASharedServiceTheParentDoesNotHaveIsLeftToTheChild() + { + await using var parent = await ModuleTestComposition.BuildScopeAsync( + new ServiceCollection(), + [], + [] + ); + + await using var child = await Build( + Context(nameof(Samples.SharedStore)), + modules: [new ServiceModule(s => s.AddSingleton())], + parent: parent + ); + + Verify(child.Services.GetService() is not null); + } + + [VerifyTest] + public void TestMethodContextKeepsWhatItIsGiven() + { + var method = MethodOf(nameof(Samples.NoParameters)); + Attribute[] attributes = [new SharedAttribute()]; + + var context = new TestMethodContext(method, attributes); + + Verify(ReferenceEquals(context.Method, method)); + Verify(ReferenceEquals(context.Attributes, attributes)); + Throws(() => new TestMethodContext(null!, attributes)); + Throws(() => new TestMethodContext(method, null!)); + } + + private static ValueTask Build( + TestMethodContext context, + IServiceCollection? services = null, + IReadOnlyList? modules = null, + IReadOnlyList? overrides = null, + ICurrentTestProvider? currentTest = null, + ModuleTestContainer? parent = null + ) => + ModuleTestComposition.BuildAsync( + services ?? new ServiceCollection(), + modules ?? [], + context, + overrides ?? [], + currentTest, + parent + ); + + /// + /// The type that wins when LoadModules is given these modules in this order. + /// + private static Type? LoadedWinner(params IDependencyModule[] modules) + { + var services = new ServiceCollection(); + DependencyRegistry.LoadModules(services, modules); + + return services.BuildServiceProvider().GetService()?.GetType(); + } + + private static TestMethodContext Context(string method, params Attribute[] attributes) => + new(MethodOf(method), attributes); + + private static MethodInfo MethodOf(string name) => typeof(Samples).GetMethod(name)!; + + private static class Samples + { + public static void NoParameters() { } + + public static void Supplied([Supplies("supplied")] string value) { } + + public static void Mocked([Mock] IThing thing) { } + + public static void KeyedMock([Mock] [FromKeyedServices("k")] IThing thing) { } + + public static void Mixed(int row, IThing thing, IServiceProvider provider) { } + + public static void TakesAStore(Store store) { } + + public static void SharedStore([Shared] Store store, IThing thing) { } + + public static void KeyedSharedStore([Shared] [FromKeyedServices("k")] Store store) { } + + public static void Resolvable( + IServiceProvider provider, + IThing thing, + [FromKeyedServices("k")] IThing keyed, + [InjectValues("text")] NeedsAValue value, + IOther missing, + [FromKeyedServices("missing")] IThing missingKeyed + ) { } + } + + private sealed class Log : List; + + private interface IThing; + + private interface IOther; + + private sealed class Thing : IThing; + + private sealed class Other : IThing, IOther; + + private sealed class ModuleMarker; + + private sealed class SetupMarker; + + private sealed class ParameterMarker; + + private sealed class Store : IDisposable + { + public bool Disposed { get; private set; } + + public void Dispose() => Disposed = true; + } + + private sealed class Tracked : IDisposable + { + public bool Disposed { get; private set; } + + public void Dispose() => Disposed = true; + } + + private sealed class NeedsAValue(IThing thing, string text) + { + public IThing Thing { get; } = thing; + + public string Text { get; } = text; + } + + private sealed class ServiceModule( + Action register, + Log? log = null, + string? name = null + ) : IDependencyModule + { + public void PopulateServiceCollection(IServiceCollection serviceCollection) { } + + public void InternalApplyServices(IServiceCollection serviceCollection) + { + if (name != null) + { + log?.Add(name); + } + + register(serviceCollection); + } + } + + private sealed class EnvironmentModule + : IDependencyModule, + IEnvironmentServiceCollectionConfiguration + { + public IModuleEnvironment? Observed { get; private set; } + + public void PopulateServiceCollection(IServiceCollection serviceCollection) { } + + public void ConfigureServices( + IServiceCollection services, + IModuleEnvironment environment + ) => Observed = environment; + } + + private sealed class StubEnvironment(string name) : IModuleEnvironment + { + public string EnvironmentName => name; + + public string? Value(string valueName) => null; + } + + private sealed class FakeCurrentTest : ICurrentTestProvider + { + public object? Key => this; + + public string? DisplayName => "fake"; + + public Assembly? Assembly => null; + + public bool TryWriteLine(string message) => false; + } + + private sealed class EnvironmentAttribute(Log log, string? name) + : Attribute, + IModuleEnvironmentProvider + { + public IModuleEnvironment? ProvideEnvironment(MethodInfo testMethod) + { + log.Add("environment"); + + return name == null ? null : new StubEnvironment(name); + } + } + + private sealed class SetupAttribute(Log log, string name, Action setup) + : Attribute, + ITestServiceSetupAttribute + { + public void SetupServiceCollection( + ITestMethodContext testMethod, + IServiceCollection serviceCollection + ) + { + log.Add(name); + setup(serviceCollection); + } + } + + private sealed class FakeMockSupportAttribute(Log log) + : Attribute, + ITestServiceSetupAttribute, + IMockSupportAttribute + { + public object ProvideMock(Type type) => throw new NotSupportedException(); + + public void SetupServiceCollection( + ITestMethodContext testMethod, + IServiceCollection serviceCollection + ) + { + log.Add("mock support"); + serviceCollection.AddSingleton(); + } + } + + private sealed class BuilderAttribute(Log log, string name) + : Attribute, + IServiceProviderBuilderAttribute + { + public List Registered { get; } = []; + + public IServiceProvider BuildServiceProvider( + ITestMethodContext testMethod, + IServiceCollection serviceCollection + ) + { + log.Add(name); + Registered.Clear(); + Registered.AddRange(serviceCollection.Select(descriptor => descriptor.ServiceType)); + + return serviceCollection.BuildServiceProvider(); + } + } + + private sealed class ThrowingDisposalBuilderAttribute + : Attribute, + IServiceProviderBuilderAttribute + { + public IServiceProvider BuildServiceProvider( + ITestMethodContext testMethod, + IServiceCollection serviceCollection + ) => new ThrowingDisposalProvider(serviceCollection.BuildServiceProvider()); + } + + private sealed class ThrowingDisposalProvider(ServiceProvider inner) + : IServiceProvider, + IDisposable + { + public bool DisposeCalled { get; private set; } + + public object? GetService(Type serviceType) => inner.GetService(serviceType); + + public void Dispose() + { + DisposeCalled = true; + inner.Dispose(); + + throw new InvalidOperationException("dispose"); + } + } + + private sealed class StartupAttribute(Log log, Func? startup = null) + : Attribute, + ITestStartupAttribute + { + public Task StartupAsync(ITestMethodContext testMethod, IServiceProvider serviceProvider) + { + log.Add("startup"); + + return startup?.Invoke(serviceProvider) ?? Task.CompletedTask; + } + } + + private sealed class IsolatesAttribute(Type service) : Attribute, ISharedTestRegistration + { + public IReadOnlyList IsolatedServices(MethodInfo testMethod) => [service]; + } + + [AttributeUsage(AttributeTargets.Parameter)] + private sealed class SuppliesAttribute(string value) : Attribute, ITestParameterValueProvider + { + public void SetupServiceCollection( + ITestMethodContext testMethod, + IServiceCollection serviceCollection, + ParameterInfo parameter + ) + { + var log = (Log) + serviceCollection + .Single(descriptor => descriptor.ServiceType == typeof(Log)) + .ImplementationInstance!; + + log.Add("parameter " + parameter.Name); + serviceCollection.AddSingleton(new ParameterMarker()); + } + + public Task GetParameterValueAsync( + ITestMethodContext testMethod, + IServiceProvider serviceProvider, + ParameterInfo parameter + ) => Task.FromResult(value); + } +}