diff --git a/benchmarks/E128.Benchmarks/PackageAnalyzerBenchmarks.cs b/benchmarks/E128.Benchmarks/PackageAnalyzerBenchmarks.cs
new file mode 100644
index 0000000..d3f59cc
--- /dev/null
+++ b/benchmarks/E128.Benchmarks/PackageAnalyzerBenchmarks.cs
@@ -0,0 +1,150 @@
+using System;
+using System.Collections.Immutable;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using BenchmarkDotNet.Attributes;
+using E128.Analyzers.Design;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.Diagnostics;
+
+namespace E128.Benchmarks;
+
+///
+/// Starter benchmark for the consumer critical path of the E128.Analyzers package: every analyzer in the
+/// package runs over one ordinary service-style compilation, as it does in a consumer build. The compilation
+/// references the whole shared framework and is built once, so the number shows warm analyzer cost, not
+/// first-compile cost. The code fixers are not measured here.
+/// BenchmarkDotNet requires an unsealed class, so this class is not sealed.
+///
+[MemoryDiagnoser]
+public class PackageAnalyzerBenchmarks
+{
+ private const string Source = """
+ using System;
+ using System.Collections.Generic;
+ using System.IO;
+ using System.Linq;
+ using System.Net.Http;
+ using System.Text;
+ using System.Threading;
+ using System.Threading.Tasks;
+
+ namespace Sample;
+
+ public sealed record Order(int Id, string Customer, decimal Total, DateTime CreatedAt);
+
+ public interface IOrderStore
+ {
+ Task> LoadAsync(CancellationToken cancellationToken);
+ }
+
+ public sealed class OrderReport
+ {
+ private readonly IOrderStore _store;
+ private readonly HttpClient _client;
+
+ public OrderReport(IOrderStore store, HttpClient client)
+ {
+ _store = store;
+ _client = client;
+ }
+
+ public async Task BuildAsync(string path, CancellationToken cancellationToken)
+ {
+ var orders = await _store.LoadAsync(cancellationToken).ConfigureAwait(false);
+ var builder = new StringBuilder();
+ foreach (var group in orders.GroupBy(order => order.Customer))
+ {
+ var total = group.Sum(order => order.Total);
+ builder.Append(group.Key + ": " + total);
+ builder.AppendLine();
+ }
+
+ var status = await _client.GetStringAsync(new Uri("https://example.com/status"), cancellationToken)
+ .ConfigureAwait(false);
+ if (status == "down" || status == "maintenance" || status == "degraded")
+ {
+ return string.Empty;
+ }
+
+ var text = builder.ToString();
+ await File.WriteAllTextAsync(path, text, cancellationToken).ConfigureAwait(false);
+ return File.ReadAllText(path);
+ }
+
+ public static Order? Latest(List orders)
+ {
+ return orders.OrderByDescending(order => order.CreatedAt).FirstOrDefault();
+ }
+
+ public static DateTime ParseDate(string value)
+ {
+ return DateTime.Parse(value);
+ }
+ }
+ """;
+
+ private readonly CSharpCompilation _compilation = CreateCompilation();
+
+ private readonly ImmutableArray _analyzers =
+ [
+ .. typeof(ExcessiveInheritanceAnalyzer).Assembly.GetTypes()
+ .Where(static type => !type.IsAbstract
+ && typeof(DiagnosticAnalyzer).IsAssignableFrom(type)
+ && Attribute.IsDefined(type, typeof(DiagnosticAnalyzerAttribute), inherit: false))
+ .Select(static type => (DiagnosticAnalyzer)(Activator.CreateInstance(type)
+ ?? throw new InvalidOperationException($"Cannot create analyzer {type.FullName}.")))
+ ];
+
+ [GlobalSetup]
+ public async Task VerifyPackageReportsAsync()
+ {
+ // An empty analyzer set or a run that reports nothing times only the cheap path. Fail fast instead.
+ if (_analyzers.IsEmpty)
+ {
+ throw new InvalidOperationException("No analyzer was found in the E128.Analyzers assembly.");
+ }
+
+ var diagnostics = await AllPackageAnalyzersAsync().ConfigureAwait(false);
+ if (!diagnostics.IsEmpty)
+ {
+ return;
+ }
+
+ throw new InvalidOperationException("The package analyzers reported no diagnostic for the sample source.");
+ }
+
+ [Benchmark]
+ public Task> AllPackageAnalyzersAsync()
+ {
+ return _compilation
+ .WithAnalyzers(_analyzers)
+ .GetAnalyzerDiagnosticsAsync(CancellationToken.None);
+ }
+
+ private static CSharpCompilation CreateCompilation()
+ {
+ var platformAssemblies = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string
+ ?? throw new InvalidOperationException("The trusted platform assembly list is unavailable.");
+
+ var references = platformAssemblies
+ .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
+ .Select(static path => MetadataReference.CreateFromFile(path));
+
+ var compilation = CSharpCompilation.Create(
+ "PackageBenchmarkSample",
+ [CSharpSyntaxTree.ParseText(Source, cancellationToken: CancellationToken.None)],
+ references,
+ new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable));
+
+ var errors = compilation.GetDiagnostics(CancellationToken.None)
+ .Where(static diagnostic => diagnostic.Severity is DiagnosticSeverity.Error);
+
+ return errors.Any()
+ ? throw new InvalidOperationException("The sample source does not compile.")
+ : compilation;
+ }
+}
diff --git a/lode/dotnet/analyzers/testing.md b/lode/dotnet/analyzers/testing.md
index a9b581f..7767a88 100644
--- a/lode/dotnet/analyzers/testing.md
+++ b/lode/dotnet/analyzers/testing.md
@@ -1,6 +1,6 @@
# Analyzer Testing
-*Updated: 2026-11-16T20:16:49Z*
+*Updated: 2026-11-16T22:58:37Z*
How a test drives an analyzer and a code fix. The harness types live in
`Microsoft.CodeAnalysis.CSharp.Testing`. The repo wrapper lives in
@@ -157,7 +157,7 @@ instead.
The NuGet package `E128.Analyzers` carries two assemblies: `E128.Analyzers` and
`E128.Analyzers.CodeFixers`. Add their branch totals to get the package surface.
-As of 2026-11-16, that surface covers about 87 percent of its branches. See
+As of 2026-11-16T22:58:32Z, that surface covers about 91 percent of its branches. See
[Code Coverage](../code-coverage.md) for collection and the CI floors.
## Related
diff --git a/lode/dotnet/benchmarks.md b/lode/dotnet/benchmarks.md
index ff96335..f3ba9fe 100644
--- a/lode/dotnet/benchmarks.md
+++ b/lode/dotnet/benchmarks.md
@@ -1,15 +1,16 @@
# Benchmarks
-*Updated: 2026-11-09T21:51:08Z*
+*Updated: 2026-11-16T21:48:36Z*
## Overview
`benchmarks/E128.Benchmarks` is an executable project that holds BenchmarkDotNet starter benchmarks. A human must review the cases. They cover the public surface, not a measured hot path. The solution file lists the project in its `/benchmarks/` folder.
-| Class | Subject |
-| ----------------------- | -------------------------------------------------------------------------- |
-| `CoreBenchmarks` | `Greeter`, `GreetingService`, and `InMemoryGreetingRepository` |
-| `WebEndpointBenchmarks` | `GET /`, `POST /greetings`, and `GET /greetings` of the Web project |
-| `AnalyzerBenchmarks` | Three E128 analyzers, each alone and together, over one sample compilation |
+| Class | Subject |
+| --------------------------- | -------------------------------------------------------------------------- |
+| `CoreBenchmarks` | `Greeter`, `GreetingService`, and `InMemoryGreetingRepository` |
+| `WebEndpointBenchmarks` | `GET /`, `POST /greetings`, and `GET /greetings` of the Web project |
+| `AnalyzerBenchmarks` | Three E128 analyzers, each alone and together, over one sample compilation |
+| `PackageAnalyzerBenchmarks` | Every analyzer in the `E128.Analyzers` assembly over one sample service |
Each class uses `[MemoryDiagnoser]`. The packages are in [dep-map.md](../dotnet-reference/dep-map.md).
@@ -17,12 +18,14 @@ Each class uses `[MemoryDiagnoser]`. The packages are in [dep-map.md](../dotnet-
- BenchmarkDotNet rejects a sealed benchmark class. Each class is public and unsealed. A doc comment on the class states this.
- E128005 skips a class whose base type is `object`. `SealedClassTests` loads only the Core assembly. Neither gate covers this project. See [architecture-testing.md](architecture-testing.md).
-- `benchmarks/.globalconfig` sets CA1515 to `none` at `global_level = 101`. BenchmarkDotNet needs public types. See [analyzers.md](analyzers.md).
+- `benchmarks/.globalconfig` sets CA1515 to `none` at `global_level = 101`. BenchmarkDotNet needs public types. It also sets E128227 to `none` for the fixed in-process response. See [analyzers.md](analyzers.md).
- `EntryPoint` replaces a top-level `Program`. The Web project exposes `Program` through `InternalsVisibleTo`, and a second `Program` causes CS0436.
- `EntryPoint.Main` sets the working directory to `AppContext.BaseDirectory`. `WebApplicationFactory` reads `MvcTestingAppManifest.json` from the working directory. A relative path in a command-line argument resolves against that folder, so pass absolute paths.
- `EntryPoint.Main` adds `InProcessEmitToolchain` to the default config, so the benchmarks run in the host process. JIT and tiering state carries over between cases.
- `WebEndpointBenchmarks` runs the app behind the test server. The numbers exclude the network and the Kestrel socket layer. A `FixedGreetingRepository` replaces the in-memory repository, so stored state stays constant and the numbers do not drift. The repository cost is not measured.
- `AnalyzerBenchmarks` builds the sample compilation once, so the numbers show warm analyzer cost. It throws when the sample has a compile error. `GlobalSetup` throws when an analyzer reports no diagnostic.
+- `PackageAnalyzerBenchmarks` measures the consumer build path. It finds each `[DiagnosticAnalyzer]` type in the analyzer assembly by reflection, so a new rule joins the run without an edit.
+- `PackageAnalyzerBenchmarks` references every trusted platform assembly of the host runtime. `GlobalSetup` throws when it finds no analyzer or the run reports no diagnostic. The code fixers are not measured.
- `CoreBenchmarks` uses a `FixedGreetingRepository` with no greetings for the save benchmark, and a seeded in-memory repository for the read benchmark.
## Running
diff --git a/tests/E128.Analyzers.Tests/AggressiveOptimizationCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/AggressiveOptimizationCodeFixProviderBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..34bb68f
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/AggressiveOptimizationCodeFixProviderBranchCoverageMoreTests.cs
@@ -0,0 +1,103 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class AggressiveOptimizationCodeFixProviderBranchCoverageMoreTests
+{
+ private static Task VerifyFixAsync(string source, string fixedCode)
+ {
+ return CodeFixTestRunner.RunAsync(source, fixedCode);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_KeepsBothRemainingOptionsOfANestedCombination()
+ {
+ return VerifyFixAsync(
+ """
+ using System.Runtime.CompilerServices;
+ class C
+ {
+ [{|E128116:MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)|}]
+ void M()
+ {
+ }
+ }
+ """,
+ """
+ using System.Runtime.CompilerServices;
+ class C
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.NoInlining)]
+ void M()
+ {
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_DropsAnArgumentThatHoldsOnlyTheOptionTwice()
+ {
+ return VerifyFixAsync(
+ """
+ using System.Runtime.CompilerServices;
+ class C
+ {
+ [{|E128116:MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveOptimization, MethodCodeType = MethodCodeType.Native)|}]
+ void M()
+ {
+ }
+ }
+ """,
+ """
+ using System.Runtime.CompilerServices;
+ class C
+ {
+ [MethodImpl(MethodCodeType = MethodCodeType.Native)]
+ void M()
+ {
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_RemovesTheAttributeListOfALocalFunction()
+ {
+ return VerifyFixAsync(
+ """
+ using System.Runtime.CompilerServices;
+ class C
+ {
+ void M()
+ {
+ [{|E128116:MethodImpl(MethodImplOptions.AggressiveOptimization)|}]
+ void Local()
+ {
+ }
+
+ Local();
+ }
+ }
+ """,
+ """
+ using System.Runtime.CompilerServices;
+ class C
+ {
+ void M()
+ {
+ void Local()
+ {
+ }
+
+ Local();
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/AlternateLookupAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/AlternateLookupAnalyzerBranchCoverageGapTests.cs
new file mode 100644
index 0000000..b13bb1b
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/AlternateLookupAnalyzerBranchCoverageGapTests.cs
@@ -0,0 +1,156 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class AlternateLookupAnalyzerBranchCoverageGapTests
+{
+ private static Task VerifyAsync(string members)
+ {
+ var code = "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\n"
+ + "class C\n{\n"
+ + members
+ + "}\n";
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheReceiverIsAnArray()
+ {
+ return VerifyAsync("""
+ bool Has(string[] names, ReadOnlySpan key)
+ {
+ var local = names;
+ return local.Contains(new string(key));
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheKeyIsAnotherTypeWithAStringConversion()
+ {
+ return VerifyAsync("""
+ private readonly Dictionary _cache = new();
+
+ int Lookup(ReadOnlySpan key)
+ {
+ return _cache[new Wrapper(key)];
+ }
+
+ int LookupWithoutArguments()
+ {
+ return _cache[new Wrapper { }];
+ }
+
+ sealed class Wrapper
+ {
+ public Wrapper()
+ {
+ }
+
+ public Wrapper(ReadOnlySpan text)
+ {
+ }
+
+ public static implicit operator string(Wrapper wrapper) => string.Empty;
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheLocalIsNotDeclaredByAVariableDeclarator()
+ {
+ return VerifyAsync("""
+ int Lookup(List> caches, ReadOnlySpan key)
+ {
+ var total = 0;
+ foreach (var cache in caches)
+ {
+ total += cache[new string(key)];
+ }
+
+ return total;
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheInitializerHasNoArgumentList()
+ {
+ return VerifyAsync("""
+ int Lookup(ReadOnlySpan key)
+ {
+ var cache = new Dictionary { ["a"] = 1 };
+ return cache[{|E128133:new string(key)|}];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheComparerIsAnotherPropertyOrType()
+ {
+ return VerifyAsync("""
+ int WithObjectComparer(ReadOnlySpan key)
+ {
+ var cache = new Dictionary(EqualityComparer.Default);
+ return cache[new string(key)];
+ }
+
+ int WithInstanceProperty(ReadOnlySpan key)
+ {
+ var cache = new Dictionary(Custom.Instance);
+ return cache[new string(key)];
+ }
+
+ int WithNonGenericDefault(ReadOnlySpan key)
+ {
+ var cache = new Dictionary(Plain.Default);
+ return cache[new string(key)];
+ }
+
+ int WithGenericDefault(ReadOnlySpan key)
+ {
+ var cache = new Dictionary(Generic.Default);
+ return cache[new string(key)];
+ }
+
+ sealed class Custom : IEqualityComparer
+ {
+ public static Custom Instance { get; } = new();
+
+ public bool Equals(string? x, string? y) => string.Equals(x, y, StringComparison.Ordinal);
+
+ public int GetHashCode(string obj) => obj.Length;
+ }
+
+ sealed class Plain : IEqualityComparer
+ {
+ public static Plain Default { get; } = new();
+
+ public bool Equals(string? x, string? y) => string.Equals(x, y, StringComparison.Ordinal);
+
+ public int GetHashCode(string obj) => obj.Length;
+ }
+
+ sealed class Generic : IEqualityComparer
+ {
+ public static Generic Default { get; } = new();
+
+ public bool Equals(string? x, string? y) => string.Equals(x, y, StringComparison.Ordinal);
+
+ public int GetHashCode(string obj) => obj.Length;
+ }
+
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/AlternateLookupCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/AlternateLookupCodeFixProviderBranchCoverageGapTests.cs
new file mode 100644
index 0000000..4649b18
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/AlternateLookupCodeFixProviderBranchCoverageGapTests.cs
@@ -0,0 +1,43 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class AlternateLookupCodeFixProviderBranchCoverageGapTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_KeepsTheRemainingArgumentsOfAnInvocation()
+ {
+ return CodeFixTestRunner.RunAsync(
+ """
+ using System;
+ using System.Collections.Generic;
+
+ class C
+ {
+ private readonly Dictionary _cache = new();
+
+ bool Add(ReadOnlySpan key)
+ {
+ return _cache.TryAdd({|E128133:new string(key)|}, 1);
+ }
+ }
+ """,
+ """
+ using System;
+ using System.Collections.Generic;
+
+ class C
+ {
+ private readonly Dictionary _cache = new();
+
+ bool Add(ReadOnlySpan key)
+ {
+ return _cache.GetAlternateLookup>().TryAdd(key, 1);
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/AppSettingsKeyReaderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/AppSettingsKeyReaderBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..b6589c2
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/AppSettingsKeyReaderBranchCoverageMoreTests.cs
@@ -0,0 +1,92 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class AppSettingsKeyReaderBranchCoverageMoreTests
+{
+ private static string Member(string value)
+ {
+ return "{ \"Known\": " + value + " }";
+ }
+
+ private static Task VerifyAsync(string json, string read)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ $$"""
+ using Microsoft.Extensions.Configuration;
+ class C
+ {
+ string? M(IConfiguration configuration) => {{read}};
+ }
+ namespace Microsoft.Extensions.Configuration
+ {
+ public interface IConfiguration
+ {
+ string? this[string key] { get; set; }
+ }
+ }
+ """,
+ options: new AnalyzerTestOptions { AdditionalFiles = [("appsettings.json", json)] });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnObjectMemberLacksACommaSeparator()
+ {
+ return VerifyAsync(Member("1 \"Other\": 2"), "configuration[\"Missing\"]");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAStringHoldsARawControlCharacter()
+ {
+ return VerifyAsync(Member("\"a\tb\""), "configuration[\"Missing\"]");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheTextEndsAfterABackslash()
+ {
+ return VerifyAsync("{ \"Known\": \"\\", "configuration[\"Missing\"]");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAUnicodeEscapeRunsPastTheEndOfTheText()
+ {
+ return VerifyAsync("{ \"Known\": \"\\u12", "configuration[\"Missing\"]");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenALiteralRunsToTheEndOfTheText()
+ {
+ return VerifyAsync("[ 1", "configuration[\"Missing\"]");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task ReportsMissingKey_WhenAFractionEndsTheNumberToken()
+ {
+ return VerifyAsync(Member("1.5"), "{|E128195:configuration[\"Missing\"]|}");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task ReportsMissingKey_WhenALineCommentEndsTheText()
+ {
+ return VerifyAsync(Member("1") + " // trailing", "{|E128195:configuration[\"Missing\"]|}");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public async Task Silent_WhenAStringEscapeIsUnknown()
+ {
+ foreach (var escape in new[] { "\\!", "\\0", "\\a", "\\z", "\\~" })
+ {
+ await VerifyAsync(Member("\"" + escape + "\""), "configuration[\"Missing\"]");
+ }
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ArgumentTokenizerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/ArgumentTokenizerBranchCoverageGapTests.cs
new file mode 100644
index 0000000..fd7a20a
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ArgumentTokenizerBranchCoverageGapTests.cs
@@ -0,0 +1,28 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ArgumentTokenizerBranchCoverageGapTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task NoFix_WhenTheArgumentsValueIsANullLiteral()
+ {
+ return CodeFixTestRunner.NoFixAsync(
+ """
+ using System.Diagnostics;
+ class C
+ {
+ void M()
+ {
+ var startInfo = new ProcessStartInfo
+ {
+ {|E128091:Arguments = null|}
+ };
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..9eedef7
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,114 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ArrayPoolSqliteParameterSizeAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyLenientAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ code,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAddWithValueCallDoesNotResolve()
+ {
+ return VerifyLenientAsync("""
+ using System.Buffers;
+ class C
+ {
+ void M(Missing cmd)
+ {
+ var buffer = ArrayPool.Shared.Rent(8);
+ cmd.AddWithValue("@p", buffer);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheValueTargetIsAField()
+ {
+ return VerifyLenientAsync("""
+ using System.Buffers;
+ class FieldHolder { public object Value; }
+ class C
+ {
+ void M(FieldHolder holder)
+ {
+ var buffer = ArrayPool.Shared.Rent(8);
+ holder.Value = buffer;
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheBufferInitializerCallDoesNotResolve()
+ {
+ return VerifyLenientAsync("""
+ using Microsoft.Data.Sqlite;
+ namespace Microsoft.Data.Sqlite
+ {
+ public class SqliteParameterCollection
+ {
+ public void AddWithValue(string name, object value) { }
+ }
+ }
+ class C
+ {
+ void M(SqliteParameterCollection parameters)
+ {
+ byte[] buffer = Missing.Rent(8);
+ parameters.AddWithValue("@p", buffer);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheResultIsAssignedToAMemberInsteadOfALocal()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Buffers;
+ class SqliteParameter { public object Value { get; set; } public int Size { get; set; } }
+ class SqliteParameterCollection { public SqliteParameter AddWithValue(string name, object value) => new SqliteParameter(); }
+ class Holder { public SqliteParameter Slot; }
+ class C
+ {
+ void M(SqliteParameterCollection parameters, Holder holder)
+ {
+ var buffer = ArrayPool.Shared.Rent(8);
+ holder.Slot = {|E128086:parameters.AddWithValue("@p", buffer)|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheStatementSitsOutsideAnyBlock()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Buffers;
+ var parameters = new SqliteParameterCollection();
+ var buffer = ArrayPool.Shared.Rent(8);
+ var parameter = {|E128086:parameters.AddWithValue("@p", buffer)|};
+ parameter.Size = 8;
+
+ class SqliteParameter { public object Value { get; set; } public int Size { get; set; } }
+ class SqliteParameterCollection { public SqliteParameter AddWithValue(string name, object value) => new SqliteParameter(); }
+ """,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeCodeFixProviderBranchCoverageGapTests.cs
new file mode 100644
index 0000000..a968995
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeCodeFixProviderBranchCoverageGapTests.cs
@@ -0,0 +1,31 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ArrayPoolSqliteParameterSizeCodeFixProviderBranchCoverageGapTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task NoFix_WhenTheValueAssignmentUsesAComputedLength()
+ {
+ return CodeFixTestRunner.NoFixAsync(
+ """
+ using System.Buffers;
+ using Microsoft.Data.Sqlite;
+ namespace Microsoft.Data.Sqlite
+ {
+ public class SqliteParameter { public object Value { get; set; } public int Size { get; set; } }
+ }
+ class C
+ {
+ void M(SqliteParameter parameter, int size)
+ {
+ var buffer = ArrayPool.Shared.Rent(size * 2);
+ {|E128086:parameter.Value = buffer|};
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/AsyncEnumerableConsumedTwiceAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/AsyncEnumerableConsumedTwiceAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..0bdce33
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/AsyncEnumerableConsumedTwiceAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,63 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class AsyncEnumerableConsumedTwiceAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheTargetFrameworkHasNoAsyncEnumerable()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Collections.Generic;
+ class C
+ {
+ void M(List source)
+ {
+ foreach (var first in source)
+ {
+ }
+
+ foreach (var second in source)
+ {
+ }
+ }
+ }
+ """,
+ options: new AnalyzerTestOptions { References = ReferenceAssemblies.NetStandard.NetStandard20 });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForACallWithOneArgumentThatIsNotAWrapper()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+
+ class Factory
+ {
+ public IAsyncEnumerable Create(int count) => throw new NotSupportedException();
+ }
+
+ class C
+ {
+ async Task M(Factory factory)
+ {
+ await foreach (var first in factory.Create(1))
+ {
+ }
+
+ await foreach (var second in factory.Create(1))
+ {
+ }
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/CaptiveDependencyBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/CaptiveDependencyBranchCoverageGapTests.cs
new file mode 100644
index 0000000..563e819
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/CaptiveDependencyBranchCoverageGapTests.cs
@@ -0,0 +1,490 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.CSharp.Testing;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class CaptiveDependencyBranchCoverageGapTests
+{
+ private static readonly ReferenceAssemblies Net100WithDi = ReferenceAssemblies.Net.Net100
+ .AddPackages([
+ new PackageIdentity("Microsoft.Extensions.DependencyInjection", "10.0.14")
+ ]);
+
+ private static readonly ReferenceAssemblies Net100WithEfCore = ReferenceAssemblies.Net.Net100
+ .AddPackages([
+ new PackageIdentity("Microsoft.Extensions.DependencyInjection", "10.0.14"),
+ new PackageIdentity("Microsoft.EntityFrameworkCore", "10.0.14")
+ ]);
+
+ private static Task VerifyAsync(ReferenceAssemblies references, string code)
+ {
+ // Two descriptors share the E128154 id, so markup names the first one.
+ var test = new CSharpAnalyzerTest
+ {
+ TestCode = code,
+ ReferenceAssemblies = references,
+ MarkupOptions = MarkupOptions.UseFirstDescriptor
+ };
+
+ return test.RunAsync(TestContext.Current.CancellationToken);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForARegistrationCallThatDoesNotBind()
+ {
+ return VerifyAsync(ReferenceAssemblies.Net.Net100, """
+ interface IServiceCollection { }
+ class Repository { }
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.{|CS1061:AddScoped|}();
+ services.{|CS1061:AddSingleton|}();
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForSingletonTypeArgumentsThatAreNotNamedTypes()
+ {
+ return VerifyAsync(Net100WithEfCore, """
+ using Microsoft.Extensions.DependencyInjection;
+ class Repository { }
+ class Startup
+ {
+ void Configure(IServiceCollection services) where T : class
+ {
+ services.AddSingleton();
+ services.AddSingleton();
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForAContextHelperWhoseTypeofArgumentIsNotAContext()
+ {
+ return VerifyAsync(Net100WithEfCore, """
+ using System;
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+ class StoreContext : DbContext { }
+ static class Helpers
+ {
+ public static IServiceCollection AddDbContext(
+ this IServiceCollection services,
+ Type contextType,
+ ServiceLifetime contextLifetime) => services;
+ }
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddDbContext(typeof(string), ServiceLifetime.Singleton);
+ services.AddDbContext(typeof(StoreContext), ServiceLifetime.Scoped);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForAContextHelperWhoseTypeArgumentsAreNotContexts()
+ {
+ return VerifyAsync(Net100WithEfCore, """
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+ class StoreContext : DbContext { }
+ static class Helpers
+ {
+ public static IServiceCollection AddDbContext(
+ this IServiceCollection services,
+ ServiceLifetime contextLifetime) => services;
+ }
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddDbContext(ServiceLifetime.Singleton);
+ services.AddDbContext(ServiceLifetime.Singleton);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_OnTheServiceTypeWhenTheContextIsTheImplementation()
+ {
+ return VerifyAsync(Net100WithEfCore, """
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+ interface IStoreContext { }
+ class StoreContext : DbContext, IStoreContext { }
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddDbContext<{|E128154:IStoreContext|}, StoreContext>(options => { }, ServiceLifetime.Singleton);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_OnTheCallWhenTheContextTypeIsInferred()
+ {
+ return VerifyAsync(Net100WithEfCore, """
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+ class StoreContext : DbContext { }
+ static class Helpers
+ {
+ public static IServiceCollection AddDbContext(
+ this IServiceCollection services,
+ T instance,
+ ServiceLifetime contextLifetime) => services;
+ }
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ {|E128154:services.AddDbContext(new StoreContext(), ServiceLifetime.Singleton)|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheContextLifetimeIsAConvertedConstant()
+ {
+ return VerifyAsync(Net100WithEfCore, """
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+ class StoreContext : DbContext { }
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddDbContext<{|E128154:StoreContext|}>(options => { }, (ServiceLifetime)0);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_OnTheCallWhenTheSingletonTypeComesFromAServiceKey()
+ {
+ return VerifyAsync(Net100WithDi, """
+ using Microsoft.Extensions.DependencyInjection;
+ class Repository { }
+ class Worker
+ {
+ public Worker() { }
+ public Worker(Repository repository) { }
+ }
+ static class Helpers
+ {
+ public static IServiceCollection AddSingleton(this IServiceCollection services, T serviceKey)
+ where T : class => services;
+ }
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddScoped();
+ {|E128154:services.AddSingleton(new Worker())|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForSingletonHelpersWithoutOneOrTwoTypeArguments()
+ {
+ return VerifyAsync(Net100WithDi, """
+ using Microsoft.Extensions.DependencyInjection;
+ class Repository { }
+ class Worker { public Worker(Repository repository) { } }
+ static class Helpers
+ {
+ public static IServiceCollection AddSingleton(this IServiceCollection services) => services;
+
+ public static IServiceCollection AddSingleton(this IServiceCollection services) => services;
+ }
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddScoped();
+ services.AddSingleton();
+ services.AddSingleton();
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_ForAContextRegistrationWhenOnlyTheServiceCollectionTypeIsAvailable()
+ {
+ return VerifyAsync(ReferenceAssemblies.Net.Net100, """
+ namespace Microsoft.EntityFrameworkCore
+ {
+ public class DbContext { }
+ }
+
+ namespace Microsoft.Extensions.DependencyInjection
+ {
+ public enum ServiceLifetime { Singleton, Scoped, Transient }
+
+ public interface IServiceCollection { }
+ }
+
+ namespace App
+ {
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+
+ class StoreContext : DbContext { }
+
+ static class Helpers
+ {
+ public static IServiceCollection AddDbContext(
+ this IServiceCollection services,
+ ServiceLifetime contextLifetime) where T : DbContext => services;
+ }
+
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddDbContext<{|E128154:StoreContext|}>(ServiceLifetime.Singleton);
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForAContextRegistrationOnAReceiverThatIsNotAServiceCollection()
+ {
+ return VerifyAsync(ReferenceAssemblies.Net.Net100, """
+ namespace Microsoft.EntityFrameworkCore
+ {
+ public class DbContext { }
+ }
+
+ namespace Microsoft.Extensions.DependencyInjection
+ {
+ public enum ServiceLifetime { Singleton, Scoped, Transient }
+
+ public interface IServiceCollection { }
+ }
+
+ namespace App
+ {
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+
+ class StoreContext : DbContext { }
+
+ class Registry
+ {
+ public void AddDbContext(ServiceLifetime contextLifetime) where T : DbContext { }
+ }
+
+ class Startup
+ {
+ void Configure(Registry registry)
+ {
+ registry.AddDbContext(ServiceLifetime.Singleton);
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForAContextRegistrationWhenNoServiceCollectionTypeExists()
+ {
+ return VerifyAsync(ReferenceAssemblies.Net.Net100, """
+ namespace Microsoft.EntityFrameworkCore
+ {
+ public class DbContext { }
+ }
+
+ namespace Microsoft.Extensions.DependencyInjection
+ {
+ public enum ServiceLifetime { Singleton, Scoped, Transient }
+ }
+
+ namespace App
+ {
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+
+ class StoreContext : DbContext { }
+
+ class Registry
+ {
+ public void AddDbContext(ServiceLifetime contextLifetime) where T : DbContext { }
+ }
+
+ class Startup
+ {
+ void Configure(Registry registry)
+ {
+ registry.AddDbContext(ServiceLifetime.Singleton);
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheServiceLifetimeTypeHasNoSingletonMember()
+ {
+ return VerifyAsync(ReferenceAssemblies.Net.Net100, """
+ namespace Microsoft.EntityFrameworkCore
+ {
+ public class DbContext { }
+ }
+
+ namespace Microsoft.Extensions.DependencyInjection
+ {
+ public enum ServiceLifetime { Scoped, Transient }
+
+ public interface IServiceCollection { }
+ }
+
+ namespace App
+ {
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+
+ class StoreContext : DbContext { }
+
+ static class Helpers
+ {
+ public static IServiceCollection AddDbContext(
+ this IServiceCollection services,
+ ServiceLifetime contextLifetime) where T : DbContext => services;
+ }
+
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddDbContext(ServiceLifetime.Scoped);
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheSingletonMemberOfTheServiceLifetimeTypeIsAProperty()
+ {
+ return VerifyAsync(ReferenceAssemblies.Net.Net100, """
+ namespace Microsoft.EntityFrameworkCore
+ {
+ public class DbContext { }
+ }
+
+ namespace Microsoft.Extensions.DependencyInjection
+ {
+ public sealed class ServiceLifetime
+ {
+ public static ServiceLifetime Singleton => new ServiceLifetime();
+ }
+
+ public interface IServiceCollection { }
+ }
+
+ namespace App
+ {
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+
+ class StoreContext : DbContext { }
+
+ static class Helpers
+ {
+ public static IServiceCollection AddDbContext(
+ this IServiceCollection services,
+ ServiceLifetime contextLifetime) where T : DbContext => services;
+ }
+
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddDbContext(ServiceLifetime.Singleton);
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheSingletonFieldOfTheServiceLifetimeTypeHasNoConstant()
+ {
+ return VerifyAsync(ReferenceAssemblies.Net.Net100, """
+ namespace Microsoft.EntityFrameworkCore
+ {
+ public class DbContext { }
+ }
+
+ namespace Microsoft.Extensions.DependencyInjection
+ {
+ public sealed class ServiceLifetime
+ {
+ public static readonly ServiceLifetime Singleton = new ServiceLifetime();
+ }
+
+ public interface IServiceCollection { }
+ }
+
+ namespace App
+ {
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.DependencyInjection;
+
+ class StoreContext : DbContext { }
+
+ static class Helpers
+ {
+ public static IServiceCollection AddDbContext(
+ this IServiceCollection services,
+ ServiceLifetime contextLifetime) where T : DbContext => services;
+ }
+
+ class Startup
+ {
+ void Configure(IServiceCollection services)
+ {
+ services.AddDbContext(ServiceLifetime.Singleton);
+ }
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/CatchFilterOceAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/CatchFilterOceAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..e2097a8
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/CatchFilterOceAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,89 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class CatchFilterOceAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheFilterNamesATypeThroughANamespaceQualifier()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ class C
+ {
+ void M()
+ {
+ try { }
+ {|E128039:catch (Exception ex) when (ex is not System.IO.IOException)|}
+ {
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheFilterQualifiesTheCancellationType()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ class C
+ {
+ void M()
+ {
+ try { }
+ catch (Exception ex) when (ex is not System.OperationCanceledException)
+ {
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenASingleNotPatternExcludesAnUnrelatedType()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ class C
+ {
+ void M()
+ {
+ try { }
+ {|E128039:catch (Exception ex) when (ex is not OutOfMemoryException)|}
+ {
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenANestedBinaryPatternPrecedesTheNotPattern()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ using System.IO;
+ class C
+ {
+ void M()
+ {
+ try { }
+ {|E128039:catch (Exception ex) when (ex is IOException or FileNotFoundException or not OutOfMemoryException)|}
+ {
+ }
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ChainedStringReplaceCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/ChainedStringReplaceCodeFixProviderBranchCoverageGapTests.cs
new file mode 100644
index 0000000..0ba8a64
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ChainedStringReplaceCodeFixProviderBranchCoverageGapTests.cs
@@ -0,0 +1,53 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ChainedStringReplaceCodeFixProviderBranchCoverageGapTests
+{
+ private static Task VerifyNoFixAsync(string source)
+ {
+ return CodeFixTestRunner.NoFixAsync(source);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task NoFix_WhenTheConditionReceiverIsAMemberAccess()
+ {
+ return VerifyNoFixAsync("""
+ class C
+ {
+ private string _value = string.Empty;
+
+ void M()
+ {
+ {|E128098:while (this._value.Contains("--"))
+ {
+ _value = _value.Replace("--", "-");
+ }|}
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task NoFix_WhenTheReplaceReceiverIsAMemberAccess()
+ {
+ return VerifyNoFixAsync("""
+ class C
+ {
+ private string _value = string.Empty;
+
+ void M()
+ {
+ {|E128098:while (_value.Contains("--"))
+ {
+ _value = this._value.Replace("--", "-");
+ }|}
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ClosedHierarchyBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ClosedHierarchyBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..64c5102
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ClosedHierarchyBranchCoverageMoreTests.cs
@@ -0,0 +1,61 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Design;
+using Microsoft.CodeAnalysis.CSharp;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ClosedHierarchyBranchCoverageMoreTests
+{
+ private static AnalyzerTestOptions Options => new()
+ {
+ LanguageVersion = LanguageVersion.Latest,
+ Sources = [UnionTestRuntime.StubSource],
+ };
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheBaseCarriesAnUnrelatedAttribute()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ [System.Obsolete]
+ internal abstract class {|E128225:Shape|}
+ {
+ internal string Label() => "shape";
+ }
+
+ internal sealed class Circle : Shape
+ {
+ }
+ """,
+ options: Options);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenASwitchOverAnEnumEndsInADiscardArm()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ internal enum Kind
+ {
+ A,
+ B
+ }
+
+ internal static class Switcher
+ {
+ internal static int Switch(Kind kind)
+ {
+ return kind switch
+ {
+ Kind.A => 1,
+ _ => 0
+ };
+ }
+ }
+ """,
+ options: Options);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ComparerSetConstructionAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ComparerSetConstructionAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..8e217f5
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ComparerSetConstructionAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,106 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ComparerSetConstructionAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheSetIsAFieldOrPropertyInitializer()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ using System.Collections.Generic;
+
+ class C
+ {
+ private readonly HashSet field = new(StringComparer.Ordinal);
+
+ HashSet Property { get; } = new(StringComparer.Ordinal);
+
+ void M(string[] items)
+ {
+ foreach (var item in items)
+ {
+ field.Add(item);
+ Property.Add(item);
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheSetIsAssignedToAFieldOrAMemberAccess()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ using System.Collections.Generic;
+
+ class C
+ {
+ private HashSet field = new();
+
+ void M(string[] items)
+ {
+ field = new HashSet(StringComparer.Ordinal);
+ this.field = new HashSet(StringComparer.Ordinal);
+
+ foreach (var item in items)
+ {
+ field.Add(item);
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheSetIsAnArgument()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ using System.Collections.Generic;
+
+ class C
+ {
+ static void Consume(HashSet set)
+ {
+ }
+
+ void M()
+ {
+ Consume(new HashSet(StringComparer.Ordinal));
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheConstructorArgumentHasNoType()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Collections.Generic;
+
+ class C
+ {
+ void M(string[] items)
+ {
+ var set = new HashSet(null);
+ foreach (var item in items)
+ {
+ set.Add(item);
+ }
+ }
+ }
+ """,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ComplexityCeilingAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ComplexityCeilingAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..7ea1a7e
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ComplexityCeilingAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,39 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ComplexityCeilingAnalyzerBranchCoverageMoreTests
+{
+ private static DiagnosticResult Warning(int line, int column)
+ {
+ return new DiagnosticResult("E128152", DiagnosticSeverity.Warning).WithLocation(line, column);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Loop_Flagged_WhenTheInnerBoundIsAPrimaryConstructorParameterFromAnotherFile()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ partial class C
+ {
+ void M(int[] items)
+ {
+ foreach (var item in items)
+ {
+ foreach (var value in data)
+ {
+ _ = item + value;
+ }
+ }
+ }
+ }
+ """,
+ Warning(7, 13),
+ new AnalyzerTestOptions { Sources = ["partial class C(int[] data)\n{\n}\n"] });
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ComplexityCeilingBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/ComplexityCeilingBranchCoverageGapTests.cs
new file mode 100644
index 0000000..0a26fcd
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ComplexityCeilingBranchCoverageGapTests.cs
@@ -0,0 +1,64 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ComplexityCeilingBranchCoverageGapTests
+{
+ private static DiagnosticResult Warning(int line, int column)
+ {
+ return new DiagnosticResult("E128152", DiagnosticSeverity.Warning).WithLocation(line, column);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Loop_Flagged_WhenTheInnerForHasNoCondition()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ class C
+ {
+ void M(int[] items)
+ {
+ foreach (var item in items)
+ {
+ for (;;)
+ {
+ break;
+ }
+ }
+ }
+ }
+ """,
+ Warning(7, 13));
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Loop_Flagged_WhenTheInnerBoundPassesTheOuterCounterToACall()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ class C
+ {
+ static int Limit(int index) => index;
+
+ void M(int count)
+ {
+ for (var i = 0; i < count; i++)
+ {
+ for (var j = 0; j < Limit(i); j++)
+ {
+ _ = j;
+ }
+ }
+ }
+ }
+ """,
+ Warning(9, 13));
+ }
+
+}
diff --git a/tests/E128.Analyzers.Tests/CompositeDetectionSpecificityAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/CompositeDetectionSpecificityAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..628e78f
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/CompositeDetectionSpecificityAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,126 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class CompositeDetectionSpecificityAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyAsync(string statement)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ $$"""
+ namespace Detections
+ {
+ public abstract record DetectionRule;
+ public sealed record ResourceDetection(string Selector, string Extra = "") : DetectionRule;
+ public sealed record CompositeDetection(DetectionRule[] Branches, string Extra = "") : DetectionRule
+ {
+ public CompositeDetection() : this([]) { }
+ }
+ public sealed class Box(T[] values)
+ {
+ public T[] Values { get; } = values;
+ }
+ }
+ class C
+ {
+ void M()
+ {
+ {{statement}}
+ }
+ }
+ """,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenBothTypesAreNamespaceQualified()
+ {
+ return VerifyAsync(
+ """var rule = {|E128079:new Detections.CompositeDetection([new Detections.ResourceDetection("#content")])|};""");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompositeNameIsQualifiedButDiffers()
+ {
+ return VerifyAsync("""var rule = new Detections.ResourceDetection("#content");""");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompositeIsAGenericType()
+ {
+ return VerifyAsync(
+ """var rule = new Detections.Box([new Detections.ResourceDetection("#content")]);""");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheInnerDetectionIsAQualifiedOtherType()
+ {
+ return VerifyAsync(
+ """var rule = new Detections.CompositeDetection([new System.Text.StringBuilder("#content")]);""");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheInnerDetectionIsAGenericType()
+ {
+ return VerifyAsync(
+ "var rule = new Detections.CompositeDetection([new System.Collections.Generic.List()]);");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompositeHasNoArgumentList()
+ {
+ return VerifyAsync("var rule = new Detections.CompositeDetection { };");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompositeHasNoArguments()
+ {
+ return VerifyAsync("var rule = new Detections.CompositeDetection();");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompositeHasTwoArguments()
+ {
+ return VerifyAsync(
+ """var rule = new Detections.CompositeDetection([new Detections.ResourceDetection("#content")], "x");""");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheResourceDetectionHasNoArgumentList()
+ {
+ return VerifyAsync("var rule = new Detections.CompositeDetection([new Detections.ResourceDetection { }]);");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheResourceDetectionHasTwoArguments()
+ {
+ return VerifyAsync(
+ """var rule = new Detections.CompositeDetection([new Detections.ResourceDetection("#content", "x")]);""");
+ }
+
+ [Theory]
+ [Trait("Category", "CI")]
+ [InlineData("#item{")]
+ [InlineData("#item~")]
+ [InlineData("#café")]
+ [InlineData("#item[")]
+ [InlineData("#item^")]
+ [InlineData("#item`")]
+ public Task Silent_WhenTheSelectorHoldsACharacterAboveTheLetterRange(string selector)
+ {
+ return VerifyAsync($$"""var rule = new Detections.CompositeDetection([new Detections.ResourceDetection("{{selector}}")]);""");
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ConcreteOnlyDiRegistrationAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ConcreteOnlyDiRegistrationAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..09f577a
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ConcreteOnlyDiRegistrationAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,109 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Design;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ConcreteOnlyDiRegistrationAnalyzerBranchCoverageMoreTests
+{
+ private const string Stubs = """
+ interface IMyService { }
+ class MyService : IMyService { }
+ class Services
+ {
+ public Services AddSingleton() where T : class => this;
+ public T GetRequiredService() where T : class => default!;
+ public Services Configure() => this;
+ }
+ """;
+
+ private static Task VerifyAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code + "\n" + Stubs);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheRegistrationIsAnUnqualifiedCall()
+ {
+ return VerifyAsync(
+ """
+ class Startup
+ {
+ static void AddSingleton(T instance) where T : class
+ {
+ }
+
+ static void Configure()
+ {
+ {|E128032:AddSingleton(new MyService())|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheRegistrationUsesAConditionalAccess()
+ {
+ return VerifyAsync(
+ """
+ class Startup
+ {
+ static void Configure(Services? services)
+ {
+ services?.AddSingleton();
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheRegistrationTargetIsDynamic()
+ {
+ return VerifyAsync(
+ """
+ class Startup
+ {
+ static void Configure(dynamic services)
+ {
+ services.AddSingleton();
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheRegistrationSitsInAnExpressionBody()
+ {
+ return VerifyAsync(
+ """
+ class Startup
+ {
+ static Services Configure(Services services) => services.{|E128032:AddSingleton()|};
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheScopeHoldsOtherCallsAndAForwardingCallForAnotherType()
+ {
+ return VerifyAsync(
+ """
+ class Other { }
+
+ class Startup
+ {
+ static void Configure(Services services)
+ {
+ services.Configure();
+ services.GetRequiredService();
+ services.{|E128032:AddSingleton()|};
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..62dafec
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,69 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ConcreteTypeDiDependencyAnalyzerBranchCoverageMoreTests
+{
+ private const string Services = """
+ interface IMyService { }
+ class MyService : IMyService { }
+ class Services
+ {
+ public void AddSingleton(string name) { }
+ public void AddSingleton() { }
+ public void AddSingleton() { }
+ public void AddSingleton() { }
+ }
+ """;
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenInterfaceRegistrationSitsBesideNonGenericAndUnresolvedCalls()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ Services + """
+
+ class Consumer
+ {
+ public Consumer({|E128035:MyService svc|}) { }
+ }
+ class Startup
+ {
+ void Configure(Services services, Missing missing)
+ {
+ services.AddSingleton("name");
+ missing.AddSingleton();
+ services.AddSingleton();
+ }
+ }
+ """,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenRegistrationsUseArrayTypeArgumentsAndThreeTypeArguments()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ Services + """
+
+ class Consumer
+ {
+ public Consumer({|E128035:MyService svc|}, byte[] data) { }
+ }
+ class Startup
+ {
+ void Configure(Services services)
+ {
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixProviderBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..a6ecb9d
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixProviderBranchCoverageMoreTests.cs
@@ -0,0 +1,66 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ConcreteTypeDiDependencyCodeFixProviderBranchCoverageMoreTests
+{
+ private static readonly ReferenceAssemblies References = ReferenceAssemblies.Net.Net100
+ .AddPackages([new PackageIdentity("Microsoft.Extensions.DependencyInjection", "10.0.6")]);
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task NoFix_WhenTheRegistrationNamesTheImplementationWithAQualifier()
+ {
+ return CodeFixTestRunner.NoFixAsync(
+ """
+ using Microsoft.Extensions.DependencyInjection;
+ interface IService { }
+ class Outer
+ {
+ public class Service : IService { }
+ }
+ class Consumer
+ {
+ public Consumer({|E128035:Outer.Service service|}) { }
+ }
+ class Startup
+ {
+ void Note() { }
+
+ void Configure(IServiceCollection services)
+ {
+ this.Note();
+ services.AddSingleton();
+ }
+ }
+ """,
+ References,
+ CodeFixTestBehaviors.SkipLocalDiagnosticCheck);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task NoFix_WhenTheRegistrationIsNotAStatement()
+ {
+ return CodeFixTestRunner.NoFixAsync(
+ """
+ using Microsoft.Extensions.DependencyInjection;
+ interface IService { }
+ class Service : IService { }
+ class Consumer
+ {
+ public Consumer({|E128035:Service service|}) { }
+ }
+ class Startup
+ {
+ IServiceCollection Configure(IServiceCollection services) =>
+ services.AddSingleton();
+ }
+ """,
+ References,
+ CodeFixTestBehaviors.SkipLocalDiagnosticCheck);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ConcurrencyLimitAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ConcurrencyLimitAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..eb9da67
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ConcurrencyLimitAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,91 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ConcurrencyLimitAnalyzerBranchCoverageMoreTests
+{
+ private static readonly AnalyzerTestOptions IgnoreCompilerErrors = new() { CompilerDiagnostics = CompilerDiagnostics.None };
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheSemaphoreCreationDoesNotBind()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Threading;
+ class C
+ {
+ void M()
+ {
+ var semaphore = new SemaphoreSlim("one", 2, 3);
+ }
+ }
+ """,
+ expected: null,
+ options: IgnoreCompilerErrors);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheBoundedChannelCallDoesNotBind()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Threading.Channels;
+ class C
+ {
+ void M()
+ {
+ var channel = Channel.CreateBounded("a", "b", "c", "d");
+ }
+ }
+ """,
+ expected: null,
+ options: IgnoreCompilerErrors);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenANamedConstantIsNegated()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.Threading;
+ class C
+ {
+ const int Limit = 3;
+ SemaphoreSlim M() => {|E128040:new SemaphoreSlim(-Limit)|};
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenACharacterLiteralIsNegated()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.Threading;
+ class C
+ {
+ SemaphoreSlim M() => {|E128040:new SemaphoreSlim(-'a')|};
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCountIsACharacterLiteral()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.Threading;
+ using System.Threading.Channels;
+ class C
+ {
+ SemaphoreSlim M() => new SemaphoreSlim('a');
+ Channel N() => Channel.CreateBounded('a');
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ConcurrentDictionaryDoubleLookupAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ConcurrentDictionaryDoubleLookupAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..b6cb0a2
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ConcurrentDictionaryDoubleLookupAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,160 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ConcurrentDictionaryDoubleLookupAnalyzerBranchCoverageMoreTests
+{
+ private static string Wrap(string body)
+ {
+ return "using System.Collections.Concurrent;\n\n"
+ + "class C\n{\n"
+ + " int M(ConcurrentDictionary map, ConcurrentDictionary other, string key, int index)\n {\n"
+ + body
+ + " return 0;\n }\n}\n";
+ }
+
+ private static Task VerifyAsync(string body)
+ {
+ return AnalyzerTestRunner.VerifyAsync(Wrap(body));
+ }
+
+ private static Task VerifyLenientAsync(string body)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ Wrap(body),
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheReceiverIsANamespace()
+ {
+ return VerifyLenientAsync("""
+ if (System.ContainsKey(key))
+ {
+ return map[key];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenContainsKeyTakesNoArgument()
+ {
+ return VerifyLenientAsync("""
+ if (map.ContainsKey())
+ {
+ return map[key];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheReceiverIsAConditionalExpression()
+ {
+ return VerifyAsync("""
+ if ((index > 0 ? map : other).ContainsKey(key))
+ {
+ return map[key];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheIndexerCallHasTwoArguments()
+ {
+ return VerifyLenientAsync("""
+ if (map.ContainsKey(key))
+ {
+ return map[key, index];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fires_WhenTheIndexerValueIsNegated()
+ {
+ return VerifyAsync("""
+ if ({|E128208:map.ContainsKey(key)|})
+ {
+ return -map[key];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fires_WhenTheIndexerValueIsReadThroughAParenthesizedExpression()
+ {
+ return VerifyAsync("""
+ if ({|E128208:map.ContainsKey(key)|})
+ {
+ return (map[key]) + 1;
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fires_WhenTheKeysAreTheSameConstant()
+ {
+ return VerifyAsync("""
+ if ({|E128208:map.ContainsKey("a")|})
+ {
+ return map["a"];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheKeysAreNotConstantExpressions()
+ {
+ return VerifyAsync("""
+ if (map.ContainsKey(index > 0 ? "a" : "b"))
+ {
+ return map[index > 0 ? "a" : "b"];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenOnlyTheIndexerKeyIsAConstant()
+ {
+ return VerifyAsync("""
+ if (map.ContainsKey(index > 0 ? "a" : "b"))
+ {
+ return map["a"];
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenOnlyTheContainsKeyArgumentIsAConstant()
+ {
+ return VerifyAsync("""
+ if (map.ContainsKey("a"))
+ {
+ return map[index > 0 ? "a" : "b"];
+ }
+
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ConfigurationKeyMissingAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ConfigurationKeyMissingAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..44687e2
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ConfigurationKeyMissingAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,199 @@
+using System.Threading;
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Testing;
+using Microsoft.CodeAnalysis.Text;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ConfigurationKeyMissingAnalyzerBranchCoverageMoreTests
+{
+ private const string ConfigurationStub = """
+ namespace Microsoft.Extensions.Configuration
+ {
+ public interface IConfiguration
+ {
+ string? this[string key] { get; set; }
+ IConfigurationSection GetSection(string key);
+ }
+
+ public interface IConfigurationSection : IConfiguration
+ {
+ }
+
+ public static class ConfigurationExtensions
+ {
+ public static IConfigurationSection GetRequiredSection(
+ this IConfiguration configuration,
+ string key)
+ {
+ return configuration.GetSection(key);
+ }
+
+ public static string? GetConnectionString(
+ this IConfiguration configuration,
+ string name)
+ {
+ return null;
+ }
+ }
+ }
+ """;
+
+ //lang=json
+ private const string AppSettings = """{ "Known": 1 }""";
+
+ private static AnalyzerTestOptions Options => new() { AdditionalFiles = [("appsettings.json", AppSettings)] };
+
+ private static Task VerifyAsync(string code, params DiagnosticResult[] expected)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ code + ConfigurationStub,
+ expected,
+ options: Options);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompilationHasNoConfigurationType()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ class C
+ {
+ string M(string[] values) => values[0];
+ }
+ """,
+ options: Options);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnIndexerTakesTwoArguments()
+ {
+ return VerifyAsync(
+ """
+ class C
+ {
+ int M(int[,] grid) => grid[0, 1];
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnInvocationHasNoArguments()
+ {
+ return VerifyAsync(
+ """
+ class C
+ {
+ string M(object value) => value.ToString() ?? string.Empty;
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheInvokedExpressionIsNotAMemberAccess()
+ {
+ return VerifyAsync(
+ """
+ class C
+ {
+ static int Helper(string key) => key.Length;
+
+ int M() => Helper("Missing");
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenADynamicCallUsesAConfigurationMethodName()
+ {
+ return VerifyAsync(
+ """
+ class C
+ {
+ object? M(dynamic value) => value.GetSection("Missing");
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnUnrelatedTypeDeclaresGetSection()
+ {
+ return VerifyAsync(
+ """
+ class Other
+ {
+ public string? GetSection(string key) => key;
+ public string? GetRequiredSection(string key) => key;
+ public string? GetConnectionString(string key) => key;
+ }
+
+ class C
+ {
+ void M(Other other)
+ {
+ _ = other.GetSection("Missing");
+ _ = other.GetRequiredSection("Missing");
+ _ = other.GetConnectionString("Missing");
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public async Task Reports_WhenAnAppSettingsFileHasNoText()
+ {
+ var tree = CSharpSyntaxTree.ParseText(
+ """
+ using Microsoft.Extensions.Configuration;
+ class C
+ {
+ string? M(IConfiguration configuration) => configuration["Missing"];
+ }
+ """ + ConfigurationStub,
+ cancellationToken: TestContext.Current.CancellationToken);
+ var compilation = CSharpCompilation.Create(
+ "Probe",
+ [tree],
+ [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)],
+ new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
+ var options = new AnalyzerOptions(
+ [new UnreadableAdditionalText("appsettings.json", null), new UnreadableAdditionalText("appsettings.Dev.json", AppSettings)]);
+
+ var diagnostics = await compilation
+ .WithAnalyzers([new ConfigurationKeyMissingAnalyzer()], options)
+ .GetAnalyzerDiagnosticsAsync(TestContext.Current.CancellationToken);
+
+ var diagnostic = Assert.Single(diagnostics);
+ Assert.Equal("E128195", diagnostic.Id);
+ }
+
+ private sealed class UnreadableAdditionalText : AdditionalText
+ {
+ private readonly SourceText? text;
+
+ internal UnreadableAdditionalText(string path, string? content)
+ {
+ Path = path;
+ text = content is null ? null : SourceText.From(content);
+ }
+
+ public override string Path { get; }
+
+ public override SourceText? GetText(CancellationToken cancellationToken = default)
+ {
+ return text;
+ }
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/CultureStringComparerAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/CultureStringComparerAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..c43bcb9
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/CultureStringComparerAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,50 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class CultureStringComparerAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCreationHasNoArgumentList()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.Collections.Generic;
+ class C
+ {
+ HashSet Set = new HashSet { "a" };
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCreatedTypeIsATypeParameter()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ class C
+ {
+ T Make() where T : new()
+ {
+ return new T();
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheStringCollectionIsNotATrackedType()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ using System.Collections.Generic;
+ class C
+ {
+ List Items = new List(StringComparer.CurrentCulture.GetType().Name.Length);
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/DateTimeParseRoundtripAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/DateTimeParseRoundtripAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..446d75f
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/DateTimeParseRoundtripAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,25 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class DateTimeParseRoundtripAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheParseCallBindsDynamically()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ class C
+ {
+ void M(string text)
+ {
+ dynamic parser = new object();
+ parser.Parse(text, "format");
+ parser.ParseExact(text, "format", "provider");
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/DirectHttpClientInstantiationCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/DirectHttpClientInstantiationCodeFixProviderBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..fa3ded1
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/DirectHttpClientInstantiationCodeFixProviderBranchCoverageMoreTests.cs
@@ -0,0 +1,41 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Design;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class DirectHttpClientInstantiationCodeFixProviderBranchCoverageMoreTests
+{
+ private static readonly ReferenceAssemblies Net100WithHttp = ReferenceAssemblies.Net.Net100
+ .AddPackages([new PackageIdentity("Microsoft.Extensions.Http", "10.0.6")]);
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_AppendsTheFieldAndConstructorWhenTheClassHasNoMethod()
+ {
+ return CodeFixTestRunner.RunAsync(
+ """
+ using System.Net.Http;
+ class C
+ {
+ public HttpClient Client => {|E128004:new HttpClient()|};
+ }
+ """,
+ """
+ using System.Net.Http;
+ class C
+ {
+ public HttpClient Client => _httpClientFactory.CreateClient();
+
+ private readonly IHttpClientFactory _httpClientFactory;
+
+ public C(IHttpClientFactory httpClientFactory)
+ {
+ _httpClientFactory = httpClientFactory;
+ }
+ }
+ """,
+ references: Net100WithHttp);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/DiskRoundtripBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/DiskRoundtripBranchCoverageGapTests.cs
new file mode 100644
index 0000000..6dcf18a
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/DiskRoundtripBranchCoverageGapTests.cs
@@ -0,0 +1,76 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class DiskRoundtripBranchCoverageGapTests
+{
+ private static readonly AnalyzerTestOptions NoCompilerDiagnostics =
+ new() { CompilerDiagnostics = CompilerDiagnostics.None };
+
+ private static Task VerifyAsync(string members, AnalyzerTestOptions? options = null)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ "using System;\nusing System.IO;\nclass C\n{\n" + members + "}\n",
+ options: options);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnExpressionBodyHoldsAWriteAndAReadWithoutAStatement()
+ {
+ return VerifyAsync("""
+ static object Combine(object first, object second) => first;
+
+ object M(string path) => Combine(File.Create(path), File.ReadAllBytes(path));
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAFileCallCannotBindToASystemIoOverload()
+ {
+ return VerifyAsync("""
+ string M(string path)
+ {
+ File.WriteAllText(path);
+ return File.ReadAllText(path);
+ }
+
+ """, NoCompilerDiagnostics);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAFileStreamConstructorCannotBindToASystemIoOverload()
+ {
+ return VerifyAsync("""
+ string M(string path, string content)
+ {
+ File.WriteAllText(path, content);
+ using (var stream = new FileStream(path)) { }
+ return content;
+ }
+
+ """, NoCompilerDiagnostics);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheReceiverOfAnInstanceCallHasNoType()
+ {
+ return VerifyAsync("""
+ void M(string path)
+ {
+ Helper.OpenWrite();
+ Helper.OpenRead();
+ }
+
+ static void Helper() { }
+
+ """, NoCompilerDiagnostics);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/DisposableFieldInLoopAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/DisposableFieldInLoopAnalyzerBranchCoverageGapTests.cs
new file mode 100644
index 0000000..21f2122
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/DisposableFieldInLoopAnalyzerBranchCoverageGapTests.cs
@@ -0,0 +1,205 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class DisposableFieldInLoopAnalyzerBranchCoverageGapTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAConstrainedGenericFieldIsOverwritten()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ class C where T : IDisposable
+ {
+ private T value;
+ void M(T replacement)
+ {
+ while (true)
+ {
+ {|E128193:value|} = replacement;
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnUnconstrainedGenericFieldIsOverwritten()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ class C
+ {
+ private T value;
+ void M(T replacement)
+ {
+ while (true)
+ {
+ value = replacement;
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenADisposableStructFieldIsOverwritten()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ struct Item : IDisposable { public void Dispose() { } }
+ class C
+ {
+ private Item value;
+ void M(Item replacement)
+ {
+ while (true)
+ {
+ value = replacement;
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenOnlyAParameterIsDisposedBeforeReplacement()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ class C
+ {
+ private IDisposable value;
+ void M(IDisposable replacement)
+ {
+ while (true)
+ {
+ replacement.Dispose();
+ {|E128193:value|} = replacement;
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenOnlyAParameterIsDisposedAfterReplacement()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ class C
+ {
+ private IDisposable value;
+ void M(IDisposable replacement)
+ {
+ while (true)
+ {
+ {|E128193:value|} = replacement;
+ replacement.Dispose();
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAConcreteDisposableFieldIsOverwritten()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.IO;
+ class C
+ {
+ private MemoryStream value;
+ void M(MemoryStream replacement)
+ {
+ while (true)
+ {
+ {|E128193:value|} = replacement;
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAGenericConstraintIsNotDisposable()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ class Resource { }
+ class C where T : Resource
+ {
+ private T value;
+ void M(T replacement)
+ {
+ while (true)
+ {
+ value = replacement;
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAnOrdinaryCallPrecedesTheAssignment()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ using System.IO;
+ class C
+ {
+ private MemoryStream value;
+ void M(MemoryStream replacement)
+ {
+ while (true)
+ {
+ GC.KeepAlive(this);
+ {|E128193:value|} = replacement;
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenALambdaExitsBetweenTheAssignmentAndTheDispose()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ using System.IO;
+ class C
+ {
+ private MemoryStream value;
+ void M(MemoryStream replacement)
+ {
+ while (true)
+ {
+ value = replacement;
+ Action leave = () => { return; };
+ GC.KeepAlive(leave);
+ value.Dispose();
+ }
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/DllImportToLibraryImportAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/DllImportToLibraryImportAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..4416b36
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/DllImportToLibraryImportAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,206 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis.CSharp.Testing;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class DllImportToLibraryImportAnalyzerBranchCoverageMoreTests
+{
+ private static AnalyzerTestOptions Lenient => new() { CompilerDiagnostics = CompilerDiagnostics.None };
+
+ private static Task VerifyFixAsync(string source, string fixedCode)
+ {
+ var test = new CSharpCodeFixTest<
+ DllImportToLibraryImportAnalyzer,
+ DllImportToLibraryImportCodeFixProvider,
+ DefaultVerifier>
+ {
+ TestCode = source,
+ FixedCode = fixedCode,
+ ReferenceAssemblies = ReferenceAssemblies.Net.Net100,
+ CompilerDiagnostics = CompilerDiagnostics.None,
+ };
+ test.SolutionTransforms.Add(CodeFixTestRunner.AllowUnsafe);
+
+ return test.RunAsync(TestContext.Current.CancellationToken);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheRuntimeLacksLibraryImportAttribute()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Runtime.InteropServices;
+ static class Native
+ {
+ [DllImport("libc")]
+ internal static extern int Abs(int value);
+ }
+ """,
+ options: new AnalyzerTestOptions
+ {
+ References = ReferenceAssemblies.NetStandard.NetStandard20,
+ CompilerDiagnostics = CompilerDiagnostics.None
+ });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheDllImportAttributeDoesNotResolve()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ static class Native
+ {
+ [DllImport("libc")]
+ internal static extern int Abs(int value);
+ }
+ """,
+ options: Lenient);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAUserAttributeIsNamedDllImport()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ class DllImport : Attribute
+ {
+ public DllImport(string name) { }
+ }
+ static class Native
+ {
+ [DllImport("libc")]
+ internal static int Abs(int value) => value;
+ }
+ """,
+ options: Lenient);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAttributeNameIsAliasQualified()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System;
+ class DllImportAttribute : Attribute
+ {
+ public DllImportAttribute(string name) { }
+ }
+ static class Native
+ {
+ [global::DllImport("libc")]
+ internal static int Abs(int value) => value;
+ }
+ """,
+ options: Lenient);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_AcceptsAVoidReturn()
+ {
+ return VerifyFixAsync(
+ """
+ using System.Runtime.InteropServices;
+ static class Native
+ {
+ [{|E128117:DllImport("libc")|}]
+ internal static extern void Sleep(int milliseconds);
+ }
+ """,
+ """
+ using System.Runtime.InteropServices;
+ static partial class Native
+ {
+ [LibraryImport("libc")]
+ internal static partial void Sleep(int milliseconds);
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_AcceptsEnumParametersAndReturns()
+ {
+ return VerifyFixAsync(
+ """
+ using System.Runtime.InteropServices;
+ enum Mode : int { A, B }
+ static class Native
+ {
+ [{|E128117:DllImport("libc")|}]
+ internal static extern Mode Next(Mode mode);
+ }
+ """,
+ """
+ using System.Runtime.InteropServices;
+ enum Mode : int { A, B }
+ static partial class Native
+ {
+ [LibraryImport("libc")]
+ internal static partial Mode Next(Mode mode);
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_AcceptsPointerParametersAndReturns()
+ {
+ return VerifyFixAsync(
+ """
+ using System.Runtime.InteropServices;
+ static class Native
+ {
+ [{|E128117:DllImport("libc")|}]
+ internal static extern unsafe int* Next(int* cursor);
+ }
+ """,
+ """
+ using System.Runtime.InteropServices;
+ static partial class Native
+ {
+ [LibraryImport("libc")]
+ internal static unsafe partial int* Next(int* cursor);
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task NoFix_WhenOnlyTheReturnTypeIsNotBlittable()
+ {
+ const string Code = """
+ using System.Runtime.InteropServices;
+ static class Native
+ {
+ [{|E128117:DllImport("libc")|}]
+ internal static extern string Name(int value);
+ }
+ """;
+
+ return VerifyFixAsync(Code, Code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheQualifiedAttributeNameEndsInAGenericName()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ static class Native
+ {
+ [System.Runtime.InteropServices.DllImport("libc")]
+ internal static extern int Abs(int value);
+ }
+ """,
+ options: Lenient);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/DllImportToLibraryImportCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/DllImportToLibraryImportCodeFixProviderBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..e920f2e
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/DllImportToLibraryImportCodeFixProviderBranchCoverageMoreTests.cs
@@ -0,0 +1,75 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis.CSharp.Testing;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class DllImportToLibraryImportCodeFixProviderBranchCoverageMoreTests
+{
+ private static Task VerifyFixAsync(string source, string fixedCode)
+ {
+ // The fixed code needs the LibraryImport source generator, which the test
+ // harness does not run. Compiler diagnostics are therefore not validated.
+ var test = new CSharpCodeFixTest<
+ DllImportToLibraryImportAnalyzer,
+ DllImportToLibraryImportCodeFixProvider,
+ DefaultVerifier>
+ {
+ TestCode = source,
+ FixedCode = fixedCode,
+ ReferenceAssemblies = ReferenceAssemblies.Net.Net100,
+ CompilerDiagnostics = CompilerDiagnostics.None,
+ };
+ test.SolutionTransforms.Add(CodeFixTestRunner.AllowUnsafe);
+
+ return test.RunAsync(TestContext.Current.CancellationToken);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_KeepsATypeThatIsAlreadyPartial()
+ {
+ return VerifyFixAsync(
+ """
+ using System.Runtime.InteropServices;
+ static partial class Native
+ {
+ [{|E128117:DllImport("libc")|}]
+ internal static extern int Abs(int value);
+ }
+ """,
+ """
+ using System.Runtime.InteropServices;
+ static partial class Native
+ {
+ [LibraryImport("libc")]
+ internal static partial int Abs(int value);
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_KeepsAMethodThatIsAlreadyPartial()
+ {
+ return VerifyFixAsync(
+ """
+ using System.Runtime.InteropServices;
+ static class Native
+ {
+ [{|E128117:DllImport("libc")|}]
+ internal static extern partial int Abs(int value);
+ }
+ """,
+ """
+ using System.Runtime.InteropServices;
+ static partial class Native
+ {
+ [LibraryImport("libc")]
+ internal static partial int Abs(int value);
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/DuplicateJsonPropertyNameBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/DuplicateJsonPropertyNameBranchCoverageGapTests.cs
new file mode 100644
index 0000000..b2e81b8
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/DuplicateJsonPropertyNameBranchCoverageGapTests.cs
@@ -0,0 +1,145 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class DuplicateJsonPropertyNameBranchCoverageGapTests
+{
+ private static Task VerifyAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ "using System;\nusing System.Text.Json.Serialization;\n" + code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenADerivedFieldReusesTheNameOfABaseField()
+ {
+ return VerifyAsync("""
+ public class Base
+ {
+ [JsonPropertyName("id")]
+ public int BaseId;
+ }
+
+ public sealed class Derived : Base
+ {
+ [{|E128178:JsonPropertyName("id")|}]
+ public int DerivedId;
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAnUnresolvedAttributePrecedesTheJsonPropertyName()
+ {
+ return VerifyAsync("""
+ public sealed class Widget
+ {
+ [JsonPropertyName("id")]
+ public int First { get; set; }
+
+ [{|CS0246:{|CS0246:Missing|}|}]
+ [{|E128178:JsonPropertyName("id")|}]
+ public int Second { get; set; }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheJsonNameIsNull()
+ {
+ return VerifyAsync("""
+ public sealed class Widget
+ {
+ [JsonPropertyName(null)]
+ public int First { get; set; }
+
+ [JsonPropertyName(null)]
+ public int Second { get; set; }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAJsonPropertyNameLookalikeCarriesNoName()
+ {
+ return VerifyAsync("""
+ namespace System.Text.Json.Serialization
+ {
+ [AttributeUsage(AttributeTargets.Property)]
+ public sealed class JsonPropertyNameAttribute : Attribute
+ {
+ public JsonPropertyNameAttribute() { }
+
+ public JsonPropertyNameAttribute(string name) { }
+ }
+ }
+
+ public sealed class Widget
+ {
+ [JsonPropertyName]
+ public int First { get; set; }
+
+ [JsonPropertyName]
+ public int Second { get; set; }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAJsonIgnoreLookalikeNamesNoCondition()
+ {
+ return VerifyAsync("""
+ namespace System.Text.Json.Serialization
+ {
+ [AttributeUsage(AttributeTargets.Property)]
+ public sealed class JsonIgnoreAttribute : Attribute
+ {
+ public int Order { get; set; }
+ }
+ }
+
+ public sealed class Widget
+ {
+ [JsonPropertyName("id")]
+ public int First { get; set; }
+
+ [JsonIgnore(Order = 1)]
+ [JsonPropertyName("id")]
+ public int Second { get; set; }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAJsonIgnoreLookalikeNamesANonIntegerCondition()
+ {
+ return VerifyAsync("""
+ namespace System.Text.Json.Serialization
+ {
+ [AttributeUsage(AttributeTargets.Property)]
+ public sealed class JsonIgnoreAttribute : Attribute
+ {
+ public string Condition { get; set; }
+ }
+ }
+
+ public sealed class Widget
+ {
+ [JsonPropertyName("id")]
+ public int First { get; set; }
+
+ [JsonIgnore(Condition = "never")]
+ [{|E128178:JsonPropertyName("id")|}]
+ public int Second { get; set; }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/EfQueryInLoopAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/EfQueryInLoopAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..cddae0f
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/EfQueryInLoopAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,158 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class EfQueryInLoopAnalyzerBranchCoverageMoreTests
+{
+ // The test project carries no EF Core package. Each snippet declares the query surface as a stub.
+ private const string EfStub = """
+ using System;
+ using System.Collections;
+ using System.Collections.Generic;
+ using System.Linq;
+ using Microsoft.EntityFrameworkCore;
+
+ namespace Microsoft.EntityFrameworkCore
+ {
+ public abstract class DbSet : IQueryable
+ {
+ public Type ElementType => typeof(T);
+ public System.Linq.Expressions.Expression Expression => throw new NotImplementedException();
+ public IQueryProvider Provider => throw new NotImplementedException();
+ public IEnumerator GetEnumerator() => throw new NotImplementedException();
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
+ }
+ }
+
+ class Item
+ {
+ public int Id { get; set; }
+ }
+
+ class Holder
+ {
+ public IQueryable- Query { get; set; } = Enumerable.Empty
- ().AsQueryable();
+ }
+
+ """;
+
+ private static Task VerifyAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync
(EfStub + code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompilationHasNoDbSetType()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Collections.Generic;
+ using System.Linq;
+
+ class C
+ {
+ void M(List local, int[] ids)
+ {
+ foreach (var id in ids)
+ {
+ var all = local.ToList();
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheReceiverIsAnArray()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ void M(int[] values, int[] ids)
+ {
+ foreach (var id in ids)
+ {
+ var found = values.Contains(id);
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheReceiverIsATypeParameterConstrainedToQueryable()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ void M(TQuery source, int[] ids)
+ where TQuery : IQueryable-
+ {
+ foreach (var id in ids)
+ {
+ var all = source.ToList();
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fires_WhenACastParenthesizedDbSetIsMaterialized()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ void M(DbSet
- items, int[] ids)
+ {
+ foreach (var id in ids)
+ {
+ var all = {|E128180:((IQueryable
- )items).ToList()|};
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheQueryableComesFromAMemberOfAnotherObject()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ void M(Holder holder, int[] ids)
+ {
+ foreach (var id in ids)
+ {
+ var all = holder.Query.ToList();
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAStaticQueryableCallStartsAtANamespace()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ void M(List
- local, int[] ids)
+ {
+ foreach (var id in ids)
+ {
+ var all = System.Linq.Queryable.AsQueryable(local).ToList();
+ }
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/EnumIfElseChainAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/EnumIfElseChainAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..ad6a7ff
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/EnumIfElseChainAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,103 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Design;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class EnumIfElseChainAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheFirstConditionIsNotABinaryExpression()
+ {
+ return AnalyzerTestRunner.VerifyAsync
("""
+ enum Color { Red, Green, Blue }
+
+ class C
+ {
+ void M(bool flag, Color c)
+ {
+ if (flag) { }
+ else if (c == Color.Green) { }
+ else if (c == Color.Blue) { }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenALaterConditionIsNotABinaryExpression()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ enum Color { Red, Green, Blue }
+
+ class C
+ {
+ void M(bool flag, Color c)
+ {
+ if (c == Color.Red) { }
+ else if (c == Color.Green) { }
+ else if (flag) { }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheComparisonIsNotAnEqualityTest()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ enum Color { Red, Green, Blue }
+
+ class C
+ {
+ void M(Color c)
+ {
+ if (c < Color.Green) { }
+ else if (c < Color.Blue) { }
+ else if (c > Color.Red) { }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenALiteralNullSitsOnTheLeftOfTheComparison()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ enum Color { Red, Green, Blue }
+
+ class C
+ {
+ void M()
+ {
+ {|E128048:if (null == Color.Red) { }
+ else if (null == Color.Green) { }
+ else if (null == Color.Blue) { }|}
+ }
+ }
+ """,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = Microsoft.CodeAnalysis.Testing.CompilerDiagnostics.None });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheRightSideOfTheComparisonIsANullLiteral()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ class C
+ {
+ void M(object o)
+ {
+ if (o == null) { }
+ else if (o != null) { }
+ else if (o == null) { }
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/EnumIfElseChainCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/EnumIfElseChainCodeFixProviderBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..30420a2
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/EnumIfElseChainCodeFixProviderBranchCoverageMoreTests.cs
@@ -0,0 +1,115 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using E128.Analyzers.Design;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CodeActions;
+using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Testing;
+using Microsoft.CodeAnalysis.Text;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class EnumIfElseChainCodeFixProviderBranchCoverageMoreTests
+{
+ ///
+ /// Applies the offered action directly and returns the resulting text. The test framework
+ /// rejects a fix that is offered and changes nothing.
+ ///
+ private static async Task ApplyOfferedFixAsync(string source)
+ {
+ var cancellationToken = TestContext.Current.CancellationToken;
+ var references = await ReferenceAssemblies.Net.Net100.ResolveAsync(LanguageNames.CSharp, cancellationToken);
+
+ using var workspace = new AdhocWorkspace();
+ var project = workspace.AddProject("TestProject", LanguageNames.CSharp)
+ .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
+ .WithMetadataReferences(references);
+ var document = project.AddDocument("Test.cs", SourceText.From(source));
+
+ var compilation = await document.Project.GetCompilationAsync(cancellationToken);
+ Assert.NotNull(compilation);
+
+ var diagnostics = await compilation
+ .WithAnalyzers([new EnumIfElseChainAnalyzer()])
+ .GetAnalyzerDiagnosticsAsync(cancellationToken);
+ var diagnostic = Assert.Single(diagnostics);
+
+ var actions = new List();
+ var context = new CodeFixContext(document, diagnostic, (action, _) => actions.Add(action), cancellationToken);
+ await new EnumIfElseChainCodeFixProvider().RegisterCodeFixesAsync(context);
+
+ var operations = await Assert.Single(actions).GetOperationsAsync(cancellationToken);
+ var changedDocument = Assert.Single(operations.OfType())
+ .ChangedSolution.GetDocument(document.Id);
+ Assert.NotNull(changedDocument);
+
+ return (await changedDocument.GetTextAsync(cancellationToken)).ToString();
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public async Task Fix_LeavesTheChainWhenAComparisonHasNoEnumConstant()
+ {
+ const string Code = """
+ enum Color { Red, Green, Blue }
+
+ class C
+ {
+ int M(Color c, Color other)
+ {
+ if (c == other)
+ {
+ return 1;
+ }
+ else if (c == Color.Green)
+ {
+ return 2;
+ }
+ else if (c == Color.Blue)
+ {
+ return 3;
+ }
+
+ return 0;
+ }
+ }
+ """;
+
+ Assert.Equal(Code, await ApplyOfferedFixAsync(Code));
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public async Task Fix_LeavesTheChainWhenAComparisonUsesALiteralZero()
+ {
+ const string Code = """
+ enum Color { Red, Green, Blue }
+
+ class C
+ {
+ int M(Color c)
+ {
+ if (c == 0)
+ {
+ return 1;
+ }
+ else if (c == Color.Green)
+ {
+ return 2;
+ }
+ else if (c == Color.Blue)
+ {
+ return 3;
+ }
+
+ return 0;
+ }
+ }
+ """;
+
+ Assert.Equal(Code, await ApplyOfferedFixAsync(Code));
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/EventSubscriptionLeakAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/EventSubscriptionLeakAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..6485ced
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/EventSubscriptionLeakAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,41 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class EventSubscriptionLeakAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyAsync(string members)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ "using System;\nclass Publisher\n{\n public event EventHandler? Changed;\n}\n"
+ + "class C : IDisposable\n{\n private readonly Publisher _publisher = new();\n private int _count;\n public event EventHandler? Own;\n"
+ + members + "}\n");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheSameRemovalAppearsTwiceAndOwnEventsAreRemoved()
+ {
+ return VerifyAsync("""
+ private void OnChanged(object? sender, EventArgs e)
+ {
+ _count++;
+ }
+
+ public void Start()
+ {
+ _publisher.Changed += OnChanged;
+ }
+
+ public void Dispose()
+ {
+ _publisher.Changed -= OnChanged;
+ _publisher.Changed -= OnChanged;
+ Own -= OnChanged;
+ }
+
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ExecuteScalarNullGuardAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ExecuteScalarNullGuardAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..bfbf09d
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ExecuteScalarNullGuardAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,95 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Design;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ExecuteScalarNullGuardAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyAsync(string body, bool lenient = false)
+ {
+ var options = lenient ? new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None } : null;
+
+ return AnalyzerTestRunner.VerifyAsync(
+ $$"""
+ using System;
+ using System.Data.Common;
+ using System.Threading.Tasks;
+
+ class Helper
+ {
+ public static int ToInt32(object value) => 0;
+ }
+
+ class C
+ {
+ static object Fetch() => 0;
+
+ static Task FetchAsync() => Task.FromResult(0);
+
+ async Task M(DbCommand cmd, Task pending)
+ {
+ {{body}}
+ }
+ }
+ """,
+ options: options);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenConvertIsCalledWithoutArguments()
+ {
+ return VerifyAsync("var x = Convert.ToInt32();", lenient: true);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheConvertCallDoesNotBind()
+ {
+ return VerifyAsync("var x = Convert.ToInt32(cmd.ExecuteScalar(), 1, 2, 3);", lenient: true);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAUserTypeDeclaresToInt32()
+ {
+ return VerifyAsync("var x = Helper.ToInt32(cmd.ExecuteScalar());");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheArgumentIsAnotherCommandMethod()
+ {
+ return VerifyAsync("var x = Convert.ToInt32(cmd.ExecuteNonQuery());");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheArgumentIsALocalMethodCall()
+ {
+ return VerifyAsync("var x = Convert.ToInt32(Fetch());");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAwaitedCallIsAnotherCommandMethod()
+ {
+ return VerifyAsync("var x = Convert.ToInt32(await cmd.ExecuteNonQueryAsync());");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAwaitedOperandIsNotAnInvocation()
+ {
+ return VerifyAsync("var x = Convert.ToInt32(await pending);");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAwaitedCallIsNotAMemberAccess()
+ {
+ return VerifyAsync("var x = Convert.ToInt32(await FetchAsync());");
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FileInfoToctouAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FileInfoToctouAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..0fc4e90
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FileInfoToctouAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,25 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FileInfoToctouAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheGuardedPathIsALiteral()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.IO;
+ class C
+ {
+ string M()
+ {
+ if (!File.Exists("data.txt")) return string.Empty;
+ return File.ReadAllText("data.txt");
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FileInfoToctouBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/FileInfoToctouBranchCoverageGapTests.cs
new file mode 100644
index 0000000..4f65226
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FileInfoToctouBranchCoverageGapTests.cs
@@ -0,0 +1,81 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FileInfoToctouBranchCoverageGapTests
+{
+ private static readonly AnalyzerTestOptions NoCompilerDiagnostics = new() { CompilerDiagnostics = CompilerDiagnostics.None };
+
+ private static Task VerifyAsync(string members, AnalyzerTestOptions? options = null)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ "using System;\nusing System.IO;\nclass FieldMarker { public bool Exists; }\nclass C\n{\n" + members + "}\n",
+ expected: null,
+ options);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheReadArgumentIsTheResultOfACall()
+ {
+ return VerifyAsync("""
+ static string Name() => "x";
+
+ string M(string path)
+ {
+ if (!File.Exists(path)) return string.Empty;
+ return File.ReadAllText(Name());
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheExistsMemberIsAField()
+ {
+ return VerifyAsync("""
+ string M(FieldMarker marker, string path)
+ {
+ if (!marker.Exists) return string.Empty;
+ return File.ReadAllText(path);
+ }
+
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheGuardedArgumentCannotBeBound()
+ {
+ return VerifyAsync(
+ """
+ string M(string path)
+ {
+ if (!File.Exists(path) || !File.Exists(missing)) return string.Empty;
+ return File.ReadAllText(missing);
+ }
+
+ """,
+ NoCompilerDiagnostics);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenFileCallsCarryNoArguments()
+ {
+ return VerifyAsync(
+ """
+ string M()
+ {
+ if (!File.Exists()) return string.Empty;
+ return File.ReadAllText();
+ }
+
+ """,
+ NoCompilerDiagnostics);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FileStreamWithoutUseAsyncAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FileStreamWithoutUseAsyncAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..ff1f6e9
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FileStreamWithoutUseAsyncAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,114 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FileStreamWithoutUseAsyncAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyWithReferencesAsync(ReferenceAssemblies references, string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ code,
+ options: new AnalyzerTestOptions
+ {
+ References = references,
+ CompilerDiagnostics = CompilerDiagnostics.None
+ });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompilationHasNoFileStream()
+ {
+ return VerifyWithReferencesAsync(
+ ReferenceAssemblies.NetStandard.NetStandard10,
+ """
+ class C
+ {
+ void M()
+ {
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompilationHasNoFileOptions()
+ {
+ return VerifyWithReferencesAsync(
+ ReferenceAssemblies.NetStandard.NetStandard10,
+ """
+ namespace System.IO
+ {
+ public class FileStream
+ {
+ public FileStream(string path, bool useAsync)
+ {
+ }
+ }
+ }
+
+ class C
+ {
+ void M(string path)
+ {
+ _ = new System.IO.FileStream(path, false);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenFileOptionsHasNoAsynchronousMember()
+ {
+ return VerifyWithReferencesAsync(
+ ReferenceAssemblies.Net.Net100,
+ """
+ namespace System.IO
+ {
+ public enum FileOptions
+ {
+ None = 0
+ }
+ }
+
+ class C
+ {
+ void M(string path)
+ {
+ _ = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, 4096, false);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAsynchronousMemberIsZero()
+ {
+ return VerifyWithReferencesAsync(
+ ReferenceAssemblies.Net.Net100,
+ """
+ namespace System.IO
+ {
+ public enum FileOptions
+ {
+ None = 0,
+ Asynchronous = 0
+ }
+ }
+
+ class C
+ {
+ void M(string path)
+ {
+ _ = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, 4096, false);
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FileSystemInfoEqualityAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FileSystemInfoEqualityAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..896bf5f
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FileSystemInfoEqualityAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,82 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Design;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FileSystemInfoEqualityAnalyzerBranchCoverageMoreTests
+{
+ private static readonly AnalyzerTestOptions IgnoreCompilerErrors = new() { CompilerDiagnostics = CompilerDiagnostics.None };
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheLeftOperandIsNullOrDefault()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.IO;
+ class C
+ {
+ bool M(FileInfo file) => null == file || default == file;
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnOperandHasNoType()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.IO;
+ class C
+ {
+ void Method()
+ {
+ }
+
+ bool M(FileInfo file) => file == Method || Method == file;
+ }
+ """,
+ expected: null,
+ options: IgnoreCompilerErrors);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForCallsThatAreNotAMemberEqualsCall()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.IO;
+ class C
+ {
+ static bool Helper(FileInfo file) => true;
+
+ bool M(FileInfo file, string name)
+ {
+ var text = file.ToString();
+ return Helper(file) && name.Equals("a") && string.Equals(name, "b") && file.FullName.Equals(name);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheEqualsReceiverHasNoType()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ class C
+ {
+ void Method()
+ {
+ }
+
+ bool M() => Method.Equals(1);
+ }
+ """,
+ expected: null,
+ options: IgnoreCompilerErrors);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FileSystemPathAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/FileSystemPathAnalyzerBranchCoverageGapTests.cs
new file mode 100644
index 0000000..7c5ed63
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FileSystemPathAnalyzerBranchCoverageGapTests.cs
@@ -0,0 +1,167 @@
+using System.Threading.Tasks;
+using E128.Analyzers.FileSystem;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FileSystemPathAnalyzerBranchCoverageGapTests
+{
+ private static Task VerifyAsync(string code, CompilerDiagnostics? compilerDiagnostics = null)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ code,
+ options: new AnalyzerTestOptions
+ {
+ MarkupOptions = MarkupOptions.UseFirstDescriptor,
+ CompilerDiagnostics = compilerDiagnostics
+ });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_ForAPathNamedParameterOfAnExpressionBodiedConstructor()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ string _stored = "";
+
+ C(string {|E128001:path|}) => _stored = path;
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForARecordWithoutAPrimaryConstructor()
+ {
+ return VerifyAsync("""
+ record R
+ {
+ public string Path { get; init; } = "";
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenLocalsDoNotDeriveFromTheParameter()
+ {
+ return VerifyAsync("""
+ using System.IO;
+
+ class C
+ {
+ static string Compute(string text) => text;
+
+ void M(string root)
+ {
+ string declaredOnly;
+ var viaCall = Compute(root);
+ var viaEmptyPath = Path.Combine();
+ var viaLiteral = Path.Combine("a", root);
+ File.ReadAllText(viaCall);
+ File.ReadAllText(viaEmptyPath);
+ File.ReadAllText(viaLiteral);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_OnlyTheParameterThatReachesFileIo()
+ {
+ return VerifyAsync("""
+ using System.IO;
+
+ class C
+ {
+ string _external = "";
+
+ void M(string {|E128001:source|}, string unused)
+ {
+ var copy = source;
+ File.ReadAllText(copy);
+ File.Exists(_external);
+ File.Exists(unused.Trim());
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAFileCallPassesTooFewArguments()
+ {
+ return VerifyAsync("""
+ using System.IO;
+
+ class C
+ {
+ void M(string root)
+ {
+ File.Exists();
+ _ = root;
+ }
+ }
+ """, CompilerDiagnostics.None);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheFileCallCannotBindToASystemIoMethod()
+ {
+ return VerifyAsync("""
+ using System.IO;
+
+ class C
+ {
+ void M(string root)
+ {
+ File.Exists(root, root);
+ }
+ }
+ """, CompilerDiagnostics.None);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheConstructorCannotBindToASystemIoOverload()
+ {
+ return VerifyAsync("""
+ using System.IO;
+
+ class C
+ {
+ void M(string root)
+ {
+ var info = new FileInfo(root, root);
+ _ = info;
+ }
+ }
+ """, CompilerDiagnostics.None);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAKnownTypeIsCreatedWithoutAnArgumentList()
+ {
+ return VerifyAsync("""
+ class FileInfo
+ {
+ public string Name { get; set; } = "";
+ }
+
+ class C
+ {
+ void M(string root)
+ {
+ var info = new FileInfo { Name = root };
+ _ = info;
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FipsDirectInstantiationAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FipsDirectInstantiationAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..7c9efc1
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FipsDirectInstantiationAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,32 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FipsDirectInstantiationAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WithTheGenericAdviceWhenTheConstructorTakesTwoArguments()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ namespace System.Security.Cryptography
+ {
+ public class TwinCng
+ {
+ public TwinCng(int first, int second) { }
+ }
+ }
+
+ class C
+ {
+ void M()
+ {
+ var a = {|E128142:new System.Security.Cryptography.TwinCng(1, 2)|};
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FipsRsaKeySizeAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/FipsRsaKeySizeAnalyzerBranchCoverageGapTests.cs
new file mode 100644
index 0000000..3743bd0
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FipsRsaKeySizeAnalyzerBranchCoverageGapTests.cs
@@ -0,0 +1,65 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FipsRsaKeySizeAnalyzerBranchCoverageGapTests
+{
+ private static Task VerifyAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_RsaKeyImportedThroughANativeHandle()
+ {
+ return VerifyAsync("""
+ using System;
+ using System.Security.Cryptography;
+ class C
+ {
+ void M(IntPtr handle)
+ {
+ var a = {|E128143:new RSAOpenSsl(handle)|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_RsaFactoryCallsThatTakeANameOrAKeySize()
+ {
+ return VerifyAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ void M()
+ {
+ var a = {|E128143:RSA.Create("RSA")|};
+ var b = {|E128143:RSA.Create("DSA")|};
+ var c = RSA.Create(3072);
+ var d = {|E128143:RSA.Create(2048)|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_ImportOnAConditionalReceiver()
+ {
+ return VerifyAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ void M(RSA? rsa, RSAParameters parameters)
+ {
+ rsa?{|E128143:.ImportParameters(parameters)|};
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FipsSymbolHelpersBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/FipsSymbolHelpersBranchCoverageGapTests.cs
new file mode 100644
index 0000000..2ff701c
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FipsSymbolHelpersBranchCoverageGapTests.cs
@@ -0,0 +1,381 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FipsSymbolHelpersBranchCoverageGapTests
+{
+ private static Task VerifyHmacAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ private static Task VerifyPbkdfAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ private static Task VerifyHashAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheKeyIsSlicedByARangeVariable()
+ {
+ return VerifyHmacAsync("""
+ using System;
+ using System.Security.Cryptography;
+ class C
+ {
+ void M(byte[] data, byte[] key, Range range)
+ {
+ var a = HMACSHA256.HashData(key.AsSpan()[range], data);
+ var b = HMACSHA256.HashData(key[range], data);
+ var c = HMACSHA256.HashData(new byte[8].AsSpan()[range], data);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_ShortKeyHeldInAChainOfLocalsWithinTheDepthLimit()
+ {
+ return VerifyHmacAsync("""
+ using System.Security.Cryptography;
+ using System.Text;
+ class C
+ {
+ void M(byte[] data)
+ {
+ var encoded1 = Encoding.UTF8.GetBytes("short");
+ var encoded2 = encoded1;
+ var encoded3 = encoded2;
+ var a = {|E128151:HMACSHA256.HashData(encoded3, data)|};
+
+ var ranged1 = (new byte[64])[..8];
+ var ranged2 = ranged1;
+ var ranged3 = ranged2;
+ var b = {|E128151:HMACSHA256.HashData(ranged3, data)|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheKeyLiesBeyondTheLocalChainDepthLimit()
+ {
+ return VerifyHmacAsync("""
+ using System.Security.Cryptography;
+ using System.Text;
+ class C
+ {
+ void M(byte[] data)
+ {
+ var encoded1 = Encoding.UTF8.GetBytes("short");
+ var encoded2 = encoded1;
+ var encoded3 = encoded2;
+ var encoded4 = encoded3;
+ var a = HMACSHA256.HashData(encoded4, data);
+
+ var ranged1 = (new byte[64])[..8];
+ var ranged2 = ranged1;
+ var ranged3 = ranged2;
+ var ranged4 = ranged3;
+ var b = HMACSHA256.HashData(ranged4, data);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnEncodedConstantExceedsTheLengthCap()
+ {
+ return VerifyHmacAsync("""
+ using System;
+ using System.Security.Cryptography;
+ using System.Text;
+ class C
+ {
+ private const string K0 = "0123456789abcdef";
+ private const string K1 = K0 + K0;
+ private const string K2 = K1 + K1;
+ private const string K3 = K2 + K2;
+ private const string K4 = K3 + K3;
+ private const string K5 = K4 + K4;
+ private const string K6 = K5 + K5;
+ private const string K7 = K6 + K6;
+ private const string K8 = K7 + K7;
+ private const string K9 = K8 + K8;
+ private const string K10 = K9 + K9;
+ private const string K11 = K10 + K10;
+ private const string K12 = K11 + K11;
+ private const string K13 = K12 + K12;
+ private const string K14 = K13 + K13;
+ private const string K15 = K14 + K14;
+ private const string K16 = K15 + K15;
+ private const string K17 = K16 + K16;
+
+ void M(byte[] data)
+ {
+ var a = HMACSHA256.HashData(Encoding.UTF8.GetBytes(K17), data);
+ var b = HMACSHA256.HashData(Convert.FromBase64String(K17), data);
+ var c = HMACSHA256.HashData(Convert.FromHexString(K17), data);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheKeyComesFromAStaticCallThatIsNotAnEncoding()
+ {
+ return VerifyHmacAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ void M(byte[] data)
+ {
+ var a = HMACSHA256.HashData(RandomNumberGenerator.GetBytes(8), data);
+ var b = HMACSHA256.HashData(System.GC.AllocateArray(8), data);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_ShortKeyFromAnIndexStartedSlice()
+ {
+ return VerifyHmacAsync("""
+ using System;
+ using System.Security.Cryptography;
+ class C
+ {
+ void M(byte[] data)
+ {
+ var a = {|E128151:HMACSHA256.HashData(new byte[40].AsSpan(^4), data)|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForSliceHelpersThatTakeNoSourceArgument()
+ {
+ return VerifyHmacAsync("""
+ using System.Security.Cryptography;
+
+ namespace System
+ {
+ public static class Odd
+ {
+ public static byte[] Slice() => new byte[8];
+ }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public static class RuntimeHelpers
+ {
+ public static T[] GetSubArray(T[] array) => array;
+ }
+ }
+
+ class C
+ {
+ void M(byte[] data)
+ {
+ var a = HMACSHA256.HashData(System.Odd.Slice(), data);
+ var b = HMACSHA256.HashData(System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray(new byte[8]), data);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheKeyIsNotAByteBuffer()
+ {
+ return VerifyHmacAsync("""
+ namespace System.Security.Cryptography
+ {
+ public static class HMACSHA256
+ {
+ public static byte[] HashData(object key, byte[] source) => source;
+ }
+ }
+
+ class C
+ {
+ void M(byte[] data)
+ {
+ var a = System.Security.Cryptography.HMACSHA256.HashData(new byte[2, 3], data);
+ var b = System.Security.Cryptography.HMACSHA256.HashData(System.Convert.ToInt32("5"), data);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheKeyOwnerIsATypeParameter()
+ {
+ return VerifyHmacAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ void M(T hmac) where T : HMAC
+ {
+ hmac.Key = new byte[8];
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_NestedConditionalsWithinTheDepthLimit()
+ {
+ return VerifyHashAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ static void Use(HashAlgorithmName name) { }
+
+ void M(bool f)
+ {
+ {|E128071:Use(f ? (f ? (f ? (f ? HashAlgorithmName.MD5 : HashAlgorithmName.SHA256) : HashAlgorithmName.SHA256) : HashAlgorithmName.SHA256) : HashAlgorithmName.SHA256)|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForNestedConditionalsBeyondTheDepthLimit()
+ {
+ return VerifyHashAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ static void Use(HashAlgorithmName name) { }
+
+ void M(bool f)
+ {
+ Use(f ? (f ? (f ? (f ? (f ? HashAlgorithmName.MD5 : HashAlgorithmName.SHA256) : HashAlgorithmName.SHA256) : HashAlgorithmName.SHA256) : HashAlgorithmName.SHA256) : HashAlgorithmName.SHA256);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForFromOidLookalikesAndUnknownOids()
+ {
+ return VerifyHashAsync("""
+ using System.Security.Cryptography;
+ static class Other
+ {
+ public static HashAlgorithmName FromOid(string oid) => HashAlgorithmName.SHA256;
+ }
+
+ class Maker
+ {
+ public HashAlgorithmName FromOid(string oid) => HashAlgorithmName.SHA256;
+ }
+
+ class C
+ {
+ static void Use(HashAlgorithmName name) { }
+
+ void M(Maker maker)
+ {
+ Use(Other.FromOid("1.2.840.113549.2.5"));
+ Use(maker.FromOid("1.2.840.113549.2.5"));
+ Use(HashAlgorithmName.FromOid("9.9.9"));
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForAStackallocWithoutSizeOrInitializer()
+ {
+ return VerifyHmacAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ void M(byte[] data)
+ {
+ var a = HMACSHA256.HashData(stackalloc byte{|CS1586:[]|}, data);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAnInitializerSetsAnotherPropertyThanIterationCount()
+ {
+ return VerifyPbkdfAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ void M(byte[] salt)
+ {
+ var a = {|E128145:{|E128145:new Rfc2898DeriveBytes("password", salt) { Salt = salt }|}|};
+ var b = {|E128145:{|E128145:new Rfc2898DeriveBytes("password", salt) { Salt = { [0] = 1 } }|}|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenALocalIsFirstUsedThroughReorderedNamedArguments()
+ {
+ return VerifyPbkdfAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ static void Use(Rfc2898DeriveBytes first, Rfc2898DeriveBytes second) { }
+
+ void M(byte[] salt)
+ {
+ var derive = {|E128145:{|E128145:new Rfc2898DeriveBytes("password", salt)|}|};
+ Use(second: derive, first: derive);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_OnlyMutableHashNameInitializers()
+ {
+ return VerifyHashAsync("""
+ using System.Security.Cryptography;
+ class C
+ {
+ static int number = 1;
+ static readonly HashAlgorithmName ReadOnlyName = HashAlgorithmName.SHA256;
+ static HashAlgorithmName SafeName = HashAlgorithmName.SHA256;
+ static HashAlgorithmName UnsafeName = {|E128071:HashAlgorithmName.MD5|};
+
+ int Count { get; set; } = 3;
+
+ HashAlgorithmName Name { get; set; } = HashAlgorithmName.SHA256;
+
+ HashAlgorithmName Other { get; set; } = {|E128071:HashAlgorithmName.MD5|};
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FipsTlsVersionAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FipsTlsVersionAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..be1e715
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FipsTlsVersionAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,79 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FipsTlsVersionAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAConvertedMaskResultIsComparedWithZero()
+ {
+ return VerifyAsync("""
+ using System.Security.Authentication;
+ class C
+ {
+ bool M(SslProtocols p)
+ {
+ return (int)(p & SslProtocols.Tls11) != 0;
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAConvertedComplementMasksAProtocolValue()
+ {
+ return VerifyAsync("""
+ using System.Security.Authentication;
+ class C
+ {
+ int M(SslProtocols p)
+ {
+ return (int)p & (int)~SslProtocols.Tls11;
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAComplementIsOredIntoAValue()
+ {
+ return VerifyAsync("""
+ using System.Security.Authentication;
+ class C
+ {
+ void M(SslProtocols p)
+ {
+ p |= ~{|E128146:SslProtocols.Tls11|};
+ p ^= ~{|E128146:SslProtocols.Tls|};
+ }
+ }
+ """);
+ }
+
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAMaskedValueIsComplemented()
+ {
+ return VerifyAsync("""
+ using System.Security.Authentication;
+ class C
+ {
+ SslProtocols M(SslProtocols p)
+ {
+ return ~({|E128146:SslProtocols.Tls11|} & p);
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FipsUnapprovedHashAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FipsUnapprovedHashAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..f8a87a4
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FipsUnapprovedHashAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,52 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FipsUnapprovedHashAnalyzerBranchCoverageMoreTests
+{
+ private const string PkcsStub = """
+ namespace System.Security.Cryptography.Pkcs
+ {
+ public class CmsSigner { public object? DigestAlgorithm { get; set; } }
+ }
+ """;
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnOrdinaryTargetIsAssigned()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ class C
+ {
+ string Label = "";
+
+ void M()
+ {
+ Label = "SHA1";
+ var local = 0;
+ local = 1;
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCmsDigestOidHasNoArgument()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.Security.Cryptography;
+ using System.Security.Cryptography.Pkcs;
+ class C
+ {
+ void M(CmsSigner signer)
+ {
+ signer.DigestAlgorithm = new Oid();
+ }
+ }
+
+ """ + PkcsStub);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FixedBufferFieldAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FixedBufferFieldAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..fa764d3
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FixedBufferFieldAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,54 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Unsafe;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FixedBufferFieldAnalyzerBranchCoverageMoreTests
+{
+ private const string Buffer = """
+ unsafe struct Buffer
+ {
+ public fixed byte Data[16];
+ }
+ """;
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheLanguageVersionPredatesInlineArrays()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ Buffer,
+ options: new AnalyzerTestOptions { AllowUnsafe = true, LanguageVersion = LanguageVersion.CSharp11 });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheRuntimeHasNoInlineArrayAttribute()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ Buffer,
+ options: new AnalyzerTestOptions
+ {
+ AllowUnsafe = true,
+ References = ReferenceAssemblies.NetStandard.NetStandard20,
+ CompilerDiagnostics = CompilerDiagnostics.None
+ });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheFixedBufferHasNoLength()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ unsafe struct Buffer
+ {
+ public fixed byte Data[0];
+ }
+ """,
+ options: new AnalyzerTestOptions { AllowUnsafe = true, CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FixedBufferFieldCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FixedBufferFieldCodeFixProviderBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..5a7e483
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FixedBufferFieldCodeFixProviderBranchCoverageMoreTests.cs
@@ -0,0 +1,59 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Unsafe;
+using Microsoft.CodeAnalysis.CSharp.Testing;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FixedBufferFieldCodeFixProviderBranchCoverageMoreTests
+{
+ private static Task VerifyFixAsync(string source, string fixedCode)
+ {
+ var test = new CSharpCodeFixTest
+ {
+ TestCode = source,
+ FixedCode = fixedCode,
+ ReferenceAssemblies = ReferenceAssemblies.Net.Net100,
+ };
+ test.SolutionTransforms.Add(CodeFixTestRunner.AllowUnsafe);
+ return test.RunAsync(TestContext.Current.CancellationToken);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_IgnoresMembersThatCannotShareTheBufferName()
+ {
+ return VerifyFixAsync(
+ """
+ unsafe struct Buffer
+ {
+ private delegate void Callback();
+
+ public Buffer(int value)
+ {
+ }
+
+ {|E128119:public fixed byte Data[4];|}
+ }
+ """,
+ """
+ unsafe struct Buffer
+ {
+ private delegate void Callback();
+
+ public Buffer(int value)
+ {
+ }
+
+ public DataBuffer Data;
+
+ [System.Runtime.CompilerServices.InlineArray(4)]
+ public struct DataBuffer
+ {
+ private byte _element0;
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FixedStringMutationAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FixedStringMutationAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..c9f6a52
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FixedStringMutationAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,125 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Unsafe;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FixedStringMutationAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyAsync(string code, bool lenient = false)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ code,
+ options: new AnalyzerTestOptions
+ {
+ AllowUnsafe = true,
+ CompilerDiagnostics = lenient ? CompilerDiagnostics.None : null,
+ });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheFixedPointerPointsAtAStruct()
+ {
+ return VerifyAsync("""
+ struct Cell
+ {
+ public int Value;
+ }
+
+ unsafe class C
+ {
+ void M(Cell[] cells)
+ {
+ fixed (Cell* pointer = cells)
+ {
+ pointer[0].Value = 1;
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheFixedDeclarationIsNotAPointerType()
+ {
+ return VerifyAsync(
+ """
+ unsafe class C
+ {
+ void M(string text)
+ {
+ fixed (var pointer = text)
+ {
+ }
+ }
+ }
+ """,
+ lenient: true);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheFixedVariableHasNoInitializer()
+ {
+ return VerifyAsync(
+ """
+ unsafe class C
+ {
+ void M()
+ {
+ fixed (char* pointer)
+ {
+ }
+ }
+ }
+ """,
+ lenient: true);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheInitializerHasNoType()
+ {
+ return VerifyAsync(
+ """
+ unsafe class C
+ {
+ void M()
+ {
+ fixed (char* pointer = null)
+ {
+ pointer[0] = 'a';
+ }
+ }
+ }
+ """,
+ lenient: true);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenThePointerIsUsedInOtherExpressionShapes()
+ {
+ return VerifyAsync(
+ """
+ unsafe class C
+ {
+ static void Read(char value) { }
+
+ void M(string text)
+ {
+ fixed (char* pointer = text)
+ {
+ var negated = -pointer;
+ var shifted = 1 + pointer;
+ Read(*(pointer - 1));
+ }
+ }
+ }
+ """,
+ lenient: true);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/FunctionPointerDelegateLifetimeAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/FunctionPointerDelegateLifetimeAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..dd2deea
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/FunctionPointerDelegateLifetimeAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,77 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Unsafe;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class FunctionPointerDelegateLifetimeAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheLocalIsStoredInAnArrayElement()
+ {
+ return VerifyAsync("""
+ using System;
+ using System.Runtime.InteropServices;
+ class C
+ {
+ void M()
+ {
+ var keep = new Action[1];
+ Action callback = () => { };
+ keep[0] = callback;
+ IntPtr pointer = Marshal.GetFunctionPointerForDelegate(callback);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnotherTypeDeclaresAMethodWithTheSameName()
+ {
+ return VerifyAsync("""
+ using System;
+ class Own
+ {
+ public static IntPtr GetFunctionPointerForDelegate(Action callback) => IntPtr.Zero;
+ }
+
+ class C
+ {
+ void M()
+ {
+ Action callback = () => { };
+ IntPtr pointer = Own.GetFunctionPointerForDelegate(callback);
+ }
+ }
+ """);
+ }
+
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheLocalIsStoredInAProperty()
+ {
+ return VerifyAsync("""
+ using System;
+ using System.Runtime.InteropServices;
+ class C
+ {
+ Action? Keep { get; set; }
+
+ void M()
+ {
+ Action callback = () => { };
+ Keep = callback;
+ IntPtr pointer = Marshal.GetFunctionPointerForDelegate(callback);
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/GeneratedRegexAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/GeneratedRegexAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..f64b30d
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/GeneratedRegexAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,71 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class GeneratedRegexAnalyzerBranchCoverageMoreTests
+{
+ private static AnalyzerTestOptions Lenient => new() { CompilerDiagnostics = CompilerDiagnostics.None };
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheAttributeConstructorTakesNoArguments()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ namespace System.Text.RegularExpressions
+ {
+ [System.AttributeUsage(System.AttributeTargets.Method)]
+ public sealed class GeneratedRegexAttribute : System.Attribute
+ {
+ public GeneratedRegexAttribute() { }
+ }
+ }
+ class C
+ {
+ [{|E128011:System.Text.RegularExpressions.GeneratedRegex|}]
+ static void First() { }
+
+ [{|E128011:System.Text.RegularExpressions.GeneratedRegex()|}]
+ static void Second() { }
+ }
+ """,
+ options: Lenient);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenANamedPropertyArgumentFollowsAPositionalTimeout()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Text.RegularExpressions;
+ partial class C
+ {
+ [GeneratedRegex(@"\d+", RegexOptions.None, 1000, Other = 1)]
+ private static partial Regex Probe();
+ private static partial Regex Probe() => null!;
+ }
+ """,
+ options: Lenient);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenThePatternIsANullLiteral()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Text.RegularExpressions;
+ partial class C
+ {
+ [GeneratedRegex(null, RegexOptions.None, 1000)]
+ private static partial Regex Probe();
+ private static partial Regex Probe() => null!;
+ }
+ """,
+ options: Lenient);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/GeneratedRegexHelpersBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/GeneratedRegexHelpersBranchCoverageGapTests.cs
new file mode 100644
index 0000000..ec0bf71
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/GeneratedRegexHelpersBranchCoverageGapTests.cs
@@ -0,0 +1,92 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class GeneratedRegexHelpersBranchCoverageGapTests
+{
+ private static Task VerifyNestedAsync(string pattern)
+ {
+ var source = "using System.Text.RegularExpressions;\n"
+ + "partial class C\n"
+ + "{\n"
+ + " [{|E128014:GeneratedRegex(@\"" + pattern + "\", RegexOptions.None, 1000)|}]\n"
+ + " private static partial Regex Probe();\n"
+ + " private static partial Regex Probe() => null!;\n"
+ + "}\n";
+ return AnalyzerTestRunner.VerifyAsync(source);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task NestedQuantifier_Fires_WhenAnEscapedBracketPairHidesTheClassEnd()
+ {
+ return VerifyNestedAsync(@"(b+\[a\])+");
+ }
+
+ [Theory]
+ [Trait("Category", "CI")]
+ [InlineData(@"\s", 0, -1)]
+ [InlineData(@"\sa", 0, -1)]
+ [InlineData(@"\s+", 0, 3)]
+ [InlineData(@"\s*?", 0, 4)]
+ [InlineData(@"a\s+", 1, 4)]
+ public void WhitespaceQuantifierEnd_ReturnsTheIndexAfterTheQuantifier(string pattern, int index, int expected)
+ {
+ Assert.Equal(expected, GeneratedRegexHelpers.WhitespaceQuantifierEnd(pattern, index));
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public void FindNestedQuantifierSpan_ReturnsEqualSpansForTheSamePattern()
+ {
+ var found = GeneratedRegexHelpers.FindNestedQuantifierSpan("(a+)+");
+ var foundAgain = GeneratedRegexHelpers.FindNestedQuantifierSpan("(a+)+");
+
+ var first = Assert.NotNull(found);
+ var second = Assert.NotNull(foundAgain);
+ Assert.Equal(new GeneratedRegexHelpers.NestedQuantifierSpan(0, 3, 4, 1, true), first);
+ Assert.True(first.Equals(second));
+ Assert.True(first.Equals((object)second));
+ Assert.Equal(first.GetHashCode(), second.GetHashCode());
+ }
+
+ [Theory]
+ [Trait("Category", "CI")]
+ [InlineData(9, 3, 4, 1, true)]
+ [InlineData(0, 9, 4, 1, true)]
+ [InlineData(0, 3, 9, 1, true)]
+ [InlineData(0, 3, 4, 9, true)]
+ [InlineData(0, 3, 4, 1, false)]
+ public void Equals_ReturnsFalse_WhenOneFieldDiffers(int open, int close, int quantifier, int length, bool singleAtom)
+ {
+ var baseline = new GeneratedRegexHelpers.NestedQuantifierSpan(0, 3, 4, 1, true);
+ var other = new GeneratedRegexHelpers.NestedQuantifierSpan(open, close, quantifier, length, singleAtom);
+
+ Assert.False(baseline.Equals(other));
+ Assert.False(baseline.Equals((object)other));
+ Assert.NotEqual(baseline.GetHashCode(), other.GetHashCode());
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public void Equals_ReturnsFalse_ForAValueOfAnotherType()
+ {
+ var span = new GeneratedRegexHelpers.NestedQuantifierSpan(0, 3, 4, 1, true);
+
+ Assert.False(span.Equals("text"));
+ Assert.False(span.Equals(null));
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public void ToString_ListsEveryField()
+ {
+ var span = new GeneratedRegexHelpers.NestedQuantifierSpan(1, 2, 3, 4, true);
+
+ Assert.Equal(
+ "NestedQuantifierSpan(open: 1, close: 2, quantifier: 3, length: 4, singleAtomBody: True)",
+ span.ToString());
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/GuidNewGuidTempPathE128AnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/GuidNewGuidTempPathE128AnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..bf9bcb2
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/GuidNewGuidTempPathE128AnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,57 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Style;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class GuidNewGuidTempPathE128AnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheInterpolationFeedsAnObjectCreation()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ using System.IO;
+ class C
+ {
+ FileInfo M() => new FileInfo($"{Guid.NewGuid()}.tmp");
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheInterpolationFeedsAnUnqualifiedCall()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ class C
+ {
+ static string Name(string value) => value;
+
+ string M() => Name($"{Guid.NewGuid()}.tmp");
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheInterpolationFeedsAnotherPathMethodOrReceiver()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ using System.IO;
+ class Paths
+ {
+ public static string Combine(string value) => value;
+ }
+ class C
+ {
+ string M(string root) => Path.Join(root, $"{Guid.NewGuid()}.tmp");
+
+ string N() => Paths.Combine($"{Guid.NewGuid()}.tmp");
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/HardcodedSecretAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/HardcodedSecretAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..bed72e2
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/HardcodedSecretAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,79 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class HardcodedSecretAnalyzerBranchCoverageMoreTests
+{
+ private static Task VerifyAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheLiteralIsAParameterDefaultOrAMethodExpressionBody()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ string Password(string secret = "Sup3rS3cret!") => secret;
+
+ string Token() => "Sup3rS3cret!";
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenAnIndexerGetterReturnsTheLiteral()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ string this[int index]
+ {
+ get => "Sup3rS3cret!";
+ }
+
+ string this[string key]
+ {
+ get
+ {
+ return "Sup3rS3cret!";
+ }
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAssignmentTargetIsParenthesized()
+ {
+ return VerifyAsync("""
+ class C
+ {
+ void M()
+ {
+ string password;
+ (password) = "Sup3rS3cret!";
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenATopLevelReturnCarriesTheLiteral()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ return "Sup3rS3cret!";
+ """,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+
+}
diff --git a/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerBranchCoverageGapTests.cs
new file mode 100644
index 0000000..6905a38
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerBranchCoverageGapTests.cs
@@ -0,0 +1,177 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class HttpBodyReadWithoutSizeBoundAnalyzerBranchCoverageGapTests
+{
+ private const string Length = "response.Content.Headers.ContentLength";
+
+ private const string Read = "_ = await response.Content.ReadAsStringAsync();";
+
+ private const string ReportedRead = "_ = await {|E128227:response.Content.ReadAsStringAsync()|};";
+
+ private static Task VerifyAsync(string members)
+ {
+ var source = $$"""
+ using System;
+ using System.Net.Http;
+ using System.Threading;
+ using System.Threading.Tasks;
+
+ class C
+ {
+ {{members}}
+ }
+ """;
+
+ return AnalyzerTestRunner.VerifyAsync(source);
+ }
+
+ private static string Method(string name, string body)
+ {
+ return $$"""
+ async Task {{name}}(HttpResponseMessage response, bool flag, int value)
+ {
+ {{body}}
+ }
+ """;
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheGuardSitsInABlockInsideASwitchSection()
+ {
+ var guard = $"if ({Length} is null or > 100) {{ throw new InvalidOperationException(); }}";
+
+ return VerifyAsync(Method(
+ "InSwitchSection",
+ $" switch (value)\n {{\n case 1:\n value++;\n {{ {guard} }}\n break;\n default:\n break;\n }}\n {ReportedRead}"));
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheGuardAndTheReadShareASwitchSection()
+ {
+ var guard = $"if ({Length} is null or > 100) {{ throw new InvalidOperationException(); }}";
+
+ return VerifyAsync(Method(
+ "SameSection",
+ $" switch (value)\n {{\n case 1:\n {guard}\n {Read}\n break;\n }}"));
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Handles_GuardsWhoseOperandsAreUnknownWhenTheLengthIsNull()
+ {
+ var methods = string.Join(
+ "\n\n",
+ Method("BothRelational", $" if ({Length} > 1 || {Length} < 5) {{ return; }}\n {ReportedRead}"),
+ Method("UnknownThenNull", $" if (flag || {Length} == null) {{ return; }}\n {Read}"),
+ Method("UnknownBoth", $" if (flag || !flag) {{ return; }}\n {ReportedRead}"),
+ Method("RelationalOrUnknown", $" if ({Length} > 1 || flag) {{ return; }}\n {ReportedRead}"),
+ Method("ReadInThenWhenUnknown", $" if (flag || {Length} > 100)\n {{\n {ReportedRead}\n }}"),
+ Method("UnknownAndNull", $" if (flag && {Length} == null) {{ return; }}\n {ReportedRead}"));
+
+ return VerifyAsync(methods);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Handles_ThenBranchesThatContainNestedFunctionsOrBlocks()
+ {
+ var methods = string.Join(
+ "\n\n",
+ Method("LambdaOnly", $" if ({Length} is null or > 100) {{ Action leave = () => {{ return; }}; leave(); }}\n {ReportedRead}"),
+ Method("LocalFunctionOnly", $" if ({Length} is null or > 100) {{ void Leave() {{ return; }} Leave(); }}\n {ReportedRead}"),
+ Method("NestedBlock", $" if ({Length} is null or > 100) {{ {{ return; }} }}\n {Read}"));
+
+ return VerifyAsync(methods);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Handles_LocalsWithoutAnInitializerAndConditionsOnOtherMembers()
+ {
+ var methods = string.Join(
+ "\n\n",
+ Method("Uninitialized", $" int unset;\n unset = value;\n if ({Length} is null or > 100) {{ return; }}\n {Read}"),
+ Method("MethodGroupInCondition", $" if (response.ToString() is null) {{ return; }}\n {ReportedRead}"));
+
+ return VerifyAsync(methods);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheReceiverIsAPostfixIncrement()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.IO;
+ using System.Net;
+ using System.Net.Http;
+ using System.Threading.Tasks;
+
+ sealed class Counted : HttpContent
+ {
+ public static Counted operator ++(Counted content) => content;
+
+ protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => Task.CompletedTask;
+
+ protected override bool TryComputeLength(out long length)
+ {
+ length = 0;
+ return false;
+ }
+ }
+
+ class C
+ {
+ async Task M(Counted content)
+ {
+ _ = await {|E128227:(content++).ReadAsStringAsync()|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheReadCallDoesNotBind()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ using System.Threading.Tasks;
+
+ class C
+ {
+ async Task M()
+ {
+ _ = await missing.ReadAsStringAsync();
+ }
+ }
+ """,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCompilationHasNoHttpContent()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ """
+ class Own
+ {
+ public int ReadAsStringAsync() => 0;
+ }
+
+ class C
+ {
+ int M(Own own) => own.ReadAsStringAsync();
+ }
+ """,
+ options: new AnalyzerTestOptions { References = ReferenceAssemblies.NetStandard.NetStandard10 });
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/HttpClientCertificateBypassBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/HttpClientCertificateBypassBranchCoverageGapTests.cs
new file mode 100644
index 0000000..9f17e6b
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/HttpClientCertificateBypassBranchCoverageGapTests.cs
@@ -0,0 +1,182 @@
+using System.IO;
+using System.Threading.Tasks;
+using E128.Analyzers.Security;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class HttpClientCertificateBypassBranchCoverageGapTests
+{
+ // Only System.Runtime: no HttpClientHandler, no SslClientAuthenticationOptions and no SslStream.
+ private static readonly ReferenceAssemblies MinimalReferences = new(
+ "netstandard1.5",
+ new PackageIdentity("System.Runtime", "4.3.1"),
+ Path.Combine("ref", "netstandard1.5"));
+
+ private static Task VerifyAsync(string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(code);
+ }
+
+ private static Task VerifyAsync(ReferenceAssemblies references, string code)
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ code,
+ options: new AnalyzerTestOptions { References = references });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenNoCertificateValidationTypesExist()
+ {
+ return VerifyAsync(MinimalReferences, "class C { }");
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenOnlyTheHandlerAndSslStreamTypesExist()
+ {
+ return VerifyAsync(ReferenceAssemblies.NetStandard.NetStandard20, """
+ using System.Net.Http;
+ using System.Net.Security;
+ using System.IO;
+
+ class C
+ {
+ void M(HttpClientHandler handler, Stream stream)
+ {
+ {|E128156:handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true|};
+ var ssl = {|E128156:new SslStream(stream, false, (_, _, _, _) => true)|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_ForSslStreamCreationsThatDoNotBind()
+ {
+ return VerifyAsync("""
+ using System.Net.Security;
+
+ class C
+ {
+ void M()
+ {
+ var a = new {|CS1729:SslStream|}();
+ var b = new {|CS0246:Missing|}();
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAssignedMemberIsAFieldOrUnresolved()
+ {
+ return VerifyAsync("""
+ using System;
+
+ class Holder
+ {
+ public Func? ServerCertificateCustomValidationCallback;
+ }
+
+ class C
+ {
+ void M(Holder holder)
+ {
+ holder.ServerCertificateCustomValidationCallback = _ => true;
+ holder.{|CS1061:RemoteCertificateValidationCallback|} = _ => true;
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenTheCallbackIsAMemberAccessToAFieldThatHoldsAnAcceptAllLambda()
+ {
+ return VerifyAsync("""
+ using System.Net.Security;
+
+ static class Callbacks
+ {
+ public static readonly RemoteCertificateValidationCallback AcceptAll = (_, _, _, _) => true;
+
+ public static readonly RemoteCertificateValidationCallback Inspect = (_, _, _, errors) => errors == SslPolicyErrors.None;
+ }
+
+ class C
+ {
+ void M(SslClientAuthenticationOptions options)
+ {
+ options.RemoteCertificateValidationCallback = Callbacks.Inspect;
+ {|E128156:options.RemoteCertificateValidationCallback = Callbacks.AcceptAll|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheNamedMethodHasNoBody()
+ {
+ return VerifyAsync("""
+ using System.Net.Security;
+ using System.Security.Cryptography.X509Certificates;
+
+ abstract class Base
+ {
+ protected abstract bool AcceptAbstract(object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors);
+
+ static extern bool AcceptExtern(object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors);
+
+ void M(SslClientAuthenticationOptions options)
+ {
+ static extern bool AcceptLocal(object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors);
+
+ options.RemoteCertificateValidationCallback = AcceptAbstract;
+ options.RemoteCertificateValidationCallback = AcceptExtern;
+ options.RemoteCertificateValidationCallback = AcceptLocal;
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCallbackBlockIsASingleStatementThatIsNotAReturn()
+ {
+ return VerifyAsync("""
+ using System;
+ using System.Net.Security;
+
+ class C
+ {
+ void M(SslClientAuthenticationOptions options)
+ {
+ options.RemoteCertificateValidationCallback = (_, _, _, _) => { throw new InvalidOperationException(); };
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenOnlySslStreamExists()
+ {
+ return VerifyAsync(ReferenceAssemblies.NetFramework.Net20.Default, """
+ using System.Net.Security;
+
+ class C
+ {
+ void M(System.IO.Stream stream)
+ {
+ var ssl = {|E128156:new SslStream(stream, false, delegate { return true; })|};
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/HttpClientMissingOceCatchAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/HttpClientMissingOceCatchAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..eee8727
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/HttpClientMissingOceCatchAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,76 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Reliability;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class HttpClientMissingOceCatchAnalyzerBranchCoverageMoreTests
+{
+ private const string Header = "using System;\nusing System.Net.Http;\nusing System.Threading.Tasks;\n";
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheAsyncMethodHasAnExpressionBody()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ Header + """
+ class C
+ {
+ private readonly HttpClient _client = new();
+
+ async Task M() => await _client.GetAsync("u");
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheRequestMethodCallDoesNotResolve()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ Header + """
+ class C
+ {
+ async Task M(Missing client)
+ {
+ try
+ {
+ await client.GetAsync("u");
+ }
+ catch (Exception)
+ {
+ }
+ }
+ }
+ """,
+ options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None });
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenAFilteredCatchWithoutTypePrecedesTheBroadCatch()
+ {
+ return AnalyzerTestRunner.VerifyAsync(
+ Header + """
+ class C
+ {
+ private readonly HttpClient _client = new();
+
+ async Task M(bool flag)
+ {
+ try
+ {
+ await _client.GetAsync("u");
+ }
+ catch when (flag)
+ {
+ }
+ {|E128051:catch (Exception)|}
+ {
+ }
+ }
+ }
+ """);
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/HttpClientResponseHeadersReadCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/HttpClientResponseHeadersReadCodeFixProviderBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..3852cab
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/HttpClientResponseHeadersReadCodeFixProviderBranchCoverageMoreTests.cs
@@ -0,0 +1,100 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CodeActions;
+using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Testing;
+using Microsoft.CodeAnalysis.Text;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class HttpClientResponseHeadersReadCodeFixProviderBranchCoverageMoreTests
+{
+ ///
+ /// Applies the offered action directly and returns the resulting text. The test framework
+ /// rejects a fix that is offered and changes nothing.
+ ///
+ private static async Task ApplyOfferedFixAsync(string source)
+ {
+ var cancellationToken = TestContext.Current.CancellationToken;
+ var references = await ReferenceAssemblies.Net.Net100.ResolveAsync(LanguageNames.CSharp, cancellationToken);
+
+ using var workspace = new AdhocWorkspace();
+ var project = workspace.AddProject("TestProject", LanguageNames.CSharp)
+ .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
+ .WithMetadataReferences(references);
+ var document = project.AddDocument("Test.cs", SourceText.From(source));
+
+ var compilation = await document.Project.GetCompilationAsync(cancellationToken);
+ Assert.NotNull(compilation);
+
+ var diagnostics = await compilation
+ .WithAnalyzers([new HttpClientResponseHeadersReadAnalyzer()])
+ .GetAnalyzerDiagnosticsAsync(cancellationToken);
+ var diagnostic = Assert.Single(diagnostics);
+
+ var actions = new List();
+ var context = new CodeFixContext(document, diagnostic, (action, _) => actions.Add(action), cancellationToken);
+ await new HttpClientResponseHeadersReadCodeFixProvider().RegisterCodeFixesAsync(context);
+
+ var operations = await Assert.Single(actions).GetOperationsAsync(cancellationToken);
+ var changedDocument = Assert.Single(operations.OfType())
+ .ChangedSolution.GetDocument(document.Id);
+ Assert.NotNull(changedDocument);
+
+ return (await changedDocument.GetTextAsync(cancellationToken)).ToString();
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Fix_AppendsTheOptionWhenTheCallHasNoCancellationToken()
+ {
+ return CodeFixTestRunner.RunAsync(
+ """
+ using System.Net.Http;
+ using System.Threading.Tasks;
+ class C
+ {
+ async Task M(HttpClient client)
+ {
+ var response = await {|E128010:client.GetAsync("https://example.com")|};
+ }
+ }
+ """,
+ """
+ using System.Net.Http;
+ using System.Threading.Tasks;
+ class C
+ {
+ async Task M(HttpClient client)
+ {
+ var response = await client.GetAsync("https://example.com", HttpCompletionOption.ResponseHeadersRead);
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public async Task Fix_LeavesACallWhoseNamedArgumentsWouldNotBindAfterTheInsert()
+ {
+ const string Code = """
+ using System.Net.Http;
+ using System.Threading;
+ using System.Threading.Tasks;
+ class C
+ {
+ async Task M(HttpClient client, CancellationToken ct)
+ {
+ await client.GetAsync(cancellationToken: ct, requestUri: "https://example.com");
+ }
+ }
+ """;
+
+ Assert.Equal(Code, await ApplyOfferedFixAsync(Code));
+ }
+}
diff --git a/tests/E128.Analyzers.Tests/ImmutableArrayCreateToArrayAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ImmutableArrayCreateToArrayAnalyzerBranchCoverageMoreTests.cs
new file mode 100644
index 0000000..2eb6766
--- /dev/null
+++ b/tests/E128.Analyzers.Tests/ImmutableArrayCreateToArrayAnalyzerBranchCoverageMoreTests.cs
@@ -0,0 +1,104 @@
+using System.Threading.Tasks;
+using E128.Analyzers.Performance;
+using Microsoft.CodeAnalysis.Testing;
+using Xunit;
+
+namespace E128.Analyzers.Tests;
+
+public sealed class ImmutableArrayCreateToArrayAnalyzerBranchCoverageMoreTests
+{
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Reports_WhenCreateIsCalledThroughAStaticImport()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.Collections.Generic;
+ using System.Collections.Immutable;
+ using static System.Collections.Immutable.ImmutableArray;
+ class C
+ {
+ void M(List list)
+ {
+ var arr = {|E128083:Create(list.ToArray())|};
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCalledMethodIsNotACreateCall()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.Immutable;
+ using System.Linq;
+ class C
+ {
+ static Func Pick() => values => values.Length;
+
+ void M(List list)
+ {
+ var count = Pick()(list.ToArray());
+ var arr = ImmutableArray.Create(list.ToList());
+ }
+ }
+ """);
+ }
+
+ [Fact]
+ [Trait("Category", "CI")]
+ public Task Silent_WhenTheCreateMethodBelongsToAnotherType()
+ {
+ return AnalyzerTestRunner.VerifyAsync("""
+ using System.Collections.Generic;
+ class Factory
+ {
+ public static int Create(int[] values) => values.Length;
+ }
+ class C
+ {
+ int M(List