diff --git a/Documentation/Changelog.md b/Documentation/Changelog.md
index 1c5a8650a..1f9105192 100644
--- a/Documentation/Changelog.md
+++ b/Documentation/Changelog.md
@@ -7,9 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased
+### Improvements
+
+- Implement dynamic exclusion filters for Coverlet.MTP assemblies [#1946](https://github.com/coverlet-coverage/coverlet/pull/1946)
+
### Fixed
- Fix Regression in branch coverage for lambda expressions [#1937](https://github.com/coverlet-coverage/coverlet/issues/1937)
+- Fix coverlet.MTP crashes during instrumentation [#1934](https://github.com/coverlet-coverage/coverlet/issues/1934)
## Release date 2026-05-18
diff --git a/Documentation/Coverlet.MTP.Integration.md b/Documentation/Coverlet.MTP.Integration.md
index c87580747..4eb4dd812 100644
--- a/Documentation/Coverlet.MTP.Integration.md
+++ b/Documentation/Coverlet.MTP.Integration.md
@@ -99,21 +99,28 @@ Coverlet.MTP applies sensible default exclusions to reduce noise in coverage rep
When using command line options **without** a configuration file, the following defaults are **automatically merged** with user-specified exclusions:
-- **Default Exclude Filters:** `[coverlet.*]*`, `[xunit.*]*`, `[NUnit3.*]*`, `[nunit.*]*`, `[Microsoft.Testing.*]*`, `[Microsoft.Testplatform.*]*`, `[Microsoft.VisualStudio.TestPlatform.*]*`, `[MSTest*]*`, `[testhost*]*`
+- **Default Exclude Filters:** `[coverlet.*]*`, `[Microsoft.VisualStudio.TestPlatform.*]*`, `[testhost*]*`
- **Default Exclude by Attributes:** `ExcludeFromCodeCoverage`, `ExcludeFromCodeCoverageAttribute`, `GeneratedCodeAttribute`, `CompilerGeneratedAttribute`
+**Dynamic Exclude Filters (Assembly Naming Convention):**
+
+Coverlet.MTP also applies **dynamic exclusions** derived from the test assembly name and its namespace conventions at runtime. These are intended to automatically exclude common test infrastructure assemblies that follow standard naming patterns.
+
+> [!WARNING]
+> **Assembly Naming Limitation:** Dynamic exclusions rely on the assembly name following conventional naming schemas (e.g., `MyApp.Tests`, `MyApp.UnitTests`, `MyApp.IntegrationTests`). Assemblies that **do not follow these naming conventions** will **not** be automatically excluded by the dynamic filter. In such cases, you must add explicit `--coverlet-exclude` filters manually.
+
**Configuration File Behavior (Authoritative Mode):**
When a configuration file is present (`testconfig.json` or `coverlet.mtp.appsettings.json`), the configuration file becomes **authoritative**:
- **No defaults are injected** for `Format`, `Exclude`, `ExcludeByAttribute`, or other settings
-- You are responsible for defining all options you need
+- **Dynamic exclude filters are also not applied** — you are fully responsible for defining all exclusions
- Only the minimal `[coverlet.*]*` exclude filter is always prepended to prevent self-instrumentation
This design follows the principle that providing a configuration file represents your complete intent for coverlet settings.
> [!IMPORTANT]
-> **Breaking Change Notice:** In previous versions, defaults were merged even when a configuration file existed. Starting with this version, configuration files are authoritative. If you relied on default exclusions being applied automatically, you must now explicitly add them to your configuration file.
+> **Breaking Change Notice:** In previous versions, defaults were merged even when a configuration file existed. Starting with this version, configuration files are authoritative. If you relied on default exclusions (including dynamic ones) being applied automatically, you must now explicitly add them to your configuration file.
### Configuration Files
diff --git a/Documentation/Plans/DynamicExcludeFilters.md b/Documentation/Plans/DynamicExcludeFilters.md
new file mode 100644
index 000000000..87fecf85c
--- /dev/null
+++ b/Documentation/Plans/DynamicExcludeFilters.md
@@ -0,0 +1,267 @@
+# Dynamic Assembly Exclude Filters for coverlet.MTP
+
+## Problem
+
+`coverlet.MTP` maintains a hard-coded, growing list of `s_defaultExcludeFilters` to exclude test
+infrastructure assemblies (xunit, NUnit, MSTest, ReportGenerator.Mtp, etc.). This is brittle —
+every new test framework integration requires a code change.
+
+## Solution
+
+Instead of maintaining a static list, introspect the test process's own **loaded assemblies** at
+instrumentation time, convert them to exclude-filter patterns, and use those as the dynamic
+defaults. This list is only used when **no configuration file is present**, mirroring the existing
+config-file-takes-precedence logic.
+
+## Architecture
+
+```
+coverlet.core
+ └── Helpers/
+ └── ProcessAssemblyHelper.cs ← NEW: discovers loaded assemblies
+ └── Abstractions/
+ └── IProcessAssemblyHelper.cs ← NEW: interface for testability
+
+coverlet.MTP
+ └── Configuration/
+ └── CoverageConfiguration.cs ← MODIFIED: use dynamic list as defaults
+ └── CoverletMTPConstants.cs ← MODIFIED: keep only "[coverlet.*]*"
+ └── Collector/
+ └── CollectorExtension.cs ← MODIFIED: pass helper to CoverageConfiguration
+
+test/coverlet.core.tests
+ └── Helpers/
+ └── ProcessAssemblyHelperTests.cs ← NEW: unit tests
+
+test/coverlet.MTP.tests
+ └── Configuration/
+ └── CoverageConfigurationDynamicTests.cs ← NEW: integration-style tests
+```
+
+---
+
+## Implementation Steps
+
+### Step 1 — Add `IProcessAssemblyHelper` to `coverlet.core`
+
+**New file: `src/coverlet.core/Abstractions/IProcessAssemblyHelper.cs`**
+
+```csharp
+namespace Coverlet.Core.Abstractions;
+
+///
+/// Provides access to assemblies loaded by the current process,
+/// used to build dynamic exclude-filter defaults.
+///
+internal interface IProcessAssemblyHelper
+{
+ ///
+ /// Returns the simple assembly names (no version, culture, or public key token)
+ /// of assemblies directly loaded into the current process's default ALC,
+ /// excluding the assembly under test itself.
+ /// Transitive/indirect dependencies that are not yet loaded are not returned.
+ ///
+ ///
+ /// Simple name of the test assembly to exclude from the list.
+ ///
+ IReadOnlyList GetLoadedAssemblyNames(string testAssemblyName);
+}
+```
+
+**Design notes:**
+
+- Returns only **simple names** (e.g., `xunit.runner.utility`) — already-loaded assemblies only,
+ so no transitive dependencies are returned inadvertently.
+- The test assembly itself is excluded so it does not accidentally become an exclude-filter.
+- `internal` visibility — not part of the public API.
+
+---
+
+### Step 2 — Implement `ProcessAssemblyHelper` in `coverlet.core`
+
+**New file: `src/coverlet.core/Helpers/ProcessAssemblyHelper.cs`**
+
+```csharp
+using System.Reflection;
+using Coverlet.Core.Abstractions;
+
+namespace Coverlet.Core.Helpers;
+
+internal sealed class ProcessAssemblyHelper : IProcessAssemblyHelper
+{
+ ///
+ public IReadOnlyList GetLoadedAssemblyNames(string testAssemblyName)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(testAssemblyName);
+
+ return AppDomain.CurrentDomain
+ .GetAssemblies()
+ .Where(a => !a.IsDynamic && !string.IsNullOrWhiteSpace(a.Location))
+ .Select(a => a.GetName().Name)
+ .Where(name => !string.IsNullOrWhiteSpace(name)
+ && !name.Equals(testAssemblyName, StringComparison.OrdinalIgnoreCase))
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToList()!;
+ }
+}
+```
+
+**Design notes:**
+
+- Uses `AppDomain.CurrentDomain.GetAssemblies()` — returns **currently loaded** assemblies only
+ (no transitive unloaded dependencies).
+- Skips dynamic/in-memory assemblies (`a.IsDynamic`) which have no meaningful name.
+- Skips assemblies without a `Location` (e.g., in-memory emitted assemblies).
+- `Distinct` guards against edge cases where the same name appears under different load contexts.
+
+---
+
+### Step 3 — Add a conversion helper: assembly names → exclude filter patterns
+
+Add a `static` helper method inside `ProcessAssemblyHelper`:
+
+```csharp
+///
+/// Converts a simple assembly name to a coverlet exclude-filter pattern.
+/// e.g. "xunit.runner.utility" → "[xunit.runner.utility]*"
+///
+internal static string ToExcludeFilter(string assemblyName)
+ => $"[{assemblyName}]*";
+```
+
+---
+
+### Step 4 — Modify `CoverageConfiguration` in `coverlet.MTP`
+
+**File: `src/coverlet.MTP/Configuration/CoverageConfiguration.cs`**
+
+#### Changes
+
+1. Inject `IProcessAssemblyHelper` as an optional constructor parameter (defaults to
+ `ProcessAssemblyHelper` when `null`).
+2. Reduce `s_defaultExcludeFilters` to a single permanent baseline entry — `"[coverlet.*]*"`.
+ All other entries are now discovered dynamically.
+3. Add a private method `BuildDynamicExcludeFilters(string testAssemblyName)` that:
+ - Calls `IProcessAssemblyHelper.GetLoadedAssemblyNames(testAssemblyName)`.
+ - Converts each name to a filter pattern via `ProcessAssemblyHelper.ToExcludeFilter(...)`.
+ - Merges with `s_defaultExcludeFilters` (the baseline) and de-duplicates.
+4. Modify `GetExcludeFilters()` — Priority 3 (defaults) now calls `BuildDynamicExcludeFilters`.
+
+```csharp
+// Priority 3: Dynamic defaults from process-loaded assemblies
+string[] dynamicDefaults = BuildDynamicExcludeFilters(
+ Path.GetFileNameWithoutExtension(_testAssemblyName));
+LogOptionValue(CoverletOptionNames.Exclude, dynamicDefaults, isExplicit: false);
+return dynamicDefaults;
+```
+
+#### Constructor signature change
+
+```csharp
+public CoverageConfiguration(
+ ICommandLineOptions commandLineOptions,
+ CoverletMTPSettings? configFileSettings,
+ string? testAssemblyName,
+ ILogger? logger = null,
+ IProcessAssemblyHelper? processAssemblyHelper = null)
+```
+
+The `testAssemblyName` parameter is required so the test assembly itself is not added as an
+exclude-filter. `CollectorExtension` already holds `_testModulePath` when it constructs
+`CoverageConfiguration` — this is the correct handoff point.
+
+---
+
+### Step 5 — Update `CollectorExtension` call site
+
+**File: `src/coverlet.MTP/Collector/CollectorExtension.cs`**
+
+In `BeforeTestHostProcessStartAsync`, update the `CoverageConfiguration` construction:
+
+```csharp
+// Before
+var config = new CoverageConfiguration(
+ _commandLineOptions,
+ configFileSettings,
+ _loggerFactory.CreateLogger(nameof(CollectorExtension)));
+
+// After
+var config = new CoverageConfiguration(
+ _commandLineOptions,
+ configFileSettings,
+ testAssemblyName: Path.GetFileNameWithoutExtension(_testModulePath),
+ logger: _loggerFactory.CreateLogger(nameof(CollectorExtension)));
+ // processAssemblyHelper: null → uses ProcessAssemblyHelper by default
+```
+
+---
+
+### Step 6 — Configuration-file bypass (confirm existing behavior)
+
+The existing priority logic in `GetExcludeFilters()` is preserved unchanged:
+
+| Priority | Condition | Source | Dynamic list applied? |
+|---|---|---|---|
+| 1 | `--exclude` CLI flag set | CLI values merged with `[coverlet.*]*` baseline | No |
+| 2 | Config file present (`IsFromConfigFile == true`) | Config file only | **No** |
+| 3 | Neither | Dynamic loaded-assembly list | **Yes** |
+
+This satisfies the requirement: _"If a configuration file is used, this list will not be
+considered."_
+
+---
+
+### Step 7 — Update `CoverletMTPConstants.cs`
+
+Reduce to a single permanent baseline constant; remove the long static list (which is now
+discovered dynamically):
+
+```csharp
+// The coverlet assemblies themselves must always be excluded.
+// All other test framework assemblies are dynamically discovered at runtime
+// from the process's loaded assemblies (see ProcessAssemblyHelper).
+public const string DefaultExcludeFilter = "[coverlet.*]*";
+```
+
+---
+
+### Step 8 — Tests
+
+#### `coverlet.core.tests` — `ProcessAssemblyHelperTests.cs`
+
+| Test name | What it verifies |
+|---|---|
+| `WhenGetLoadedAssemblyNamesThenReturnsNonEmptyList` | Happy path: real loaded assemblies are returned |
+| `WhenGetLoadedAssemblyNamesThenExcludesTestAssembly` | The test assembly simple name is not in the result |
+| `WhenGetLoadedAssemblyNamesThenExcludesDynamicAssemblies` | No dynamic/in-memory assemblies included |
+| `WhenGetLoadedAssemblyNamesThenNoDuplicates` | Result contains no duplicate names |
+| `WhenTestAssemblyNameIsEmptyThenThrowsArgumentException` | Guard clause for empty string |
+| `WhenTestAssemblyNameIsWhitespaceThenThrowsArgumentException` | Guard clause for whitespace string |
+| `WhenToExcludeFilterCalledThenReturnsCorrectPattern` | `"xunit.core"` → `"[xunit.core]*"` |
+
+#### `coverlet.MTP.tests` — `CoverageConfigurationDynamicTests.cs`
+
+Uses `Mock` injected via the new constructor parameter to avoid real
+`AppDomain` calls in unit tests.
+
+| Test name | What it verifies |
+|---|---|
+| `WhenNoConfigFileThenDynamicFiltersApplied` | Priority 3: dynamic defaults returned |
+| `WhenNoConfigFileThenBaselineFilterAlwaysPresent` | `[coverlet.*]*` is always included |
+| `WhenConfigFilePresentThenDynamicFiltersNotApplied` | Priority 2 bypasses `IProcessAssemblyHelper` |
+| `WhenCliExcludeFlagSetThenBaselineMergedNotDynamic` | Priority 1 merges CLI values with baseline only |
+| `WhenDynamicHelperReturnsEmptyThenBaselineFallbackUsed` | Empty dynamic list still returns `[coverlet.*]*` |
+| `WhenDynamicHelperReturnsAssemblyNamesThenFiltersHaveCorrectFormat` | Pattern format `[name]*` is correct |
+
+---
+
+## Summary of Benefits
+
+| | Before | After |
+|---|---|---|
+| New framework support | Manual entry in `s_defaultExcludeFilters` | Automatic — if the assembly is loaded at test time |
+| `ReportGenerator.Mtp*` issue | Requires manual filter addition | Resolved automatically |
+| Config file users | Unaffected (Priority 2) | Unchanged |
+| CLI `--exclude` users | Merged with static defaults | Merged with `[coverlet.*]*` baseline only |
+| Testability | Static array — hard to unit test | `IProcessAssemblyHelper` is mockable |
+| Maintenance | Every new framework = code change | Zero maintenance for common cases |
diff --git a/src/coverlet.MTP/Collector/CollectorExtension.cs b/src/coverlet.MTP/Collector/CollectorExtension.cs
index 474f88bde..3ff0c3044 100644
--- a/src/coverlet.MTP/Collector/CollectorExtension.cs
+++ b/src/coverlet.MTP/Collector/CollectorExtension.cs
@@ -115,8 +115,13 @@ Task ITestHostProcessLifetimeHandler.BeforeTestHostProcessStartAsync(Cancellatio
// Load configuration file settings (coverlet.mtp.appsettings.json)
CoverletMTPSettings? configFileSettings = LoadConfigurationFileSettings(_testModulePath!);
- // Create merged configuration: command-line options take precedence over config file
- var config = new CoverageConfiguration(_commandLineOptions, configFileSettings, _loggerFactory.CreateLogger(nameof(CollectorExtension)));
+ // Create merged configuration: command-line options take precedence over config file.
+ // testAssemblyName is passed so the dynamic exclude-filter logic can omit the test assembly itself.
+ var config = new CoverageConfiguration(
+ _commandLineOptions,
+ configFileSettings,
+ testModulePath: _testModulePath,
+ logger: _loggerFactory.CreateLogger(nameof(CollectorExtension)));
_configuration.DeterministicReport = config.DeterministicReport;
_configuration.DisableManagedInstrumentationRestore = false;
_configuration.DoesNotReturnAttributes = config.GetDoesNotReturnAttributes();
@@ -205,9 +210,11 @@ private static string FormatErrorForDisplay(Exception ex)
if (ex is AggregateException aggEx && aggEx.InnerExceptions.Count > 0)
{
var distinctMessages = aggEx.InnerExceptions
+#pragma warning disable IDE0200
.Select(e => GetConciseErrorMessage(e))
.Distinct()
.ToList();
+#pragma warning restore IDE0200
return string.Join(Environment.NewLine + " ", distinctMessages);
}
@@ -221,12 +228,7 @@ private static string FormatErrorForDisplay(Exception ex)
private static string GetConciseErrorMessage(Exception ex)
{
// For IOException (file access issues), include the specific file info
- if (ex is IOException ioEx)
- {
- return ioEx.Message;
- }
-
- return ex.Message;
+ return ex is IOException ioEx ? ioEx.Message : ex.Message;
}
///
@@ -449,9 +451,7 @@ private static string InjectTimestamp(string filename, DateTime utcNow)
{
string timestamp = utcNow.ToString("ddMMyyHHmmssfff");
int lastDot = filename.LastIndexOf('.');
- if (lastDot > 0)
- return filename.Insert(lastDot, $".{timestamp}");
- return $"{filename}.{timestamp}";
+ return lastDot > 0 ? filename.Insert(lastDot, $".{timestamp}") : $"{filename}.{timestamp}";
}
///
@@ -599,12 +599,7 @@ private string GetHitsFilePath()
// Reject invalid filename characters
char[] invalidChars = Path.GetInvalidFileNameChars();
- if (prefix.IndexOfAny(invalidChars) >= 0)
- {
- return null;
- }
-
- return prefix;
+ return prefix.IndexOfAny(invalidChars) >= 0 ? null : prefix;
}
private string? ResolveTestModulePath()
diff --git a/src/coverlet.MTP/Configuration/CoverageConfiguration.cs b/src/coverlet.MTP/Configuration/CoverageConfiguration.cs
index 61d981fad..8ae0271a2 100644
--- a/src/coverlet.MTP/Configuration/CoverageConfiguration.cs
+++ b/src/coverlet.MTP/Configuration/CoverageConfiguration.cs
@@ -12,20 +12,13 @@ internal sealed class CoverageConfiguration
private readonly ICommandLineOptions _commandLineOptions;
private readonly ILogger? _logger;
private readonly CoverletMTPSettings? _configFileSettings;
+ private readonly Coverlet.Core.Abstractions.IProcessAssemblyHelper _processAssemblyHelper;
+ /// Full path to the test module (.dll), used to locate its deps.json for dynamic exclude discovery.
+ private readonly string? _testModulePath;
- // Default exclusions for user convenience, to avoid common noise in coverage reports. These are merged with any user-specified exclusions.
- private static readonly string[] s_defaultExcludeFilters =
- [
- "[coverlet.*]*",
- "[xunit.*]*",
- "[NUnit3.*]*",
- "[nunit.*]*",
- "[Microsoft.Testing.*]*",
- "[Microsoft.Testplatform.*]*",
- "[Microsoft.VisualStudio.TestPlatform.*]*",
- "[MSTest*]*",
- "[testhost*]*"
- ];
+ // Permanent baseline: coverlet assemblies must always be excluded regardless of source.
+ // All other test-framework assemblies are discovered dynamically at runtime via IProcessAssemblyHelper.
+ private static readonly string[] s_baselineExcludeFilters = ["[coverlet.*]*", "[Microsoft.VisualStudio.TestPlatform.*]*", "[testhost*]*"];
private static readonly string[] s_defaultExcludeByAttributes =
[
@@ -39,7 +32,7 @@ internal sealed class CoverageConfiguration
/// Initializes a new instance of CoverageConfiguration using only command-line options.
///
public CoverageConfiguration(ICommandLineOptions commandLineOptions, ILogger? logger = null)
- : this(commandLineOptions, configFileSettings: null, logger)
+ : this(commandLineOptions, configFileSettings: null, testModulePath: null, logger)
{
}
@@ -48,13 +41,20 @@ public CoverageConfiguration(ICommandLineOptions commandLineOptions, ILogger? lo
/// Configuration precedence (highest to lowest):
/// 1. Explicit command-line options
/// 2. Configuration file settings (coverlet.mtp.appsettings.json)
- /// 3. Built-in defaults
+ /// 3. Dynamic defaults derived from the test module's deps.json (only when no config file)
///
- public CoverageConfiguration(ICommandLineOptions commandLineOptions, CoverletMTPSettings? configFileSettings, ILogger? logger = null)
+ public CoverageConfiguration(
+ ICommandLineOptions commandLineOptions,
+ CoverletMTPSettings? configFileSettings,
+ string? testModulePath,
+ ILogger? logger = null,
+ Coverlet.Core.Abstractions.IProcessAssemblyHelper? processAssemblyHelper = null)
{
_commandLineOptions = commandLineOptions;
_configFileSettings = configFileSettings;
+ _testModulePath = testModulePath;
_logger = logger;
+ _processAssemblyHelper = processAssemblyHelper ?? new Coverlet.Core.Helpers.ProcessAssemblyHelper();
}
public bool IsCoverageEnabled =>
@@ -114,23 +114,94 @@ public string[] GetExcludeFilters()
CoverletOptionNames.Exclude,
out string[]? filters))
{
- // Merge explicit exclusions with defaults for CLI convenience
- string[] merged = [.. s_defaultExcludeFilters.Concat(filters).Distinct()];
+ // Merge explicit exclusions with the permanent baseline only — dynamic list is not
+ // applied here because the user is taking explicit control of the filter set.
+ string[] merged = [.. s_baselineExcludeFilters.Concat(filters).Distinct()];
LogOptionValue(CoverletOptionNames.Exclude, merged, isExplicit: true);
return merged;
}
- // Priority 2: Configuration file - authoritative when present
- // Config file filters already include [coverlet.*]* prepended by CoverletMTPSettingsParser
+ // Priority 2: Configuration file - authoritative when present.
+ // Config file filters already include [coverlet.*]* prepended by CoverletMTPSettingsParser.
+ // Dynamic defaults are intentionally skipped when a config file is in use.
if (_configFileSettings?.IsFromConfigFile == true)
{
LogOptionValue(CoverletOptionNames.Exclude, _configFileSettings.ExcludeFilters, isExplicit: false, source: "config file");
return _configFileSettings.ExcludeFilters;
}
- // Priority 3: Built-in defaults - only when no config file
- LogOptionValue(CoverletOptionNames.Exclude, s_defaultExcludeFilters, isExplicit: false);
- return s_defaultExcludeFilters;
+ // Priority 3: Dynamic defaults derived from the assemblies already loaded into this
+ // process. Because only loaded assemblies are inspected, transitive dependencies that
+ // have not yet been resolved are never included in the list.
+ string[] dynamicDefaults = BuildDynamicExcludeFilters();
+ LogOptionValue(CoverletOptionNames.Exclude, dynamicDefaults, isExplicit: false);
+ return dynamicDefaults;
+ }
+
+ ///
+ /// Builds exclude-filter defaults by merging two complementary sources, then combining
+ /// with :
+ ///
+ /// -
+ ///
+ /// deps.json — reads *.deps.json next to the test module and converts
+ /// every non-project RuntimeLibrary entry into a filter pattern. Covers
+ /// test-host infrastructure (e.g. xunit.v3.mtp-v2, testhost,
+ /// Microsoft.TestPlatform.*) that is only loaded inside the test-host process,
+ /// not in the controller process where instrumentation runs.
+ ///
+ ///
+ /// -
+ ///
+ /// AppDomain — enumerates assemblies already loaded into this (controller)
+ /// process. Covers build-extension assemblies such as
+ /// Microsoft.Testing.Extensions.MSBuild that are loaded by MTP during the
+ /// build-driven test run and are therefore held open when instrumentation starts,
+ /// but are not declared as RuntimeLibrary entries in deps.json.
+ ///
+ ///
+ ///
+ ///
+ private string[] BuildDynamicExcludeFilters()
+ {
+ if (string.IsNullOrWhiteSpace(_testModulePath))
+ {
+ return s_baselineExcludeFilters;
+ }
+
+ string simpleTestName = Path.GetFileNameWithoutExtension(_testModulePath);
+ string? moduleDirectory = Path.GetDirectoryName(_testModulePath);
+
+ if (string.IsNullOrWhiteSpace(moduleDirectory))
+ {
+ return s_baselineExcludeFilters;
+ }
+
+ try
+ {
+ // Source 1: runtime package entries from deps.json (test-host-side packages).
+ IReadOnlyList depsNames = _processAssemblyHelper.GetDepsJsonAssemblyNames(moduleDirectory, simpleTestName);
+
+ // Source 2: assemblies already loaded in the controller process (build-extension assemblies
+ // such as Microsoft.Testing.Extensions.MSBuild that are held open before instrumentation).
+ IReadOnlyList loadedNames = _processAssemblyHelper.GetLoadedAssemblyNames(simpleTestName);
+
+ IEnumerable dynamicFilters = depsNames.Concat(loadedNames)
+ .Select(Coverlet.Core.Helpers.ProcessAssemblyHelper.ToExcludeFilter);
+
+ IEnumerable merged = s_baselineExcludeFilters
+ .Concat(dynamicFilters)
+ .Distinct(StringComparer.OrdinalIgnoreCase);
+
+ return [.. Coverlet.Core.Helpers.ProcessAssemblyHelper.PruneRedundantFilters(merged)];
+ }
+ catch (Exception ex)
+ {
+ // Dynamic discovery is best-effort; fall back to the permanent baseline so coverage
+ // collection is never completely broken by an unexpected error.
+ _logger?.LogWarning($"Dynamic assembly discovery failed; falling back to baseline exclude filters. Reason: {ex.Message}");
+ return s_baselineExcludeFilters;
+ }
}
public string[] GetExcludeByFileFilters()
diff --git a/src/coverlet.core/Abstractions/IProcessAssemblyHelper.cs b/src/coverlet.core/Abstractions/IProcessAssemblyHelper.cs
new file mode 100644
index 000000000..1a712c67f
--- /dev/null
+++ b/src/coverlet.core/Abstractions/IProcessAssemblyHelper.cs
@@ -0,0 +1,33 @@
+// Copyright (c) Toni Solarin-Sodara
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+using System.Collections.Generic;
+
+namespace Coverlet.Core.Abstractions
+{
+ ///
+ /// Provides access to assemblies loaded by the current process and to assembly
+ /// names declared in the test module's deps.json, used to build dynamic exclude-filter defaults.
+ ///
+ internal interface IProcessAssemblyHelper
+ {
+ ///
+ /// Returns the simple assembly names (no version, culture, or public key token)
+ /// of assemblies directly loaded into the current process's default ALC,
+ /// excluding the assembly under test itself.
+ /// Transitive/indirect dependencies that are not yet loaded are not returned.
+ ///
+ /// Simple name of the test assembly to exclude from the list.
+ IReadOnlyList GetLoadedAssemblyNames(string testAssemblyName);
+
+ ///
+ /// Returns the simple assembly names of all non-project NuGet package entries
+ /// declared in the *.deps.json files located next to the test module.
+ /// These entries represent test-host infrastructure that is not yet loaded into
+ /// the controller process when is called.
+ ///
+ /// Directory that contains the test module and its deps.json.
+ /// Simple name of the test assembly to exclude from the list.
+ IReadOnlyList GetDepsJsonAssemblyNames(string testModuleDirectory, string testAssemblyName);
+ }
+}
diff --git a/src/coverlet.core/Helpers/ProcessAssemblyHelper.cs b/src/coverlet.core/Helpers/ProcessAssemblyHelper.cs
new file mode 100644
index 000000000..559e6ea49
--- /dev/null
+++ b/src/coverlet.core/Helpers/ProcessAssemblyHelper.cs
@@ -0,0 +1,145 @@
+// Copyright (c) Toni Solarin-Sodara
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Coverlet.Core.Abstractions;
+using Microsoft.Extensions.DependencyModel;
+
+namespace Coverlet.Core.Helpers
+{
+ internal sealed class ProcessAssemblyHelper : IProcessAssemblyHelper
+ {
+ ///
+ public IReadOnlyList GetLoadedAssemblyNames(string testAssemblyName)
+ {
+ if (string.IsNullOrWhiteSpace(testAssemblyName))
+ throw new ArgumentException("Test assembly name must not be null or whitespace.", nameof(testAssemblyName));
+
+ return AppDomain.CurrentDomain
+ .GetAssemblies()
+ .Where(a => !a.IsDynamic && !string.IsNullOrWhiteSpace(a.Location))
+ .Select(a => a.GetName().Name)
+ .Where(name => !string.IsNullOrWhiteSpace(name) &&
+ !name!.Equals(testAssemblyName, StringComparison.OrdinalIgnoreCase))
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToList()!;
+ }
+
+ ///
+ public IReadOnlyList GetDepsJsonAssemblyNames(string testModuleDirectory, string testAssemblyName)
+ {
+ if (string.IsNullOrWhiteSpace(testModuleDirectory))
+ throw new ArgumentException("Test module directory must not be null or whitespace.", nameof(testModuleDirectory));
+
+ if (string.IsNullOrWhiteSpace(testAssemblyName))
+ throw new ArgumentException("Test assembly name must not be null or whitespace.", nameof(testAssemblyName));
+
+ var names = new HashSet(StringComparer.OrdinalIgnoreCase);
+
+ using var reader = new DependencyContextJsonReader();
+ foreach (string depsFile in Directory.EnumerateFiles(testModuleDirectory, "*.deps.json"))
+ {
+ try
+ {
+ using FileStream stream = File.OpenRead(depsFile);
+ DependencyContext context = reader.Read(stream);
+
+ foreach (RuntimeLibrary lib in context.RuntimeLibraries)
+ {
+ // Skip the test project itself; we only want infrastructure packages.
+ if (lib.Type.Equals("project", StringComparison.OrdinalIgnoreCase))
+ continue;
+
+ if (!string.IsNullOrWhiteSpace(lib.Name) &&
+ !lib.Name.Equals(testAssemblyName, StringComparison.OrdinalIgnoreCase))
+ {
+ names.Add(lib.Name);
+ }
+ }
+ }
+ catch (Exception)
+ {
+ // Best-effort; a corrupt or unreadable deps.json is not fatal.
+ }
+ }
+
+ return [.. names];
+ }
+
+ ///
+ /// Converts a simple assembly name to a coverlet exclude-filter pattern.
+ /// For names with three or more dot-separated segments the third segment onwards is
+ /// replaced by a wildcard so the filter is resilient to assembly names that differ
+ /// from the NuGet package name (e.g. dashes vs. dots in the suffix).
+ ///
+ /// - xunit.v3.mtp-v2 → [xunit.v3.*]*
+ /// - Microsoft.Extensions.Configuration.Binder → [Microsoft.Extensions.*]*
+ /// - coverlet.core → [coverlet.core]*
+ /// - xunit → [xunit]*
+ ///
+ ///
+ internal static string ToExcludeFilter(string assemblyName)
+ {
+ int first = assemblyName.IndexOf('.');
+ if (first < 0)
+ return $"[{assemblyName}]*";
+
+ int second = assemblyName.IndexOf('.', first + 1);
+ if (second < 0)
+ return $"[{assemblyName}]*"; // exactly two segments — keep exact
+
+ // Three or more segments: use first two as prefix and wildcard the rest.
+ string prefix = assemblyName.Substring(0, second);
+ return $"[{prefix}.*]*";
+ }
+
+ ///
+ /// Removes exact-name filters from that are already matched
+ /// by a wildcard filter present in the same collection.
+ /// For example [coverlet.core]* is redundant when [coverlet.*]* is present.
+ ///
+ internal static IEnumerable PruneRedundantFilters(IEnumerable filters)
+ {
+ // Collect wildcard filters of the form "[prefix.*]*"
+ var wildcards = new HashSet(
+ filters.Where(f => f.EndsWith(".*]*", StringComparison.Ordinal)),
+ StringComparer.OrdinalIgnoreCase);
+
+ foreach (string filter in filters)
+ {
+ if (!filter.EndsWith(".*]*", StringComparison.Ordinal)
+ && IsExactFilterCoveredByWildcard(filter, wildcards))
+ {
+ continue; // skip — already covered
+ }
+
+ yield return filter;
+ }
+ }
+
+ // Checks whether an exact filter like "[coverlet.core]*" is already matched by
+ // a wildcard like "[coverlet.*]*" in the wildcard set.
+ private static bool IsExactFilterCoveredByWildcard(string filter, HashSet wildcards)
+ {
+ // filter must be of the form "[AssemblyName]*"
+ if (filter.Length < 4 || filter[0] != '[' || !filter.EndsWith("]*", StringComparison.Ordinal))
+ return false;
+
+ string name = filter.Substring(1, filter.Length - 3); // strip "[" and "]*"
+
+ int dotIndex = name.LastIndexOf('.');
+ while (dotIndex > 0)
+ {
+ string candidate = $"[{name.Substring(0, dotIndex)}.*]*";
+ if (wildcards.Contains(candidate))
+ return true;
+ dotIndex = name.LastIndexOf('.', dotIndex - 1);
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs b/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs
new file mode 100644
index 000000000..1188542f3
--- /dev/null
+++ b/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs
@@ -0,0 +1,377 @@
+// Copyright (c) Toni Solarin-Sodara
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+using Coverlet.Core.Abstractions;
+using Coverlet.MTP.CommandLine;
+using Microsoft.Testing.Platform.CommandLine;
+using Moq;
+using Xunit;
+
+namespace Coverlet.MTP.Configuration.Tests;
+
+///
+/// Tests for the dynamic exclude-filter behaviour introduced by IProcessAssemblyHelper injection.
+/// Dynamic defaults are built from the test module's deps.json rather than from controller-process
+/// assemblies, so test-host infrastructure loaded after the controller starts is also excluded.
+///
+public sealed class CoverageConfigurationDynamicExcludeTests
+{
+ // Fake module path used across tests — directory portion must exist conceptually for deps.json look-up.
+ private const string FakeModulePath = "/fake/path/MyTests.dll";
+ // Derived at runtime so the separator always matches what Path.GetDirectoryName produces on the current OS.
+ private static readonly string s_fakeModuleDir = Path.GetDirectoryName(FakeModulePath)!;
+ private const string TestAssemblyName = "MyTests";
+
+ private readonly Mock _mockLogger;
+ private readonly Mock _mockCommandLineOptions;
+ private readonly Mock _mockProcessAssemblyHelper;
+
+ public CoverageConfigurationDynamicExcludeTests()
+ {
+ _mockCommandLineOptions = new Mock();
+ _mockLogger = new Mock();
+ _mockProcessAssemblyHelper = new Mock();
+
+ // Default: no CLI --exclude flag
+ _mockCommandLineOptions
+ .Setup(x => x.TryGetOptionArgumentList(CoverletOptionNames.Exclude, out It.Ref.IsAny))
+#pragma warning disable IDE0350 // Use implicitly typed lambda
+ .Returns(new TryGetOptionArgumentListDelegate((string _, out string[]? v) => { v = null; return false; }));
+#pragma warning restore IDE0350 // Use implicitly typed lambda
+ }
+
+ #region Priority 3: Dynamic defaults from deps.json
+
+ [Fact]
+ public void WhenNoConfigFileThenDepsJsonFiltersApplied()
+ {
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetDepsJsonAssemblyNames(s_fakeModuleDir, TestAssemblyName))
+ .Returns(["xunit.core", "ReportGenerator.Mtp"]);
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetLoadedAssemblyNames(TestAssemblyName))
+ .Returns([]);
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ Assert.Contains("[xunit.core]*", result);
+ Assert.Contains("[ReportGenerator.Mtp]*", result);
+ }
+
+ [Fact]
+ public void WhenNoConfigFileThenBaselineFilterAlwaysPresent()
+ {
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetDepsJsonAssemblyNames(It.IsAny(), It.IsAny()))
+ .Returns(["xunit.core"]);
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetLoadedAssemblyNames(It.IsAny()))
+ .Returns([]);
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ Assert.Contains("[coverlet.*]*", result);
+ }
+
+ [Fact]
+ public void WhenDepsJsonHelperReturnsEmptyListThenBaselineFallbackUsed()
+ {
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetDepsJsonAssemblyNames(It.IsAny(), It.IsAny()))
+ .Returns([]);
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetLoadedAssemblyNames(It.IsAny()))
+ .Returns([]);
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ Assert.Equal(["[coverlet.*]*", "[Microsoft.VisualStudio.TestPlatform.*]*", "[testhost*]*"], result);
+ }
+
+ [Fact]
+ public void WhenDepsJsonHelperThrowsThenBaselineFallbackUsed()
+ {
+ // Throwing from GetDepsJsonAssemblyNames propagates out of the try block,
+ // so GetLoadedAssemblyNames is never reached — no extra stub needed.
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetDepsJsonAssemblyNames(It.IsAny(), It.IsAny()))
+ .Throws(new InvalidOperationException("Simulated deps.json read failure"));
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ Assert.Equal(["[coverlet.*]*", "[Microsoft.VisualStudio.TestPlatform.*]*", "[testhost*]*"], result);
+ }
+
+ [Fact]
+ public void WhenDepsJsonHelperReturnsAssemblyNamesThenFiltersHaveCorrectFormat()
+ {
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetDepsJsonAssemblyNames(s_fakeModuleDir, TestAssemblyName))
+ .Returns(["some.assembly", "another.lib"]);
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetLoadedAssemblyNames(TestAssemblyName))
+ .Returns([]);
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ Assert.Contains("[some.assembly]*", result);
+ Assert.Contains("[another.lib]*", result);
+ }
+
+ [Fact]
+ public void WhenNullTestModulePathThenBaselineOnlyReturned()
+ {
+ // When testModulePath is null the helper must not be called at all
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: null,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ Assert.Equal(["[coverlet.*]*", "[Microsoft.VisualStudio.TestPlatform.*]*", "[testhost*]*"], result);
+ _mockProcessAssemblyHelper.Verify(
+ x => x.GetDepsJsonAssemblyNames(It.IsAny(), It.IsAny()),
+ Times.Never);
+ _mockProcessAssemblyHelper.Verify(
+ x => x.GetLoadedAssemblyNames(It.IsAny()),
+ Times.Never);
+ }
+
+ [Fact]
+ public void WhenDynamicFiltersNoDuplicatesThenResultContainsBaselineOnce()
+ {
+ // A deps.json entry named "coverlet.*" must not duplicate the baseline "[coverlet.*]*" entry
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetDepsJsonAssemblyNames(s_fakeModuleDir, TestAssemblyName))
+ .Returns(["coverlet.core", "xunit.core"]);
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetLoadedAssemblyNames(TestAssemblyName))
+ .Returns([]);
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ // [coverlet.core] maps to [coverlet.core]* (two segments, kept exact),
+ // but it is pruned as redundant because [coverlet.*]* (the baseline) already covers it.
+ // [xunit.core] maps to [xunit.core]* (two segments, kept exact).
+ Assert.Single(result, f => f == "[coverlet.*]*");
+ Assert.DoesNotContain("[coverlet.core]*", result);
+ Assert.Contains("[xunit.core]*", result);
+ }
+
+ [Fact]
+ public void WhenLoadedAssemblyReturnsEntryThenFilterApplied()
+ {
+ // Validates that controller-process assemblies (e.g. build extensions) are also excluded.
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetDepsJsonAssemblyNames(s_fakeModuleDir, TestAssemblyName))
+ .Returns([]);
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetLoadedAssemblyNames(TestAssemblyName))
+ .Returns(["Microsoft.Testing.Extensions.MSBuild"]);
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ // Three-segment name → wildcarded to [Microsoft.Testing.*]*
+ Assert.Contains("[Microsoft.Testing.*]*", result);
+ }
+
+ [Fact]
+ public void WhenBothSourcesReturnEntriesThenAllFiltersApplied()
+ {
+ // Validates the union of deps.json + AppDomain sources.
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetDepsJsonAssemblyNames(s_fakeModuleDir, TestAssemblyName))
+ .Returns(["xunit.v3.core", "testhost"]);
+ _mockProcessAssemblyHelper
+ .Setup(x => x.GetLoadedAssemblyNames(TestAssemblyName))
+ .Returns(["Microsoft.Testing.Extensions.MSBuild"]);
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ // Three-segment names are wildcarded to their two-segment prefix.
+ Assert.Contains("[xunit.v3.*]*", result);
+ Assert.Contains("[testhost]*", result);
+ Assert.Contains("[Microsoft.Testing.*]*", result);
+ }
+
+ #endregion
+
+ #region Priority 2: Config file bypasses dynamic list
+
+ [Fact]
+ public void WhenConfigFilePresentThenDynamicFiltersNotApplied()
+ {
+ var configFileSettings = new CoverletMTPSettings
+ {
+ IsFromConfigFile = true,
+ ExcludeFilters = ["[coverlet.*]*", "[MyApp.Tests]*"]
+ };
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ config.GetExcludeFilters();
+
+ // IProcessAssemblyHelper must NOT be called when a config file governs the filters
+ _mockProcessAssemblyHelper.Verify(
+ x => x.GetDepsJsonAssemblyNames(It.IsAny(), It.IsAny()),
+ Times.Never);
+ _mockProcessAssemblyHelper.Verify(
+ x => x.GetLoadedAssemblyNames(It.IsAny()),
+ Times.Never);
+ }
+
+ [Fact]
+ public void WhenConfigFilePresentThenConfigFileFiltersReturned()
+ {
+ string[] configFilters = ["[coverlet.*]*", "[MyApp.Tests]*"];
+ var configFileSettings = new CoverletMTPSettings
+ {
+ IsFromConfigFile = true,
+ ExcludeFilters = configFilters
+ };
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ Assert.Equal(configFilters, result);
+ }
+
+ #endregion
+
+ #region Priority 1: CLI flag bypasses dynamic list
+
+ [Fact]
+ public void WhenCliExcludeFlagSetThenDepsJsonHelperNotCalled()
+ {
+ string[] cliFilters = ["[MyCustomFilter]*"];
+#pragma warning disable IDE0350 // Use implicitly typed lambda
+ _mockCommandLineOptions
+ .Setup(x => x.TryGetOptionArgumentList(CoverletOptionNames.Exclude, out It.Ref.IsAny))
+ .Returns(new TryGetOptionArgumentListDelegate((string _, out string[]? v) =>
+ {
+ v = cliFilters;
+ return true;
+ }));
+#pragma warning restore IDE0350 // Use implicitly typed lambda
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ config.GetExcludeFilters();
+
+ // Dynamic helper must NOT be called when CLI flag is explicitly set
+ _mockProcessAssemblyHelper.Verify(
+ x => x.GetDepsJsonAssemblyNames(It.IsAny(), It.IsAny()),
+ Times.Never);
+ _mockProcessAssemblyHelper.Verify(
+ x => x.GetLoadedAssemblyNames(It.IsAny()),
+ Times.Never);
+ }
+
+ [Fact]
+ public void WhenCliExcludeFlagSetThenBaselineFilterIsAlwaysPresent()
+ {
+ string[] cliFilters = ["[MyCustomFilter]*"];
+#pragma warning disable IDE0350 // Use implicitly typed lambda
+ _mockCommandLineOptions
+ .Setup(x => x.TryGetOptionArgumentList(CoverletOptionNames.Exclude, out It.Ref.IsAny))
+ .Returns(new TryGetOptionArgumentListDelegate((string _, out string[]? v) =>
+ {
+ v = cliFilters;
+ return true;
+ }));
+#pragma warning restore IDE0350 // Use implicitly typed lambda
+
+ var config = new CoverageConfiguration(
+ _mockCommandLineOptions.Object,
+ configFileSettings: null,
+ testModulePath: FakeModulePath,
+ logger: _mockLogger.Object,
+ processAssemblyHelper: _mockProcessAssemblyHelper.Object);
+
+ string[] result = config.GetExcludeFilters();
+
+ Assert.Contains("[coverlet.*]*", result);
+ Assert.Contains("[MyCustomFilter]*", result);
+ }
+
+ #endregion
+
+ // Helper delegate for Moq setup — must return bool to match TryGetOptionArgumentList signature
+ private delegate bool TryGetOptionArgumentListDelegate(string optionName, out string[]? value);
+}
+
diff --git a/test/coverlet.MTP.tests/Configuration/CoverageConfigurationTests.cs b/test/coverlet.MTP.tests/Configuration/CoverageConfigurationTests.cs
index 1759d5d68..dd2161f9d 100644
--- a/test/coverlet.MTP.tests/Configuration/CoverageConfigurationTests.cs
+++ b/test/coverlet.MTP.tests/Configuration/CoverageConfigurationTests.cs
@@ -227,8 +227,7 @@ public void GetExcludeFiltersWhenOptionSetMergesWithDefaults()
var config = new CoverageConfiguration(_mockCommandLineOptions.Object, _mockLogger.Object);
string[] result = config.GetExcludeFilters();
- Assert.Contains("[xunit.*]*", result);
- Assert.Contains("[Microsoft.Testing.*]*", result);
+ // Baseline filter is always present when CLI flag is used
Assert.Contains("[coverlet.*]*", result);
Assert.Contains("[CustomExclude]*", result);
}
@@ -248,22 +247,16 @@ public void GetExcludeFiltersWhenOptionNotSetReturnsDefaults()
var config = new CoverageConfiguration(_mockCommandLineOptions.Object, _mockLogger.Object);
string[] result = config.GetExcludeFilters();
- Assert.Equal(9, result.Length);
- Assert.Contains("[xunit.*]*", result);
- Assert.Contains("[Microsoft.Testing.*]*", result);
+ // Permanent baseline is always present
Assert.Contains("[coverlet.*]*", result);
- Assert.Contains("[Microsoft.Testplatform.*]*", result);
- Assert.Contains("[Microsoft.VisualStudio.TestPlatform.*]*", result);
- Assert.Contains("[NUnit3.*]*", result);
- Assert.Contains("[nunit.*]*", result);
- Assert.Contains("[MSTest*]*", result);
- Assert.Contains("[testhost*]*", result);
+ // Dynamic discovery adds loaded-process assemblies on top of the baseline
+ Assert.True(result.Length >= 1);
}
[Fact]
public void GetExcludeFiltersRemovesDuplicates()
{
- string[] customFilters = ["[xunit.*]*", "[CustomExclude]*"];
+ string[] customFilters = ["[coverlet.*]*", "[CustomExclude]*"];
#pragma warning disable IDE0350 // Use implicitly typed lambda
_mockCommandLineOptions.Setup(x => x.TryGetOptionArgumentList(CoverletOptionNames.Exclude, out It.Ref.IsAny))
.Returns(new TryGetOptionArgumentListDelegate((string optionName, out string[]? filters) =>
@@ -276,14 +269,15 @@ public void GetExcludeFiltersRemovesDuplicates()
var config = new CoverageConfiguration(_mockCommandLineOptions.Object, _mockLogger.Object);
string[] result = config.GetExcludeFilters();
- Assert.Equal(10, result.Length);
- Assert.Single(result, f => f == "[xunit.*]*");
+ // [coverlet.*]* appears in both the baseline and the custom list; must be deduplicated
+ Assert.Single(result, f => f == "[coverlet.*]*");
+ Assert.Contains("[CustomExclude]*", result);
}
[Fact]
public void GetExcludeFiltersWithMultipleDuplicatesRemovesAllDuplicates()
{
- string[] customFilters = ["[xunit.*]*", "[Microsoft.Testing.*]*", "[CustomExclude]*", "[xunit.*]*"];
+ string[] customFilters = ["[coverlet.*]*", "[MyFilter]*", "[CustomExclude]*", "[coverlet.*]*"];
#pragma warning disable IDE0350 // Use implicitly typed lambda
_mockCommandLineOptions.Setup(x => x.TryGetOptionArgumentList(CoverletOptionNames.Exclude, out It.Ref.IsAny))
.Returns(new TryGetOptionArgumentListDelegate((string optionName, out string[]? filters) =>
@@ -296,9 +290,10 @@ public void GetExcludeFiltersWithMultipleDuplicatesRemovesAllDuplicates()
var config = new CoverageConfiguration(_mockCommandLineOptions.Object, _mockLogger.Object);
string[] result = config.GetExcludeFilters();
- Assert.Equal(10, result.Length); // 9 defaults + 1 custom (all duplicates removed)
- Assert.Single(result, f => f == "[xunit.*]*");
- Assert.Single(result, f => f == "[Microsoft.Testing.*]*");
+ // All duplicates must be removed regardless of how many times they appear
+ Assert.Single(result, f => f == "[coverlet.*]*");
+ Assert.Single(result, f => f == "[MyFilter]*");
+ Assert.Single(result, f => f == "[CustomExclude]*");
}
#endregion
diff --git a/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs b/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs
new file mode 100644
index 000000000..345bed376
--- /dev/null
+++ b/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs
@@ -0,0 +1,120 @@
+// Copyright (c) Toni Solarin-Sodara
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+using System;
+using System.Collections.Generic;
+using Coverlet.Core.Helpers;
+using Xunit;
+
+namespace Coverlet.Core.Tests.Helpers
+{
+ public class ProcessAssemblyHelperTests
+ {
+ private readonly ProcessAssemblyHelper _sut = new();
+
+ [Fact]
+ public void WhenGetLoadedAssemblyNamesThenReturnsNonEmptyList()
+ {
+ IReadOnlyList result = _sut.GetLoadedAssemblyNames("SomeOtherAssembly");
+
+ Assert.NotEmpty(result);
+ }
+
+ [Fact]
+ public void WhenGetLoadedAssemblyNamesThenExcludesTestAssembly()
+ {
+ string testAssemblyName = "coverlet.core.tests";
+
+ IReadOnlyList result = _sut.GetLoadedAssemblyNames(testAssemblyName);
+
+ Assert.DoesNotContain(testAssemblyName, result, StringComparer.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void WhenGetLoadedAssemblyNamesThenExcludesTestAssemblyCaseInsensitive()
+ {
+ IReadOnlyList result = _sut.GetLoadedAssemblyNames("COVERLET.CORE.TESTS");
+
+ Assert.DoesNotContain("coverlet.core.tests", result, StringComparer.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void WhenGetLoadedAssemblyNamesThenNoDuplicates()
+ {
+ IReadOnlyList result = _sut.GetLoadedAssemblyNames("SomeOtherAssembly");
+
+ var unique = new HashSet(result, StringComparer.OrdinalIgnoreCase);
+ Assert.Equal(unique.Count, result.Count);
+ }
+
+ [Fact]
+ public void WhenGetLoadedAssemblyNamesThenAllNamesAreNonEmpty()
+ {
+ IReadOnlyList result = _sut.GetLoadedAssemblyNames("SomeOtherAssembly");
+
+ Assert.All(result, name => Assert.False(string.IsNullOrWhiteSpace(name)));
+ }
+
+ [Fact]
+ public void WhenGetLoadedAssemblyNamesWithEmptyStringThenThrowsArgumentException()
+ {
+ Assert.Throws(() => _sut.GetLoadedAssemblyNames(string.Empty));
+ }
+
+ [Fact]
+ public void WhenGetLoadedAssemblyNamesWithWhitespaceThenThrowsArgumentException()
+ {
+ Assert.Throws(() => _sut.GetLoadedAssemblyNames(" "));
+ }
+
+ [Theory]
+ // Single segment — exact
+ [InlineData("xunit", "[xunit]*")]
+ // Two segments — exact
+ [InlineData("ReportGenerator.Mtp", "[ReportGenerator.Mtp]*")]
+ // Two segments — exact
+ [InlineData("coverlet.core", "[coverlet.core]*")]
+ // Three segments — wildcard from third onwards
+ [InlineData("xunit.v3.mtp-v2", "[xunit.v3.*]*")]
+ [InlineData("xunit.runner.utility", "[xunit.runner.*]*")]
+ [InlineData("Microsoft.Testing.Platform", "[Microsoft.Testing.*]*")]
+ // Four segments — still uses first-two-segment prefix
+ [InlineData("Microsoft.Extensions.Configuration.Binder", "[Microsoft.Extensions.*]*")]
+ public void WhenToExcludeFilterThenReturnsCorrectPattern(string assemblyName, string expectedFilter)
+ {
+ string result = ProcessAssemblyHelper.ToExcludeFilter(assemblyName);
+
+ Assert.Equal(expectedFilter, result);
+ }
+
+ [Theory]
+ // An exact filter that is already covered by a wildcard should be pruned.
+ [InlineData(new[] { "[coverlet.*]*", "[coverlet.core]*" }, new[] { "[coverlet.*]*" })]
+ // A wildcard is not pruned by itself.
+ [InlineData(new[] { "[coverlet.*]*" }, new[] { "[coverlet.*]*" })]
+ // An exact filter not covered by any wildcard is kept.
+ [InlineData(new[] { "[coverlet.*]*", "[Serilog]*" }, new[] { "[coverlet.*]*", "[Serilog]*" })]
+ // Deeper exact filter covered by parent wildcard.
+ [InlineData(new[] { "[Microsoft.Extensions.*]*", "[Microsoft.Extensions.Logging]*" }, new[] { "[Microsoft.Extensions.*]*" })]
+ // Exact filter where no matching wildcard exists is kept.
+ [InlineData(new[] { "[xunit.v3.*]*", "[System.Runtime]*" }, new[] { "[xunit.v3.*]*", "[System.Runtime]*" })]
+ public void WhenPruneRedundantFiltersThenRemovesExactFiltersCoveredByWildcard(string[] input, string[] expected)
+ {
+ IEnumerable result = ProcessAssemblyHelper.PruneRedundantFilters(input);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Fact]
+ public void WhenGetLoadedAssemblyNamesThenContainsKnownAssembly()
+ {
+ // Derive the expected name from a type that is definitely in the test process,
+ // so this test stays valid if the xUnit package or assembly name ever changes.
+ string expectedAssemblyName = typeof(FactAttribute).Assembly.GetName().Name!;
+
+ IReadOnlyList result = _sut.GetLoadedAssemblyNames("SomeOtherAssembly");
+
+ Assert.Contains(expectedAssemblyName, result, StringComparer.OrdinalIgnoreCase);
+ }
+ }
+}