Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ namespace DependencyModules.Runtime.Interfaces;
/// integrations consult this before loading any module, which is the whole difference.
/// </para>
/// <para>
/// Beside <see cref="IDependencyModuleProvider" /> 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
/// <see cref="MethodInfo" /> rather than a test-method context for the same reason.
/// The parameter is a <see cref="MethodInfo" /> 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.
/// </para>
/// <para>
/// Attributes are consulted widest scope first - assembly, then class, then method - and the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
16 changes: 12 additions & 4 deletions src/DependencyModules.Testing/DependencyModules.Testing.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,27 @@
<Nullable>enable</Nullable>
<IsPackable>True</IsPackable>
<PackageId>DependencyModules.Testing</PackageId>
<Description>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.</Description>
<Description>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.</Description>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<!-- Framework-matched per TFM; see DependencyModules.Runtime.csproj for why. -->
<!--
Framework-matched per TFM; see DependencyModules.Runtime.csproj for why. The same versions of
Microsoft.Extensions.DependencyInjection as DependencyModules.xUnit and DependencyModules.NUnit.
ModuleTestComposition calls its BuildServiceProvider().
-->
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1"/>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0"/>
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0"/>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\DependencyModules.Runtime\DependencyModules.Runtime.csproj"/>
</ItemGroup>

</Project>
278 changes: 278 additions & 0 deletions src/DependencyModules.Testing/Impl/ModuleTestComposition.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Builds a test's container from modules and testing attributes, the same way for every runner.
/// </summary>
public static class ModuleTestComposition
{
/// <summary>
/// Builds the container of one test.
/// </summary>
/// <remarks>
/// <para>The steps, in order:</para>
/// <list type="number">
/// <item>Register an <see cref="ITestContainerSource"/>.</item>
/// <item>Register <paramref name="currentTest"/> when it is not null.</item>
/// <item>Register the environment from the narrowest <see cref="IModuleEnvironmentProvider"/> that answers.</item>
/// <item>Load <paramref name="modules"/>, reversed.</item>
/// <item>Run the <see cref="ITestServiceSetupAttribute"/>s, the <see cref="IMockSupportAttribute"/>s first.</item>
/// <item>When <paramref name="parent"/> is set, register the parent's instances of the shared services.</item>
/// <item>Run <see cref="ITestParameterValueProvider.SetupServiceCollection"/> for each parameter that no override names.</item>
/// <item>Register <paramref name="overrides"/> as instances.</item>
/// <item>Build with the narrowest <see cref="IServiceProviderBuilderAttribute"/>, or <c>BuildServiceProvider()</c>.</item>
/// <item>Run the <see cref="ITestStartupAttribute"/>s.</item>
/// <item>Initialize the <see cref="TestContainerSource"/>.</item>
/// </list>
/// <para>
/// When a step throws, every container built so far is disposed and the exception is rethrown.
/// </para>
/// </remarks>
/// <param name="services">
/// The collection to build into. A runner registers its own services in it first.
/// </param>
/// <param name="modules">
/// The modules in declaration order: the runner's own modules first, then the module attributes,
/// widest scope first.
/// </param>
/// <param name="testMethod">The test method and its attribute instances, widest scope first.</param>
/// <param name="overrides">The instances that replace services, such as mocks.</param>
/// <param name="currentTest">
/// Registered as the container's <see cref="ICurrentTestProvider"/> when it is not null.
/// <see cref="CurrentTest.Provider"/> is not changed.
/// </param>
/// <param name="parent">
/// A class or assembly container from <see cref="BuildScopeAsync"/>, or null.
/// </param>
/// <exception cref="ArgumentException">
/// The instance of an override is not assignable to its service type.
/// </exception>
public static async ValueTask<ModuleTestContainer> BuildAsync(
IServiceCollection services,
IReadOnlyList<IDependencyModule> modules,
ITestMethodContext testMethod,
IReadOnlyList<TestServiceOverride> 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<ITestContainerSource>(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;
}
}

/// <summary>
/// Builds the shared container of a class or an assembly, which <see cref="BuildAsync"/> takes
/// as its parent.
/// </summary>
/// <remarks>
/// It loads <paramref name="modules"/>, reversed, with the default environment. It registers
/// each <c>[TestExport(Shared = true)]</c> in <paramref name="scopeAttributes"/> and builds with
/// <c>BuildServiceProvider()</c>. It runs nothing that needs a test method.
/// </remarks>
/// <param name="services">The collection to build into.</param>
/// <param name="modules">The modules in declaration order, as for <see cref="BuildAsync"/>.</param>
/// <param name="scopeAttributes">The attribute instances of the class or the assembly, widest scope first.</param>
public static ValueTask<ModuleTestContainer> BuildScopeAsync(
IServiceCollection services,
IReadOnlyList<IDependencyModule> modules,
IReadOnlyList<Attribute> scopeAttributes
)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(modules);
ArgumentNullException.ThrowIfNull(scopeAttributes);

LoadModules(services, modules);

foreach (var export in scopeAttributes.OfType<TestExportAttribute>())
{
if (export.Shared)
{
export.Register(services);
}
}

var container = new ModuleTestContainer(null, scopeAttributes);

container.SetServices(services.BuildServiceProvider());

return new ValueTask<ModuleTestContainer>(container);
}

private static bool IsOverridden(
ParameterInfo parameter,
IReadOnlyList<TestServiceOverride> overrides
)
{
var key = parameter.GetCustomAttribute<FromKeyedServicesAttribute>()?.Key;

return overrides.Any(entry =>
entry.ServiceType == parameter.ParameterType && Equals(entry.ServiceKey, key)
);
}

/// <remarks>
/// Before the modules, because <c>LoadModules</c> decides <c>[IfEnvironment]</c> from the
/// <see cref="IModuleEnvironment"/> already in the collection.
/// </remarks>
private static void SeedEnvironment(
IServiceCollection services,
MethodInfo method,
IReadOnlyList<Attribute> attributes
)
{
IModuleEnvironment? environment = null;

foreach (var provider in attributes.OfType<IModuleEnvironmentProvider>())
{
environment = provider.ProvideEnvironment(method) ?? environment;
}

if (environment != null)
{
services.Add(new ServiceDescriptor(typeof(IModuleEnvironment), environment));
}
}

private static void LoadModules(
IServiceCollection services,
IReadOnlyList<IDependencyModule> modules
)
{
var reversed = modules.ToArray();

Array.Reverse(reversed);

DependencyRegistry<object>.LoadModules(services, reversed);
}

private static void SetupServiceSetupAttributes(
ITestMethodContext testMethod,
IServiceCollection services,
IReadOnlyList<Attribute> attributes
)
{
var setupAttributes = attributes
.OfType<ITestServiceSetupAttribute>()
.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<Attribute> attributes
)
{
var builder = attributes.OfType<IServiceProviderBuilderAttribute>().LastOrDefault();

return builder != null
? builder.BuildServiceProvider(testMethod, services)
: services.BuildServiceProvider();
}

private static async ValueTask StartAsync(
ITestMethodContext testMethod,
IReadOnlyList<Attribute> attributes,
IServiceProvider provider
)
{
foreach (var startupAttribute in attributes.OfType<ITestStartupAttribute>())
{
await startupAttribute.StartupAsync(testMethod, provider);
}
}
}
Loading
Loading