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 list) => Factory.Create(list.ToArray()); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallsDoNotBind() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + using System.Collections.Immutable; + class C + { + void M(List list) + { + var first = Missing.Create(list.ToArray()); + var second = ImmutableArray.CreateRange(missing.ToArray()); + } + } + """, + expected: null, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFrameworkHasNoImmutableCollectionsMarshal() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M() + { + } + } + """, + expected: null, + options: new AnalyzerTestOptions { References = ReferenceAssemblies.NetStandard.NetStandard20 }); + } +} diff --git a/tests/E128.Analyzers.Tests/ImplicitStateMachineAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/ImplicitStateMachineAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..99f051e --- /dev/null +++ b/tests/E128.Analyzers.Tests/ImplicitStateMachineAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,153 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ImplicitStateMachineAnalyzerBranchCoverageGapTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAWriteTargetsAFieldOfAMetadataType() + { + return VerifyAsync(""" + sealed class Machine + { + private bool _a; + private bool _b; + private bool _c; + + public void Run() + { + var pair = (false, false); + pair.Item1 = true; + pair.Item2 = false; + _ = pair; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForInterlockedWritesInATypeThatIsNotAnalyzed() + { + return VerifyAsync(""" + using System.Threading; + + sealed record Gate + { + private bool _a; + private bool _b; + private bool _c; + + public void Open() + { + Interlocked.Exchange(ref _a, true); + Interlocked.Exchange(ref _b, false); + Interlocked.Exchange(ref _c, true); + } + + public void Close() + { + Interlocked.Exchange(ref _a, false); + Interlocked.Exchange(ref _b, true); + Interlocked.Exchange(ref _c, false); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenConditionPatternsDoNotNegateAFlag() + { + return VerifyAsync(""" + sealed class Machine + { + private bool _a; + private bool _b; + private bool _c; + private bool _d; + + public void SetA(bool value) { _a = value; } + public void SetB(bool value) { _b = value; } + public void SetC(bool value) { _c = value; } + public void SetD(bool value) { _d = value; } + + public void Run() + { + if (_a && _b is bool seen && _c && _d is true or false) + { + _ = seen; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAFlagCarriesAnAttributeThatIsNotObsolete() + { + return VerifyAsync(""" + sealed class {|E128218:Machine|} + { + [System.NonSerialized] + private bool _a; + private bool _b; + private bool _c; + + public void Merge(bool x) + { + _a |= x; + _b &= x; + _c |= x; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenFlagsOutsideTheClusterAreOnlySetOneWay() + { + return VerifyAsync(""" + sealed class Machine + { + private bool _a; + private bool _b; + private bool _onlyTrue; + private bool _onlyFalse; + + public void Start() { _a = true; _b = false; _onlyTrue = true; _onlyFalse = false; } + public void Stop() { _a = false; _b = true; _onlyTrue = true; _onlyFalse = false; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAForwardingAccessorTouchesAnotherInstance() + { + return VerifyAsync(""" + sealed class Machine + { + private readonly Machine _other = new(); + private bool _a; + private bool _b; + private bool _c; + + public bool A { get => _other._a; set => _other._a = value; } + + public void X() { A = true; _b = true; _c = true; } + public void Y() { A = false; _b = false; _c = false; } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..89da5bf --- /dev/null +++ b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,40 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InsecureRandomInCryptoContextAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string code, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(code, expected: null, options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_CallsOnARandomReachedThroughPropertiesThatAreNotRandomShared() + { + return VerifyAsync(""" + using System; + class Holder + { + public Random Rng { get; } = new(); + public static Random Instance { get; } = new(); + } + class Other + { + public static Random Shared { get; } = new(); + } + class C + { + void M(Holder holder) + { + var token = {|E128075:holder.Rng.Next()|}; + var pin = {|E128075:Holder.Instance.Next()|}; + var otp = {|E128075:Other.Shared.Next()|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextBranchCoverageGapTests.cs new file mode 100644 index 0000000..f45d507 --- /dev/null +++ b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextBranchCoverageGapTests.cs @@ -0,0 +1,166 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InsecureRandomInCryptoContextBranchCoverageGapTests +{ + private static Task VerifyAsync(string code, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + code, + expected: null, + options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenANextBytesOverloadTakesNoBuffer() + { + return VerifyAsync(""" + using System; + sealed class FixedRandom : Random + { + public void NextBytes() { } + } + + class C + { + private readonly FixedRandom _random = new(); + + void M() + { + _random.NextBytes(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheValueReachesASensitiveNameThroughAPropertyRead() + { + return VerifyAsync(""" + using System; + class C + { + void M() + { + var tokenLength = {|E128075:new Random()|}.Next().ToString().Length; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheValueReachesASensitiveNameThroughAFieldRead() + { + return VerifyAsync(""" + using System; + struct Pair + { + public int Value; + } + + sealed class PairRandom : Random + { + public Pair NextPair() => default; + } + + class C + { + void M() + { + var tokenValue = {|E128075:new PairRandom()|}.NextPair().Value; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheValueIsOnlyTheReceiverOfAnAssignmentTarget() + { + return VerifyAsync(""" + using System; + class Holder + { + public int Token { get; set; } + } + + sealed class HolderRandom : Random + { + public Holder NextHolder() => new(); + } + + class C + { + void M() + { + new HolderRandom().NextHolder().Token = 1; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenARandomValueIsAssignedToASensitiveProperty() + { + return VerifyAsync(""" + using System; + class C + { + int Token { get; set; } + + void M() + { + Token = {|E128075:new Random()|}.Next(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenACryptographyNameDoesNotBind() + { + return VerifyAsync( + """ + using System; + class C + { + void M() + { + var number = new Random().Next(); + RandomNumberGenerator.Fill(null); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Handles_ARandomValuePassedToCallsThatReturnAStringOrNothing() + { + return VerifyAsync(""" + using System; + class C + { + static string Format(int value) => value.ToString(); + + static void Consume(int value) { } + + void M(Random random) + { + var tokenText = Format({|E128075:random.Next()|}); + Consume(random.Next()); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..8eeea9e --- /dev/null +++ b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,63 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InsecureRandomInCryptoContextCodeFixProviderBranchCoverageGapTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsTheExistingCryptographyUsing() + { + return CodeFixTestRunner.RunAsync( + """ + using System; + using System.Security.Cryptography; + class C + { + int M() + { + var token = {|E128075:Random.Shared|}.Next(1, 7); + return token; + } + } + """, + """ + using System; + using System.Security.Cryptography; + class C + { + int M() + { + var token = RandomNumberGenerator.GetInt32(1, 7); + return token; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheNextCallBindsToAnExtensionMethod() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System; + + static class RandomExtensions + { + public static int Next(this Random random, string label) => label.Length; + } + + class C + { + int M() + { + var token = {|E128075:Random.Shared|}.Next("label"); + return token; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/JsonDocumentLifetimeAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/JsonDocumentLifetimeAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..4c48058 --- /dev/null +++ b/tests/E128.Analyzers.Tests/JsonDocumentLifetimeAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,51 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class JsonDocumentLifetimeAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string source) + { + return AnalyzerTestRunner.VerifyAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenParseIsCalledOnADynamicReceiver() + { + return VerifyAsync(""" + class C + { + void M(dynamic parser) + { + var result = parser.Parse("{}"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnExpressionBodiedMethodLeaksTheRootElementFromALambda() + { + return VerifyAsync(""" + using System; + using System.Text.Json; + class C + { + static JsonElement Keep; + + static int Run(Func action) => action(); + + int M() => Run(() => + { + using var doc = {|E128041:JsonDocument.Parse("{}")|}; + Keep = doc.RootElement; + return 0; + }); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/LargeStructByValueAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/LargeStructByValueAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..de31e11 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LargeStructByValueAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,89 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LargeStructByValueAnalyzerBranchCoverageMoreTests +{ + private static AnalyzerTestOptions Lenient => new() { CompilerDiagnostics = CompilerDiagnostics.None }; + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheParameterCarriesAnUnrelatedModifier() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M({|E128217:scoped Big value|}) + { + } + } + """, + options: Lenient); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheRuntimeLacksInlineArrayAttribute() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M({|E128217:Big value|}) + { + } + } + """, + options: new AnalyzerTestOptions { References = ReferenceAssemblies.NetStandard.NetStandard20 }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnInlineArrayStructHasNoElementField() + { + return AnalyzerTestRunner.VerifyAsync( + """ + [System.Runtime.CompilerServices.InlineArray(4)] + struct Empty + { + } + + struct Holder + { + public Empty Tail; + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M({|E128217:Holder value|}) + { + } + } + """, + options: Lenient); + } +} diff --git a/tests/E128.Analyzers.Tests/LazyFieldThreadSafetyAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/LazyFieldThreadSafetyAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..d35df1a --- /dev/null +++ b/tests/E128.Analyzers.Tests/LazyFieldThreadSafetyAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,87 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LazyFieldThreadSafetyAnalyzerBranchCoverageGapTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheNamedModeFollowsTheNamedFactory() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Threading; + + class C + { + private static readonly Lazy {|E128194:Value = new Lazy(valueFactory: () => 1, mode: LazyThreadSafetyMode.None)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherModeTypeWithoutANoneMemberIsDeclared() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + + namespace System.Threading + { + public enum LazyThreadSafetyMode { Other = 7 } + } + + class C + { + private static readonly Lazy {|E128194:Value = new Lazy(() => 1, false)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherModeTypeHasANonConstantNoneField() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + + namespace System.Threading + { + public sealed class LazyThreadSafetyMode + { + public static readonly int None = 0; + } + } + + class C + { + private static readonly Lazy {|E128194:Value = new Lazy(() => 1, false)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherModeTypeHasALongNoneConstant() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + + namespace System.Threading + { + public enum LazyThreadSafetyMode : long { None = 0 } + } + + class C + { + private static readonly Lazy {|E128194:Value = new Lazy(() => 1, false)|}; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/LinearLookupInLoopCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/LinearLookupInLoopCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..3112f54 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LinearLookupInLoopCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,92 @@ +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 LinearLookupInLoopCodeFixProviderBranchCoverageMoreTests +{ + /// + /// 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 LinearLookupInLoopAnalyzer()]) + .GetAnalyzerDiagnosticsAsync(cancellationToken); + var diagnostic = Assert.Single(diagnostics); + + var actions = new List(); + var context = new CodeFixContext(document, diagnostic, (action, _) => actions.Add(action), cancellationToken); + await new LinearLookupInLoopCodeFixProvider().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_LeavesTheCodeWhenTheReceiverIsAMemberAccess() + { + const string Code = """ + using System.Collections.Generic; + class C + { + private readonly List items = new(); + + void M(List source) + { + foreach (var item in source) + { + _ = this.items.Contains(item); + } + } + } + """; + + Assert.Equal(Code, await ApplyOfferedFixAsync(Code)); + } + + [Fact] + [Trait("Category", "CI")] + public async Task Fix_LeavesTheCodeWhenTheLookupLambdaIsAFieldInitializer() + { + const string Code = """ + using System.Collections.Generic; + using System.Linq; + class C + { + static readonly List Other = new(); + static readonly List Source = new(); + static readonly int[] Result = Source.Where(x => Other.Contains(x)).ToArray(); + } + """; + + Assert.Equal(Code, await ApplyOfferedFixAsync(Code)); + } +} diff --git a/tests/E128.Analyzers.Tests/LoggerArgumentGuardAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/LoggerArgumentGuardAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..e2ca849 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LoggerArgumentGuardAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,81 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LoggerArgumentGuardAnalyzerBranchCoverageMoreTests +{ + private static readonly ReferenceAssemblies Net100WithLogging = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.Logging.Abstractions", "10.0.13")]); + + private static Task VerifyAsync(string code, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + code, + expected: null, + options ?? new AnalyzerTestOptions { References = Net100WithLogging }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFrameworkHasNoLoggerExtensions() + { + return VerifyAsync( + """ + class C + { + void M() + { + } + } + """, + new AnalyzerTestOptions()); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLogCallDoesNotBind() + { + return VerifyAsync( + """ + class C + { + void M(object logger, int count) + { + logger.LogInformation($"count {count}"); + } + } + """, + new AnalyzerTestOptions { References = Net100WithLogging, CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardLivesInALocalFunctionOrIsAssignedLater() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, int count) + { + bool Enabled() => logger.IsEnabled(LogLevel.Information); + + if (Enabled()) + { + {|E128122:logger.LogInformation($"count {count}")|}; + } + + bool later; + later = logger.IsEnabled(LogLevel.Warning); + if (later) + { + {|E128122:logger.LogWarning($"count {count}")|}; + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/LoopContextBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/LoopContextBranchCoverageMoreTests.cs new file mode 100644 index 0000000..0a7f9c4 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LoopContextBranchCoverageMoreTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LoopContextBranchCoverageMoreTests +{ + private const string Prelude = """ + using System; + + class C + { + int[] items = new int[4]; + (int, int)[] pairs = new (int, int)[4]; + int Use(int value) { return value; } + + """; + + private static SyntaxNode Parse(string members) + { + var tree = CSharpSyntaxTree.ParseText( + Prelude + members + "\n}\n", + cancellationToken: TestContext.Current.CancellationToken); + return tree.GetRoot(TestContext.Current.CancellationToken); + } + + private static T Find(SyntaxNode root, string text) + where T : SyntaxNode + { + return root.DescendantNodes().OfType().First(n => string.Equals(n.ToString(), text, StringComparison.Ordinal)); + } + + [Fact] + [Trait("Category", "CI")] + public void FindEnclosingLoop_IsNullForANodeOutsideEveryLoop() + { + var root = Parse("void M() { Use(1); }"); + Assert.Null(LoopContext.FindEnclosingLoop(Find(root, "Use(1)"))); + } + + [Fact] + [Trait("Category", "CI")] + public void IsWithinAnyLoop_IsFalseForANodeInAFieldInitializer() + { + var root = Parse("int field = Use(1);"); + Assert.False(LoopContext.IsWithinAnyLoop(Find(root, "Use(1)"))); + } + + [Fact] + [Trait("Category", "CI")] + public void IsInsideLoopBody_IsFalseForANodeInAnExpressionBodiedProperty() + { + var root = Parse("int P => Use(1);"); + Assert.False(LoopContext.IsInsideLoopBody(Find(root, "Use(1)"))); + } + + [Fact] + [Trait("Category", "CI")] + public void IsInsideLoopBody_IsFalseForANodeInAForLoopWithoutACondition() + { + var root = Parse("void M() { for (var i = Use(1); ; i++) { } }"); + Assert.False(LoopContext.IsInsideLoopBody(Find(root, "Use(1)"))); + } + + [Fact] + [Trait("Category", "CI")] + public void IsInsideLoopBody_IsFalseForTheTypeOfAForeachVariable() + { + var root = Parse("void M() { foreach (int item in items) { } }"); + var type = root.DescendantNodes().OfType().Single().Type; + Assert.False(LoopContext.IsInsideLoopBody(type)); + } + + [Fact] + [Trait("Category", "CI")] + public void IsInsideLoopBody_CountsTheDeconstructedForeachVariable() + { + var root = Parse("void M() { foreach (var (a, b) in pairs) { } }"); + var variable = root.DescendantNodes().OfType().Single().Variable; + Assert.True(LoopContext.IsInsideLoopBody(variable)); + } + + [Fact] + [Trait("Category", "CI")] + public void FindEnclosingLoopBody_IsNullForTheDeconstructedForeachVariable() + { + var root = Parse("void M() { foreach (var (a, b) in pairs) { } }"); + var variable = root.DescendantNodes().OfType().Single().Variable; + Assert.Null(LoopContext.FindEnclosingLoopBody(variable)); + } +} diff --git a/tests/E128.Analyzers.Tests/LowValueTestAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/LowValueTestAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..b9c32c3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LowValueTestAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,418 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LowValueTestAnalyzerBranchCoverageGapTests +{ + private static readonly ReferenceAssemblies Net100WithXunit = ReferenceAssemblies.Net.Net100 + .AddPackages([ + new PackageIdentity("xunit.v3.core", "3.2.2"), + new PackageIdentity("xunit.v3.assert", "3.2.2") + ]); + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions { References = Net100WithXunit }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTestCallsACheckMethodThatReturnsAValue() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Rule + { + public bool Check(int value) => value > 0; + } + + public sealed class Subject + { + [Fact] + public void Should_AcceptThePositiveValue() + { + var rule = new Rule(); + rule.Check(1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_BareSizeWhenTheMemberAccessesAreTypesFixturesOrUnresolved() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Subject + { + private readonly int fixture = 2; + + [Fact] + public void {|E128107:Should_ReadFixture|}() + { + var type = typeof(System.String); + var right = this.fixture; + Assert.Equal(2, right); + } + + [Fact] + public void {|E128107:Should_ReadMissingMember|}() + { + var left = 1; + var right = left.{|CS1061:Missing|}; + Assert.NotEqual(0, 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheAssertedLiteralIsNotAReturnedProductionLiteral() + { + return VerifyAsync(""" + using System; + using Xunit; + + public delegate int Transform(int value); + + public static class Calc + { + [Obsolete("legacy")] + public static int Compute(int left, int right = 5) + { + var offset = 9; + return left + right + offset; + } + + public static Transform Make() => value => value + 7; + } + + public sealed class Subject + { + [Fact] + public void Should_ComputeTheTotal() + { + var total = Calc.Compute(1); + Assert.Equal(5, total); + Assert.Equal(9, total); + Assert.Equal("legacy", total.ToString()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheAssertedLiteralIsReturnedThroughADelegateTypedCall() + { + return VerifyAsync(""" + using Xunit; + + public delegate int Transform(int value); + + public static class Calc + { + public static Transform Make() => value => value + 7; + } + + public sealed class Subject + { + [Fact] + public void {|E128107:Should_RunTheTransform|}() + { + var transform = Calc.Make(); + var result = transform(1); + Assert.Equal(7, result); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_OrderLockForAnInterfaceTypedSetAndSilentForANullActualValue() + { + return VerifyAsync(""" + using System.Collections.Generic; + using Xunit; + + public sealed class Subject + { + [Fact] + public void Should_AcceptNull() + { + var value = "a"; + var other = 1; + Assert.Equal(value, null); + Assert.Equal(1, other); + } + + [Fact] + public void {|E128107:Should_ReadTheSet|}() + { + var expected = new[] { 1, 2 }; + ISet actual = new HashSet { 1, 2 }; + var other = 1; + Assert.Equal(expected, actual); + Assert.Equal(1, other); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ConstructorPassthroughOnlyForAMatchingLiteral() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Box + { + public Box(int value, string name) + { + Value = value; + Name = name; + } + + public Box() { } + + public int Value { get; set; } + + public string Name { get; set; } = string.Empty; + } + + public sealed class Subject + { + [Fact] + public void {|E128107:Should_KeepTheValue|}() + { + var name = "x"; + Assert.Equal(5, new Box(5, name).Value); + } + + [Fact] + public void Should_KeepTheInitializedValue() + { + var name = "x"; + Assert.Equal(5, new Box { Value = 5 }.Value); + } + + [Fact] + public void Should_KeepAnotherValue() + { + var name = "x"; + var box = new Box(5, name); + Assert.Equal(7, box.Value); + } + + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheConstructedLocalIsNotAnExplicitObjectCreation() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Box + { + public Box(int value, string name) + { + Value = value; + } + + public int Value { get; set; } + } + + public sealed class Subject + { + [Fact] + public void Should_KeepTheTargetTypedValue() + { + Box box = new(5, "x"); + Assert.Equal(5, box.Value); + } + + [Fact] + public void Should_KeepTheFactoryValue() + { + var box = Create(); + Assert.Equal(5, box.Value); + } + + [Fact] + public void Should_KeepTheAssignedValue() + { + Box box; + box = new Box(5, "x"); + Assert.Equal(5, box.Value); + } + + private static Box Create() => new Box(5, "x"); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheAssertedLiteralIsReturnedByAReturnStatement() + { + return VerifyAsync(""" + using Xunit; + + public static class Calc + { + public static int Answer() + { + return 42; + } + } + + public sealed class Subject + { + [Fact] + public void {|E128107:Should_ReturnTheAnswer|}() + { + var left = Calc.Answer(); + var right = 1; + Assert.Equal(42, left); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnAssertionComparesANameofExpression() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Foo { } + + public sealed class Subject + { + [Fact] + public void Should_NameTheType() + { + var left = 1; + var right = 2; + Assert.Equal("Foo", nameof(Foo)); + Assert.NotEqual(left, right); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnAssertionArgumentHoldsALambdaInsideAnObjectCreation() + { + return VerifyAsync(""" + using System; + using Xunit; + + public sealed class Box + { + public Box(Func read) + { + Value = read(); + } + + public int Value { get; } + } + + public sealed class Subject + { + [Fact] + public void Should_ReadTheLambda() + { + var left = 1; + var right = 2; + Assert.Equal(1, new Box(() => left + right).Value); + Assert.NotEqual(left, right); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_LogAssertOnlyForAReceiverThatNamesALogger() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Recorder + { + public void VerifyLogged(string message) { } + } + + public sealed class Fixture + { + public Recorder Logger { get; } = new Recorder(); + + public Recorder Make() => new Recorder(); + } + + public sealed class Subject + { + [Fact] + public void {|E128107:Should_LogTheMessage|}() + { + var fixture = new Fixture(); + fixture.Logger.VerifyLogged("x"); + } + + [Fact] + public void Should_NotLogThroughACall() + { + var fixture = new Fixture(); + fixture.Make().VerifyLogged("x"); + } + + [Fact] + public void Should_NotLogThroughAnUnqualifiedCall() + { + var fixture = new Fixture(); + VerifyLogged("x"); + } + + private static void VerifyLogged(string message) { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_OnlyConstructorPassthroughForAnImportedEqualOnAnExceptionMessage() + { + return VerifyAsync(""" + using System; + using static Xunit.Assert; + using Xunit; + + public sealed class Subject + { + [Fact] + public void {|E128107:Should_CarryTheMessage|}() + { + var exception = new InvalidOperationException("boom"); + Equal("boom", exception.Message); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..4f12265 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,168 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ManualSpanSumAnalyzerBranchCoverageGapTests +{ + private const string DoubleOnlyStub = """ + namespace System.Numerics.Tensors + { + public static class TensorPrimitives + { + public static double Sum(ReadOnlySpan values) + { + return 0d; + } + + public static float Sum(ReadOnlySpan values, int stride) + { + return 0f; + } + + public static int Sum(ReadOnlySpan values) + { + return 0; + } + } + } + """; + + private const string IntOnlyStub = """ + namespace System.Numerics.Tensors + { + public static class TensorPrimitives + { + public static int Sum(ReadOnlySpan values) + { + return 0; + } + } + } + """; + + private static Task VerifyAsync(string code) + { + return VerifyWithStubAsync(TestStubs.TensorPrimitives, code); + } + + private static Task VerifyWithStubAsync(string stub, string code) + { + return AnalyzerTestRunner.VerifyAsync("using System;\n\n" + stub + "\n\n" + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALoopSumsAFloatSpan() + { + return VerifyAsync(""" + class C + { + float Sum(Span values) + { + float sum = 0; + {|E128135:foreach (var value in values) + { + sum += value; + }|} + return sum; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSourceIsNotAnArrayOrSpan() + { + return VerifyAsync(""" + class C + { + float FromList(System.Collections.Generic.List values) + { + float sum = 0; + foreach (var value in values) + { + sum += value; + } + return sum; + } + + float FromSequence(System.Collections.Generic.IEnumerable values) + { + float sum = 0; + foreach (var value in values) + { + sum += value; + } + return sum; + } + + float FromText(string text) + { + float sum = 0; + foreach (var letter in text) + { + sum += letter; + } + return sum; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_OnlyForTheTypesThatTensorPrimitivesSums() + { + return VerifyWithStubAsync( + DoubleOnlyStub, + """ + class C + { + double SumDouble(double[] values) + { + double sum = 0; + {|E128135:foreach (var value in values) + { + sum += value; + }|} + return sum; + } + + float SumFloat(float[] values) + { + float sum = 0; + foreach (var value in values) + { + sum += value; + } + return sum; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTensorPrimitivesSumsNeitherFloatNorDouble() + { + return VerifyWithStubAsync( + IntOnlyStub, + """ + class C + { + double Sum(double[] values) + { + double sum = 0; + foreach (var value in values) + { + sum += value; + } + return sum; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MemoryMarshalNonBlittableAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/MemoryMarshalNonBlittableAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..48121da --- /dev/null +++ b/tests/E128.Analyzers.Tests/MemoryMarshalNonBlittableAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,44 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MemoryMarshalNonBlittableAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInvokedExpressionHasNoSimpleName() + { + return VerifyAsync(""" + using System; + class C + { + int M(Func> factory) + { + return factory()(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsDynamic() + { + return VerifyAsync(""" + class C + { + object M(dynamic reader) + { + return reader.Read(0); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MidNameUnderscoreCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/MidNameUnderscoreCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..5e37cb8 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MidNameUnderscoreCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,40 @@ +using System.Threading.Tasks; +using E128.Analyzers.Style; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MidNameUnderscoreCodeFixProviderBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheNameHasOnlyATrailingUnderscore() + { + return CodeFixTestRunner.NoFixAsync( + """ + class C + { + private static int {|E128063:Value_|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public void ComputeFixedName_ReturnsAnEmptyNameUnchanged() + { + Assert.Equal(string.Empty, MidNameUnderscoreCodeFixProvider.ComputeFixedName(string.Empty)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("m_foo_bar", "m_fooBar")] + [InlineData("t_foo_bar", "t_fooBar")] + [InlineData("_foo_bar", "_fooBar")] + [InlineData("x_foo", "xFoo")] + [InlineData("Plain", "Plain")] + public void ComputeFixedName_KeepsAHungarianPrefixAndMergesTheRest(string name, string expected) + { + Assert.Equal(expected, MidNameUnderscoreCodeFixProvider.ComputeFixedName(name)); + } +} diff --git a/tests/E128.Analyzers.Tests/MissingTraitCategoryAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/MissingTraitCategoryAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..e1b486e --- /dev/null +++ b/tests/E128.Analyzers.Tests/MissingTraitCategoryAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,86 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MissingTraitCategoryAnalyzerBranchCoverageMoreTests +{ + private static readonly ReferenceAssemblies Net100WithXunit = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("xunit.v3.core", "3.2.2")]); + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions + { + References = Net100WithXunit, + CompilerDiagnostics = CompilerDiagnostics.None + }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTraitAttributeDoesNotBind() + { + return VerifyAsync(""" + public sealed class MyTests + { + [{|E128073:Xunit.Fact|}] + [Trait("Category", "CI")] + public void Works() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTraitNameIsANullConstant() + { + return VerifyAsync(""" + using Xunit; + + public sealed class MyTests + { + [{|E128073:Fact|}] + [Trait(null, "CI")] + public void Works() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTraitNameIsNotAConstant() + { + return VerifyAsync(""" + using Xunit; + + public sealed class MyTests + { + private static readonly string Name = "Category"; + + [{|E128073:Fact|}] + [Trait(Name, "CI")] + public void Works() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFactAttributeIsNotOnAMethod() + { + return VerifyAsync(""" + using Xunit; + + public sealed class MyTests + { + [Fact] + public int Value { get; } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..e3ba728 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,79 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MultiStringEqualsOrChainAnalyzerBranchCoverageGapTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStringEqualsCallsDoNotResolve() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + bool M(string text) => + string.Equals(text, "a", 1) || string.Equals(text, "b", 2) || string.Equals(text, "c", 3); + } + """, + expected: null, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheComparedValueIsNotALiteral() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + class C + { + bool M(string text, string a, string b, string c) => + string.Equals(text, a, StringComparison.Ordinal) + || string.Equals(text, b, StringComparison.Ordinal) + || string.Equals(text, c, StringComparison.Ordinal); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public void StringEqualityInfo_ComparesByEveryField() + { + var baseline = new MultiStringEqualsOrChainAnalyzer.StringEqualityInfo("text", "a", "=="); + var same = new MultiStringEqualsOrChainAnalyzer.StringEqualityInfo("text", "a", "=="); + + Assert.True(baseline.Equals(same)); + Assert.True(baseline.Equals((object)same)); + Assert.Equal(baseline.GetHashCode(), same.GetHashCode()); + Assert.False(baseline.Equals("text")); + Assert.False(baseline.Equals(new MultiStringEqualsOrChainAnalyzer.StringEqualityInfo("other", "a", "=="))); + Assert.False(baseline.Equals(new MultiStringEqualsOrChainAnalyzer.StringEqualityInfo("text", "b", "=="))); + Assert.False(baseline.Equals(new MultiStringEqualsOrChainAnalyzer.StringEqualityInfo("text", "a", "Ordinal"))); + } + + [Fact] + [Trait("Category", "CI")] + public void StringEqualityInfo_HandlesAnEmptyValue() + { + var empty = default(MultiStringEqualsOrChainAnalyzer.StringEqualityInfo); + + Assert.Equal(empty.GetHashCode(), default(MultiStringEqualsOrChainAnalyzer.StringEqualityInfo).GetHashCode()); + Assert.NotEqual( + empty.GetHashCode(), + new MultiStringEqualsOrChainAnalyzer.StringEqualityInfo("text", "a", "==").GetHashCode()); + Assert.Equal("(, , )", empty.ToString()); + } + + [Fact] + [Trait("Category", "CI")] + public void StringEqualityInfo_ToString_ListsEveryField() + { + var info = new MultiStringEqualsOrChainAnalyzer.StringEqualityInfo("text", "a", "=="); + + Assert.Equal("(text, a, ==)", info.ToString()); + } +} diff --git a/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..b39f74b --- /dev/null +++ b/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,82 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MultiStringEqualsOrChainCodeFixProviderBranchCoverageGapTests +{ + private static Task VerifyNoFixAsync(string source, OutputKind outputKind = OutputKind.DynamicallyLinkedLibrary) + { + var test = new CSharpCodeFixTest + { + TestCode = source, + FixedCode = source, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100 + }; + test.TestState.OutputKind = outputKind; + + return test.RunAsync(TestContext.Current.CancellationToken); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnOperandOfTheChainIsNotAStringTest() + { + return VerifyNoFixAsync( + """ + class C + { + bool M(string text, bool flag) => + {|E128029:text == "a" || text == "b" || text == "c" || flag|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnOperandTestsAnotherValue() + { + return VerifyNoFixAsync( + """ + class C + { + bool M(string text, string other) => + {|E128029:text == "a" || text == "b" || text == "c" || other == "d"|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnOperandUsesAnotherComparison() + { + return VerifyNoFixAsync( + """ + using System; + class C + { + bool M(string text) => + {|E128029:text == "a" || text == "b" || text == "c" || string.Equals(text, "d", StringComparison.Ordinal)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheChainSitsInTopLevelStatements() + { + return VerifyNoFixAsync( + """ + using System; + + var text = args.Length > 0 ? args[0] : string.Empty; + var hit = {|E128029:text == "a" || text == "b" || text == "c"|}; + Console.WriteLine(hit); + """, + OutputKind.ConsoleApplication); + } +} diff --git a/tests/E128.Analyzers.Tests/MutableCollectionExposureAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/MutableCollectionExposureAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..29370b2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MutableCollectionExposureAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,40 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MutableCollectionExposureAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForMethodsThatReturnArraysOrTypeParameters() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + class Source + { + public List[] Buckets() => []; + + public T Single(T value) => value; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForPropertiesThatAreArraysOrTypeParameters() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + class Source + { + public List[] Buckets { get; } = []; + + public T Value { get; } = default!; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MutableStaticReadonlyArrayCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/MutableStaticReadonlyArrayCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..e82626a --- /dev/null +++ b/tests/E128.Analyzers.Tests/MutableStaticReadonlyArrayCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,57 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MutableStaticReadonlyArrayCodeFixProviderBranchCoverageGapTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_SplitsAMultiVariableByteFieldIntoOnePropertyEach() + { + return VerifyFixAsync( + """ + class C + { + private static readonly {|E128061:{|E128061:byte[] First = [1, 2], Second = [3]|}|}; + } + """, + """ + using System; + + class C + { + private static ReadOnlySpan First => [1, 2]; + + private static ReadOnlySpan Second => [3]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_LeavesAnUninitializedSiblingVariableAlone() + { + return VerifyFixAsync( + """ + class C + { + private static readonly {|E128061:string[] Names = ["a"], Spare|}; + } + """, + """ + using System.Collections.Immutable; + + class C + { + private static readonly ImmutableArray Names = ["a"], Spare; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/NullByRefAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/NullByRefAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..c0461c0 --- /dev/null +++ b/tests/E128.Analyzers.Tests/NullByRefAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,141 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class NullByRefAnalyzerBranchCoverageMoreTests +{ + 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_WhenTheCalleeIsAnElementAccess() + { + return VerifyAsync(""" + using System; + class C + { + void M(Action[] callbacks) + { + callbacks[0](); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenNullRefIsCopiedOutsideARefExpression() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + class C + { + void M() + { + int copy = {|E128127:Unsafe.NullRef()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNullRefCallDoesNotBind() + { + return VerifyAsync( + """ + using System.Runtime.CompilerServices; + class C + { + void M() + { + ref int value = ref Unsafe.NullRef(1); + } + } + """, + lenient: true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAsRefTakesNoArgumentOrTwoArguments() + { + return VerifyAsync( + """ + using System.Runtime.CompilerServices; + class C + { + void M(int value) + { + ref int a = ref Unsafe.AsRef(); + ref int b = ref Unsafe.AsRef(value, value); + } + } + """, + lenient: true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAsRefOfTheDefaultLiteral() + { + return VerifyAsync( + """ + using System.Runtime.CompilerServices; + unsafe class C + { + void M() + { + ref int value = ref {|E128127:Unsafe.AsRef(default)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAsRefOfAZeroIntegerPointerCast() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M() + { + ref int value = ref {|E128127:Unsafe.AsRef((void*)0)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAsRefOfNonZeroPointerCastsOfEachIntegerLiteralType() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M() + { + ref int a = ref Unsafe.AsRef((void*)1); + ref int b = ref Unsafe.AsRef((void*)1u); + ref int c = ref Unsafe.AsRef((void*)1L); + ref int d = ref Unsafe.AsRef((void*)1UL); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/OptionsBindInitAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/OptionsBindInitAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..3c8b896 --- /dev/null +++ b/tests/E128.Analyzers.Tests/OptionsBindInitAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,69 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class OptionsBindInitAnalyzerBranchCoverageMoreTests +{ + private const string Stubs = """ + namespace Microsoft.Extensions.Configuration + { + public interface IConfiguration + { + IConfigurationSection GetSection(string key); + } + + public interface IConfigurationSection : IConfiguration + { + } + } + + namespace Microsoft.Extensions.Options + { + public class OptionsBuilder where T : class + { + public OptionsBuilder Bind(Microsoft.Extensions.Configuration.IConfigurationSection section) => this; + } + } + + """; + + private static Task VerifyAsync(string source) + { + return AnalyzerTestRunner.VerifyAsync(Stubs + source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheBoundTypeIsATypeParameter() + { + return VerifyAsync(""" + class Setup + { + static void Configure( + Microsoft.Extensions.Options.OptionsBuilder builder, + Microsoft.Extensions.Configuration.IConfiguration config) + where T : class + { + builder.Bind(config.GetSection("Options")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheBindReceiverIsDynamic() + { + return VerifyAsync(""" + class Setup + { + static void Configure(dynamic builder, Microsoft.Extensions.Configuration.IConfiguration config) + { + builder.Bind(config.GetSection("Options")); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/OptionsValidationMissingAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/OptionsValidationMissingAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..19d2160 --- /dev/null +++ b/tests/E128.Analyzers.Tests/OptionsValidationMissingAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,134 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class OptionsValidationMissingAnalyzerBranchCoverageGapTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenNoValidatorTypeOrServiceCollectionTypeExists() + { + return VerifyAsync(""" + using System; + using Microsoft.Extensions.DependencyInjection; + + namespace Microsoft.Extensions.Options + { + public sealed class OptionsBuilder + where TOptions : class + { + } + } + + namespace Microsoft.Extensions.DependencyInjection + { + using Microsoft.Extensions.Options; + + public static class OptionsServiceCollectionExtensions + { + public static OptionsBuilder AddOptions() + where TOptions : class + { + return new OptionsBuilder(); + } + + public static void Configure(Action configure) + where TOptions : class + { + } + } + + public static class OptionsBuilderConfigurationExtensions + { + public static OptionsBuilder Bind(this OptionsBuilder builder, object configuration) + where TOptions : class + { + return builder; + } + } + } + + class MyOptions + { + } + + class Startup + { + void Run(object configuration) + { + {|E128179:OptionsServiceCollectionExtensions.AddOptions()|}.Bind(configuration); + OptionsServiceCollectionExtensions.Configure(options => { }); + Local(); + } + + void Local() + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAValidatorTypeExistsButNoServiceCollectionTypeDoes() + { + return VerifyAsync(""" + using Microsoft.Extensions.DependencyInjection; + + namespace Microsoft.Extensions.Options + { + public sealed class OptionsBuilder + where TOptions : class + { + } + + public interface IValidateOptions + where TOptions : class + { + } + } + + namespace Microsoft.Extensions.DependencyInjection + { + using Microsoft.Extensions.Options; + + public static class OptionsServiceCollectionExtensions + { + public static OptionsBuilder AddOptions() + where TOptions : class + { + return new OptionsBuilder(); + } + } + + public static class OptionsBuilderConfigurationExtensions + { + public static OptionsBuilder Bind(this OptionsBuilder builder, object configuration) + where TOptions : class + { + return builder; + } + } + } + + class MyOptions + { + } + + class Startup + { + void Run(object configuration) + { + {|E128179:OptionsServiceCollectionExtensions.AddOptions()|}.Bind(configuration); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/OutOfRepoResolverAssertionAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/OutOfRepoResolverAssertionAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..ce98ad6 --- /dev/null +++ b/tests/E128.Analyzers.Tests/OutOfRepoResolverAssertionAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,119 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class OutOfRepoResolverAssertionAnalyzerBranchCoverageMoreTests +{ + private static readonly ReferenceAssemblies Net100WithXunit = ReferenceAssemblies.Net.Net100 + .AddPackages([ + new PackageIdentity("xunit.v3.core", "3.2.2"), + new PackageIdentity("xunit.v3.assert", "3.2.2") + ]); + + private const string Resolver = """ + public static class CssPathResolver + { + public static string Resolve(string name) => name; + } + """; + + private static Task VerifyAsync(string code, bool lenient = false) + { + var test = new CSharpAnalyzerTest + { + TestCode = code + "\n" + Resolver, + ReferenceAssemblies = Net100WithXunit + }; + test.TestState.AnalyzerConfigFiles.Add( + ("/.editorconfig", "is_global = true\ne128_out_of_repo_resolvers = CssPathResolver.Resolve")); + + if (lenient) + { + test.CompilerDiagnostics = CompilerDiagnostics.None; + } + + return test.RunAsync(TestContext.Current.CancellationToken); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTestMethodHasNoBody() + { + return VerifyAsync(""" + using Xunit; + + public abstract class Subject + { + [Fact] + public abstract void ResolvePath_ReturnsThePath(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnUnresolvedCallPrecedesTheResolver() + { + return VerifyAsync( + """ + using Xunit; + + public sealed class Subject + { + [Fact] + public void {|E128105:ResolvePath_ReturnsThePath|}() + { + Missing(); + var path = CssPathResolver.Resolve("alpha"); + Assert.NotNull(path); + } + } + """, + lenient: true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenSeveralSkipGuardsPrecedeTheResolver() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Subject + { + [Fact] + public void ResolvePath_ReturnsThePath() + { + Assert.SkipWhen(false, "first guard"); + Assert.SkipUnless(true, "second guard"); + var path = CssPathResolver.Resolve("alpha"); + Assert.NotNull(path); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTestCarriesAnotherAttributeAndANonSkipArgument() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Subject + { + [Trait("Category", "CI")] + [Fact(DisplayName = "resolves the path")] + public void {|E128105:ResolvePath_ReturnsThePath|}() + { + var path = CssPathResolver.Resolve("alpha"); + Assert.NotNull(path); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ParallelCollectionIndexAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ParallelCollectionIndexAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..a707ff2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ParallelCollectionIndexAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,43 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ParallelCollectionIndexAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string body) + { + var code = "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n" + + "using static System.Linq.Enumerable;\n\n" + + "public static class Subject\n{\n" + + " public static void Verify(List columns, List> rows, int k)\n {\n" + + body + + " }\n}\n"; + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRangeStartIsNotALiteral() + { + return VerifyAsync(""" + _ = Range(k, columns.Count).Select(i => rows[i]).ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheForLoopDeclaresNoVariable() + { + return VerifyAsync(""" + int i; + for (i = 0; i < columns.Count; i++) + { + _ = rows[i]; + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/PfxImportEphemeralKeySetAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/PfxImportEphemeralKeySetAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..01c93d4 --- /dev/null +++ b/tests/E128.Analyzers.Tests/PfxImportEphemeralKeySetAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,67 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PfxImportEphemeralKeySetAnalyzerBranchCoverageGapTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCreationsAndInvocationsThatAreNotConstructorCalls() + { + return VerifyAsync(""" + using System.Security.Cryptography.X509Certificates; + + struct Pair + { + public int First; + } + + class C + { + T Make() where T : X509Certificate2, new() + { + return new T(); + } + + string Describe() + { + var pair = new Pair(); + var number = new int(); + return nameof(X509Certificate2) + pair.First + number; + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("public enum X509KeyStorageFlags { Exportable = 4 }")] + [InlineData("public enum X509KeyStorageFlags : long { EphemeralKeySet = 32 }")] + [InlineData("public static class X509KeyStorageFlags { public static int EphemeralKeySet => 32; }")] + [InlineData("public static class X509KeyStorageFlags { public static readonly int EphemeralKeySet = 32; }")] + public Task Silent_WhenTheFlagTypeHasNoReadableEphemeralKeySetConstant(string declaration) + { + return AnalyzerTestRunner.VerifyAsync( + $$""" + namespace System.Security.Cryptography.X509Certificates + { + {{declaration}} + } + + class C + { + object M(string path) + { + return System.Security.Cryptography.X509Certificates.X509CertificateLoader.LoadPkcs12FromFile(path, "pw"); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/PoolRentCapacityGuardAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/PoolRentCapacityGuardAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..3968af5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/PoolRentCapacityGuardAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,25 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PoolRentCapacityGuardAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRentCallPassesTwoArguments() + { + return AnalyzerTestRunner.VerifyAsync(""" + class WidePool + { + public byte[] Rent(int size, int extra) => new byte[size + extra]; + } + + class C + { + byte[] M(WidePool pool, int size) => pool.Rent(size, 2); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/PooledBufferZeroingAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/PooledBufferZeroingAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..8f04dc6 --- /dev/null +++ b/tests/E128.Analyzers.Tests/PooledBufferZeroingAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,106 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PooledBufferZeroingAnalyzerBranchCoverageGapTests +{ + private static readonly AnalyzerTestOptions NoCompilerDiagnostics = new() { CompilerDiagnostics = CompilerDiagnostics.None }; + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForReturnCallsWithAnUnexpectedArgumentCount() + { + return AnalyzerTestRunner.VerifyAsync(""" + class Pool + { + public void Return() { } + + public void Return(byte[] buffer, bool clear, int extra) { } + } + + class C + { + void M(Pool pool, byte[] buffer) + { + pool.Return(); + pool.Return(buffer, true, 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAReturnMethodOfAnotherTypeOrAnUnboundReceiver() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class Pool + { + public void Return(byte[] buffer) { } + } + + class C + { + void M(Pool pool, byte[] buffer) + { + pool.Return(buffer); + missing.Return(buffer); + } + } + """, + expected: null, + NoCompilerDiagnostics); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_UseAfterReturnBehindAStatementThatIgnoresTheBuffer() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Buffers; + class C + { + void M() + { + var buffer = ArrayPool.Shared.Rent(8); + {|E128110:ArrayPool.Shared.Return(buffer)|}; + Console.WriteLine("done"); + Console.WriteLine({|E128111:buffer|}.Length); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFinallyBlockHoldsOnlyOtherCallsBeforeTheReturn() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Buffers; + class C + { + void M() + { + var buffer = ArrayPool.Shared.Rent(8); + try { } + finally + { + Array.Clear(buffer); + Array.Clear(buffer, 0, buffer.Length); + Missing(buffer); + {|E128110:ArrayPool.Shared.Return(buffer)|}; + } + } + } + """, + expected: null, + NoCompilerDiagnostics); + } +} diff --git a/tests/E128.Analyzers.Tests/PragmaBundlingCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/PragmaBundlingCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..fcb1688 --- /dev/null +++ b/tests/E128.Analyzers.Tests/PragmaBundlingCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,44 @@ +using System.Threading.Tasks; +using E128.Analyzers.Style; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PragmaBundlingCodeFixProviderBranchCoverageMoreTests +{ + private static CSharpCodeFixTest CreateTest( + string source, + string fixedCode) + { + return new CSharpCodeFixTest + { + TestCode = source, + FixedCode = fixedCode, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + NumberOfFixAllIterations = 1, + TestBehaviors = TestBehaviors.SkipSuppressionCheck, + }; + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_LeavesAnEarlierPragmaOfTheSameLeadingTriviaUntouched() + { + const string source = """ + #pragma warning disable CA2007 + {|E128065:#pragma warning disable MA0004, MA0045|} + class Foo { } + """; + + const string fixedCode = """ + #pragma warning disable CA2007 + #pragma warning disable MA0004 + #pragma warning disable MA0045 + class Foo { } + """; + + return CreateTest(source, fixedCode).RunAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/E128.Analyzers.Tests/PresizeCollectionAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/PresizeCollectionAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..2d686f3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/PresizeCollectionAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,58 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PresizeCollectionAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenOneDeclarationCreatesTwoCollections() + { + return VerifyAsync(""" + using System.Collections.Generic; + class C + { + int M(IReadOnlyList source) + { + List first = new(), second = new(); + foreach (int item in source) + { + first.Add(item); + } + + return first.Count + second.Count; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheDeclarationHasNoInitializer() + { + return VerifyAsync(""" + using System.Collections.Generic; + class C + { + List M(IReadOnlyList source) + { + List result; + result = new(); + foreach (int item in source) + { + result.Add(item); + } + + return result; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ProcessOutputValidatorAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ProcessOutputValidatorAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..8cb0dec --- /dev/null +++ b/tests/E128.Analyzers.Tests/ProcessOutputValidatorAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,64 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ProcessOutputValidatorAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Diagnostics;\nclass C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFileReadHasNoArguments() + { + return VerifyAsync(""" + static class File + { + public static string ReadAllText() => string.Empty; + + public static bool Exists() => true; + } + + string M(Process process) + { + process.WaitForExit(); + _ = File.Exists(); + return File.ReadAllText(); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForReadsThroughAnotherQualifierOrACall() + { + return VerifyAsync(""" + sealed class Reader + { + public string ReadAllText(string path) => path; + } + + sealed class Holder + { + public Reader Reader { get; } = new Reader(); + } + + string M(Process process, Holder holder, string outputFile) + { + process.WaitForExit(); + var first = holder.Reader.ReadAllText(outputFile); + var second = Create().ReadAllText(outputFile); + return first + second; + } + + static Reader Create() => new Reader(); + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ProcessOutputValidatorCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ProcessOutputValidatorCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..65fa902 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ProcessOutputValidatorCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,73 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ProcessOutputValidatorCodeFixProviderBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_InsertsTheGuardAfterAnAsyncWaitAndSkipsStatementsAfterTheRead() + { + return CodeFixTestRunner.RunAsync( + """ + using System.Diagnostics; + using System.IO; + using System.Threading.Tasks; + class C + { + static void Log() + { + } + + async Task M(Process process, string outputFile) + { + await process.WaitForExitAsync(); + Log(); + var text = {|E128101:File.ReadAllText(outputFile)|}; + Log(); + return text; + } + } + """, + """ + using System; + using System.Diagnostics; + using System.IO; + using System.Threading.Tasks; + class C + { + static void Log() + { + } + + async Task M(Process process, string outputFile) + { + await process.WaitForExitAsync(); + if (!File.Exists(outputFile)) throw new InvalidOperationException($"Expected output file not created: {outputFile}"); + Log(); + var text = File.ReadAllText(outputFile); + Log(); + return text; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheReadIsInAnExpressionBodiedMethod() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Diagnostics; + using System.IO; + class C + { + string M(Process process, string outputFile) => + process.WaitForExitAsync().IsCompleted ? {|E128101:File.ReadAllText(outputFile)|} : string.Empty; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..6d9b6b1 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,140 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ProcessStartInfoArgumentAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string code, bool lenient = false) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: lenient ? new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None } : null); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsANamespace() + { + return VerifyAsync( + """ + class C + { + void M(string value) + { + System.Diagnostics.Arguments = value; + } + } + """, + lenient: true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenArgumentListIsAssignedAfterTheArguments() + { + return VerifyAsync( + """ + using System.Diagnostics; + class C + { + void M(string value) + { + var info = new ProcessStartInfo("tool"); + info.Arguments = value; + info.ArgumentList = null; + } + } + """, + lenient: true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenOtherAssignmentsSurroundTheArguments() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string value) + { + var info = new ProcessStartInfo("tool"); + var other = new ProcessStartInfo("tool"); + int count; + count = 1; + other.FileName = "x"; + {|E128091:info.Arguments = value|}; + other.ArgumentList.Add("x"); + var unused = count; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherReceiverGetsTheArgumentList() + { + return VerifyAsync( + """ + using System.Diagnostics; + class C + { + void M(string value) + { + var info = new ProcessStartInfo("tool"); + var other = new ProcessStartInfo("tool"); + {|E128091:info.Arguments = value|}; + other.ArgumentList = null; + } + } + """, + lenient: true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheInitializerAlsoHoldsAnIndexerAssignment() + { + return VerifyAsync( + """ + using System.Diagnostics; + class C + { + void M(string value) + { + var info = new ProcessStartInfo { [0] = 1, {|E128091:Arguments = value|} }; + } + } + """, + lenient: true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForNonEmptyConstantsAndValuesThatAreNotStringEmpty() + { + return VerifyAsync(""" + using System.Diagnostics; + class Holder + { + public static string Empty = ""; + + public string Name { get; set; } = ""; + } + + class C + { + void M(Holder holder) + { + var a = new ProcessStartInfo { {|E128091:Arguments = "-v"|} }; + var b = new ProcessStartInfo { {|E128091:Arguments = Holder.Empty|} }; + var c = new ProcessStartInfo { {|E128091:Arguments = holder.Name|} }; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/QuerySelectorAllMaterializationAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/QuerySelectorAllMaterializationAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..ee4ee2c --- /dev/null +++ b/tests/E128.Analyzers.Tests/QuerySelectorAllMaterializationAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,103 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class QuerySelectorAllMaterializationAnalyzerBranchCoverageMoreTests +{ + private const string Stub = """ + using System; + using System.Collections.Generic; + using System.Linq; + using AngleSharp.Dom; + namespace AngleSharp.Dom + { + public interface IElement { } + public interface IDocument + { + IEnumerable QuerySelectorAll(string selector); + } + } + class Holder + { + public IEnumerable Elements { get; } = new List(); + } + class Own + { + public IEnumerable QuerySelectorAll(string selector) => new List(); + } + """; + + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + Stub + "\nclass C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopSourceIsAnIterationVariable() + { + return VerifyAsync(""" + void M(IEnumerable> groups) + { + foreach (var group in groups) + { + foreach (var element in group) + { + } + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheQueryReceiverIsDynamic() + { + return VerifyAsync(""" + void M(dynamic doc) + { + foreach (var element in doc.QuerySelectorAll("p")) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopSourceIsAnInvokedDelegateResult() + { + return VerifyAsync(""" + void M(Func>> factory) + { + foreach (var element in factory()()) + { + } + } + + """); + } + + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheQueryIsAnArgumentOfAnotherCall() + { + return VerifyAsync(""" + static IEnumerable Wrap(IEnumerable elements) => elements; + + void M(IDocument doc) + { + foreach (var element in Wrap({|E128076:doc.QuerySelectorAll("p")|})) + { + } + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..7db6142 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,26 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ReadOnlyMemoryStreamAnalyzerBranchCoverageGapTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStreamHasAnInitializerAndNoArgumentList() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.IO; + class C + { + void M() + { + using var stream = new MemoryStream { Capacity = 4 }; + _ = stream.Length; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/RecordMutableCollectionEqualityAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/RecordMutableCollectionEqualityAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..8e65427 --- /dev/null +++ b/tests/E128.Analyzers.Tests/RecordMutableCollectionEqualityAnalyzerBranchCoverageMoreTests.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 RecordMutableCollectionEqualityAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheBaseRecordOnlyHasTheGeneratedGetHashCode() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + record Base(int Id); + + record Derived(int Id, {|E128177:List Items|}) : Base(Id); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheBaseRecordOnlyDeclaresAGetHashCodeOverload() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + record Base(int Id) + { + public int GetHashCode(int salt) => Id + salt; + } + + record Derived(int Id, {|E128177:List Items|}) : Base(Id); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForMembersOfATypeParameterType() + { + return AnalyzerTestRunner.VerifyAsync(""" + record Box(T Item) + { + public T Other { get; init; } = Item; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePropertyDeclaresNoAccessors() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + + record Widget + { + public List Items { } + } + """, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/RecursiveDeleteRootAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/RecursiveDeleteRootAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..4c7edf5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/RecursiveDeleteRootAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,187 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class RecursiveDeleteRootAnalyzerBranchCoverageGapTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheDeleteIsReachedThroughAConditionalAccessOrAnInvokedResult() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + static Action Resolve() => Directory.Delete; + + void M(string path) + { + var info = new DirectoryInfo(Path.GetTempPath()); + info?.Delete(true); + Resolve()(path, true); + (Resolve())(path, true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalHasNoInitializerOrComesFromAnIteration() + { + return VerifyAsync(""" + using System.IO; + class C + { + string[] Names() => new[] { "a" }; + + void M(string input) + { + string assigned; + assigned = input; + Directory.Delete(assigned, true); + + foreach (var name in Names()) + { + Directory.Delete(name, true); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCombineHasNoArguments() + { + return VerifyAsync(""" + using System.IO; + class C + { + void M() + { + Directory.Delete(Path.Combine(), true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLiteralIsEmptyOrHasNoDriveColon() + { + return VerifyAsync(""" + using System.IO; + class C + { + void M() + { + Directory.Delete("", true); + Directory.Delete("ab", true); + Directory.Delete("x", true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardRootIsAnEmptyString() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + void M(string path) + { + if (!path.StartsWith("", StringComparison.Ordinal)) + { + return; + } + + {|E128184:Directory.Delete(path, true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardRootIsARootPlusAnEmptySuffix() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + void M(string path) + { + if (path.StartsWith("/srv/app" + "", StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenUnrelatedUnaryOperatorsRunBetweenTheGuardAndTheDelete() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + void M(string path, int count) + { + if (path.StartsWith(Path.GetTempPath(), StringComparison.Ordinal)) + { + --count; + count--; + ++count; + count++; + var negated = -count; + var forgiven = path!; + GC.KeepAlive(forgiven); + GC.KeepAlive(negated); + Directory.Delete(path, true); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFrameworkReferencesHaveNoDirectoryType() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class Directory + { + public static void Delete(string path, bool recursive) { } + } + + class C + { + void M(string path) + { + Directory.Delete(path, true); + } + } + """, + options: new AnalyzerTestOptions { References = ReferenceAssemblies.NetStandard.NetStandard10 }); + } +} diff --git a/tests/E128.Analyzers.Tests/RefUsageBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/RefUsageBranchCoverageMoreTests.cs new file mode 100644 index 0000000..f795757 --- /dev/null +++ b/tests/E128.Analyzers.Tests/RefUsageBranchCoverageMoreTests.cs @@ -0,0 +1,70 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class RefUsageBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheResultIsIncrementedOrDecremented() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Runtime.CompilerServices; + class C + { + void M() + { + int value = 1; + ++Unsafe.As(ref value); + --Unsafe.As(ref value); + Unsafe.As(ref value)++; + Unsafe.As(ref value)--; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAParenthesizedResultIsAssigned() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Runtime.CompilerServices; + class C + { + void M() + { + int value = 1; + (Unsafe.As(ref value)) = 2u; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheResultIsReadByValue() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Runtime.CompilerServices; + class C + { + static void Use(uint number) + { + } + + void M() + { + int value = 1; + uint copy; + copy = {|E128112:Unsafe.As(ref value)|}; + var negated = -{|E128112:Unsafe.As(ref value)|}; + var text = {|E128112:Unsafe.As(ref value)|}.ToString(); + Use({|E128112:Unsafe.As(ref value)|}); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/RegexLiteralFixBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/RegexLiteralFixBranchCoverageMoreTests.cs new file mode 100644 index 0000000..b5dff57 --- /dev/null +++ b/tests/E128.Analyzers.Tests/RegexLiteralFixBranchCoverageMoreTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class RegexLiteralFixBranchCoverageMoreTests +{ + private static AttributeSyntax ParseAttribute(string attribute) + { + var tree = CSharpSyntaxTree.ParseText( + "class C { " + attribute + " void M() { } }", + cancellationToken: TestContext.Current.CancellationToken); + + return tree.GetRoot(TestContext.Current.CancellationToken).DescendantNodes().OfType().Single(); + } + + private static async Task RewriteAsync(string attribute, Func rewrite) + { + var source = "class C { " + attribute + " void M() { } }"; + using var workspace = new AdhocWorkspace(); + var document = workspace.AddProject("Probe", LanguageNames.CSharp).AddDocument("Probe.cs", source); + var root = await document.GetSyntaxRootAsync(TestContext.Current.CancellationToken); + var node = Assert.IsType(root).DescendantNodes().OfType().Single(); + var result = await RegexLiteralFix.ApplyRewriteAsync(document, node, rewrite, TestContext.Current.CancellationToken); + var text = await result.GetTextAsync(TestContext.Current.CancellationToken); + + return text.ToString(); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetPattern_ReadsTheFirstPositionalStringLiteral() + { + Assert.True(RegexLiteralFix.TryGetPattern(ParseAttribute("""[GeneratedRegex("a+")]"""), out var pattern)); + Assert.Equal("a+", pattern); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("[GeneratedRegex]")] + [InlineData("[GeneratedRegex()]")] + [InlineData("""[GeneratedRegex(pattern: "a+")]""")] + [InlineData("""[GeneratedRegex(Pattern = "a+")]""")] + [InlineData("[GeneratedRegex(Pattern)]")] + [InlineData("[GeneratedRegex(1)]")] + public void TryGetPattern_IsFalseWhenNoPositionalStringLiteralLeads(string attribute) + { + Assert.False(RegexLiteralFix.TryGetPattern(ParseAttribute(attribute), out var pattern)); + Assert.Equal(string.Empty, pattern); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("[GeneratedRegex]")] + [InlineData("[GeneratedRegex(Pattern)]")] + public async Task ApplyRewriteAsync_KeepsTheDocumentWhenThereIsNoPattern(string attribute) + { + var rewritten = await RewriteAsync(attribute, static pattern => pattern + "x"); + + Assert.Equal("class C { " + attribute + " void M() { } }", rewritten); + } + + [Fact] + [Trait("Category", "CI")] + public async Task ApplyRewriteAsync_KeepsTheDocumentWhenTheRewriteChangesNothing() + { + var rewritten = await RewriteAsync("""[GeneratedRegex("a+")]""", static pattern => pattern); + + Assert.Equal("""class C { [GeneratedRegex("a+")] void M() { } }""", rewritten); + } + + [Fact] + [Trait("Category", "CI")] + public async Task ApplyRewriteAsync_ReplacesARegularLiteral() + { + var rewritten = await RewriteAsync("""[GeneratedRegex("a+")]""", static pattern => pattern + "b"); + + Assert.Equal("""class C { [GeneratedRegex("a+b")] void M() { } }""", rewritten); + } + + [Fact] + [Trait("Category", "CI")] + public async Task ApplyRewriteAsync_ReplacesAVerbatimLiteralAndDoublesItsQuotes() + { + var rewritten = await RewriteAsync("""[GeneratedRegex(@"a+")]""", static pattern => pattern + "\""); + + Assert.Equal("class C { [GeneratedRegex(@\"a+\"\"\")] void M() { } }", rewritten); + } +} diff --git a/tests/E128.Analyzers.Tests/SaveChangesInLoopAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SaveChangesInLoopAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..ab12866 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SaveChangesInLoopAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,202 @@ +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 SaveChangesInLoopAnalyzerBranchCoverageMoreTests +{ + private const string EfStub = """ + namespace Microsoft.EntityFrameworkCore + { + public class DbContext + { + public virtual int SaveChanges() => 0; + } + } + """; + + private static Task VerifyAsync(string code, bool lenient = false) + { + return AnalyzerTestRunner.VerifyAsync( + code + "\n" + EfStub, + options: lenient ? new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None } : null); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSaveChangesCallDoesNotResolve() + { + return VerifyAsync( + """ + using System.Collections.Generic; + + class C + { + void M(List rows) + { + foreach (var row in rows) + { + Missing.SaveChanges(); + } + } + } + """, + lenient: true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenAGenericSaveChangesOnADerivedContextRunsInALoop() + { + return VerifyAsync(""" + using System.Collections.Generic; + using Microsoft.EntityFrameworkCore; + + class AppContext : DbContext + { + int SaveChanges() => 0; + + void Run(List rows) + { + foreach (var row in rows) + { + {|E128185:SaveChanges()|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenANullConditionalCallContinuesWithAMemberAccess() + { + return VerifyAsync(""" + using System.Collections.Generic; + using Microsoft.EntityFrameworkCore; + + class C + { + void M(DbContext db, List rows) + { + foreach (var row in rows) + { + db?{|E128185:.SaveChanges()|}.ToString(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenAnExtensionOnObjectIsCalledOnAContextReceiver() + { + return VerifyAsync(""" + using System.Collections.Generic; + using Microsoft.EntityFrameworkCore; + + static class Extensions + { + public static int SaveChanges(this object source) => 0; + } + + class C + { + void M(DbContext db, List rows) + { + foreach (var row in rows) + { + _ = {|E128185:db.SaveChanges()|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnExtensionIsCalledAsAPlainStaticMethod() + { + return VerifyAsync(""" + using System.Collections.Generic; + + static class Extensions + { + public static int SaveChanges(this object source) => 0; + + public static void Run(object source, List rows) + { + foreach (var row in rows) + { + _ = SaveChanges(source); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheExtensionReceiverIsAnArray() + { + return VerifyAsync(""" + using System.Collections.Generic; + + static class Extensions + { + public static int SaveChanges(this int[] source) => 0; + } + + class C + { + void M(int[] values, List rows) + { + foreach (var row in rows) + { + _ = values.SaveChanges(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenTheExtensionLivesInAnEntityFrameworkAssembly() + { + var test = new CSharpAnalyzerTest + { + TestCode = """ + using System.Collections.Generic; + + namespace Other + { + static class Extensions + { + public static int SaveChanges(this List source) => 0; + } + + class C + { + void M(List rows) + { + foreach (var row in rows) + { + _ = {|E128185:rows.SaveChanges()|}; + } + } + } + } + """ + "\n" + EfStub, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + }; + test.SolutionTransforms.Add(static (solution, projectId) => + solution.WithProjectAssemblyName(projectId, "Microsoft.EntityFrameworkCore.Extras")); + + return test.RunAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/E128.Analyzers.Tests/SearchValuesHoistingAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SearchValuesHoistingAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..604cae8 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SearchValuesHoistingAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,138 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SearchValuesHoistingAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCompilationHasNoSearchValues() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class Factory + { + public static int Create(string values) => values.Length; + } + + class C + { + int M() + { + return Factory.Create("abc"); + } + } + """, + options: new AnalyzerTestOptions { References = ReferenceAssemblies.NetStandard.NetStandard20 }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenCreateIsADynamicCallOrAnotherType() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Buffers; + class Factory + { + public static int Create(string values) => values.Length; + } + + class C + { + void M() + { + dynamic factory = new Factory(); + factory.Create("abc"); + _ = Factory.Create("abc"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArgumentIsAStaticFieldThatIsNotReadonly() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Buffers; + class C + { + private static string chars = "abc"; + + bool M(ReadOnlySpan text) + { + return text.ContainsAny(SearchValues.Create(chars)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheArgumentCallsAStaticMethod() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Buffers; + class C + { + private static string Chars() => "abc"; + + bool M(ReadOnlySpan text) + { + return text.ContainsAny({|E128124:SearchValues.Create(Chars())|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheArgumentMixesAConstantAndAStaticReadonlyField() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Buffers; + class C + { + private const string Prefix = "a"; + private static readonly string Suffix = "b"; + + bool M(ReadOnlySpan text) + { + return text.ContainsAny({|E128124:SearchValues.Create(Prefix + Suffix)|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTableIsAnInstancePropertyInitializer() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Buffers; + class C + { + SearchValues Values { get; } = {|E128124:SearchValues.Create("abc")|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTableIsAStaticExpressionBodiedProperty() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Buffers; + class C + { + static SearchValues Values => {|E128124:SearchValues.Create("abc")|}; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SearchValuesHoistingCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SearchValuesHoistingCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..1346db5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SearchValuesHoistingCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,70 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SearchValuesHoistingCodeFixProviderBranchCoverageMoreTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_UsesTheFallbackNameAndKeepsAFirstInstanceFieldTogetherWithTheNewField() + { + return VerifyFixAsync( + """ + using System; + using System.Buffers; + + class C + { + private readonly int _count; + + public bool Has => "abc".AsSpan().ContainsAny({|E128124:SearchValues.Create("abc")|}); + } + """, + """ + using System; + using System.Buffers; + + class C + { + private static readonly System.Buffers.SearchValues _searchValues = SearchValues.Create("abc"); + private readonly int _count; + + public bool Has => "abc".AsSpan().ContainsAny(_searchValues); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_HandlesAFirstMemberThatHasNoIndentation() + { + return VerifyFixAsync( + "using System;\nusing System.Buffers;\n\nclass C\n{\n\nbool M(ReadOnlySpan text)\n{\nreturn text.ContainsAny({|E128124:SearchValues.Create(\"abc\")|});\n}\n}\n", + "using System;\nusing System.Buffers;\n\nclass C\n{\n private static readonly System.Buffers.SearchValues _mSearchValues = SearchValues.Create(\"abc\");\n\n bool M(ReadOnlySpan text)\n{\nreturn text.ContainsAny(_mSearchValues);\n}\n}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCallIsInTopLevelStatements() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System; + using System.Buffers; + + ReadOnlySpan text = "abc"; + var found = text.ContainsAny({|E128124:SearchValues.Create("abc")|}); + """, + null, + CodeFixTestBehaviors.None, + DiagnosticResult.CompilerError("CS8805").WithLocation(4, 1)); + } +} diff --git a/tests/E128.Analyzers.Tests/SelectManyToListCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/SelectManyToListCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..d7f8dff --- /dev/null +++ b/tests/E128.Analyzers.Tests/SelectManyToListCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,105 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SelectManyToListCodeFixProviderBranchCoverageGapTests +{ + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheSelectorIsAMethodGroup() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + static IEnumerable Flatten(List list) => list; + + void M(List> lists) + { + var flat = {|E128085:lists.SelectMany(Flatten).ToList()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheSelectorIsAParenthesizedLambda() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List> lists) + { + var flat = {|E128085:lists.SelectMany((x) => x).ToList()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheSelectorHasABlockBody() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List> lists) + { + var flat = {|E128085:lists.SelectMany(x => { return x; }).ToList()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheDeclarationHoldsSeveralVariables() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List> lists) + { + List flat = {|E128085:lists.SelectMany(x => x).ToList()|}, other = null; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCallIsNotPartOfALocalDeclaration() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + List M(List> lists) + { + return {|E128085:lists.SelectMany(x => x).ToList()|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SemaphoreSlimReleaseAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SemaphoreSlimReleaseAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..6992cb8 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SemaphoreSlimReleaseAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,95 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SemaphoreSlimReleaseAnalyzerBranchCoverageMoreTests +{ + private const string Header = """ + using System; + using System.Threading; + using System.Threading.Tasks; + + """; + + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(Header + source, expected: null, options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitTakesATimeoutOrMoreThanOneArgument() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + async Task M(CancellationToken token) + { + _sem.Wait(100); + _sem.Wait(100, token); + await _sem.WaitAsync(TimeSpan.FromSeconds(1)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheEarlyReturnCallsAMethodWithoutAnyRelease() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + static int Compute() => 1; + + int M(bool flag) + { + {|E128175:_sem.Wait()|}; + if (flag) + { + return Compute(); + } + + return 0; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnEarlyReturnFollowsARelease() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + int M(bool flag) + { + _sem.Wait(); + if (flag) + { + _sem.Release(); + return 1; + } + + try + { + return 0; + } + finally + { + _sem.Release(); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SensitiveLogArgumentAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/SensitiveLogArgumentAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..70b16b3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SensitiveLogArgumentAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,90 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SensitiveLogArgumentAnalyzerBranchCoverageGapTests +{ + private static readonly ReferenceAssemblies Net100WithLogging = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.Logging.Abstractions", "10.0.13")]); + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions { References = Net100WithLogging }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForParamsArraysWithoutAnInitializer() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, object[] values) + { + logger.LogInformation("a {A}", new object[2]); + logger.LogInformation("b {A}", values); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ElementsOfAnArrayThatTheCompilerConverts() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, string password, string user) + { + logger.LogInformation("a {A} {B}", new string[] { user, {|E128166:password|} }); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFormatterDelegateCarriesASensitiveName() + { + return VerifyAsync(""" + using System; + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, string payload, Func passwordFormatter) + { + logger.Log(LogLevel.Information, new EventId(1), payload, null, passwordFormatter); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForExpressionsThatKeepNoName() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, string password, int counter) + { + logger.LogInformation("a {A}", password + "!"); + logger.LogInformation("b {A}", counter++); + logger.LogInformation("c {A}", -counter); + logger.LogInformation("d {A}", new object()); + logger.LogInformation("e {A}", "literal"); + logger.LogInformation("f {A}", this); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SequentialRenameFixAllProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SequentialRenameFixAllProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..55e13e6 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SequentialRenameFixAllProviderBranchCoverageMoreTests.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using E128.Analyzers.Style; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SequentialRenameFixAllProviderBranchCoverageMoreTests +{ + private const string Source = "class C { int a = 1; int b = a; }"; + + private static async Task GetFixAsync( + Func computeNewName, + Func pickTarget) + { + using var workspace = new AdhocWorkspace(); + var project = workspace.AddProject("P", LanguageNames.CSharp) + .AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); + var document = project.AddDocument("Test.cs", Source); + var root = await document.GetSyntaxRootAsync(TestContext.Current.CancellationToken); + Assert.NotNull(root); + + var diagnostics = ImmutableArray.Empty; + if (!ReferenceEquals(pickTarget(root), root)) + { + var target = pickTarget(root); + diagnostics = [Diagnostic.Create(FakeNamingViolationAnalyzer.Rule, target.GetLocation())]; + } + + var context = new FixAllContext( + document, + new NamingStyleCodeFixProvider(), + FixAllScope.Document, + null, + ["IDE1006"], + new StaticDiagnosticProvider(diagnostics), + TestContext.Current.CancellationToken); + + var provider = new SequentialRenameFixAllProvider(computeNewName, "test"); + return await provider.GetFixAsync(context); + } + + [Fact] + [Trait("Category", "CI")] + public async Task GetFix_ReturnsNoActionWhenTheNameCalculationYieldsNoName() + { + var action = await GetFixAsync(static (_, _) => null, static root => root.DescendantNodes().OfType().First()); + + Assert.Null(action); + } + + [Fact] + [Trait("Category", "CI")] + public async Task GetFix_ReturnsNoActionWhenTheDiagnosticSitsOnANodeWithoutASymbol() + { + var action = await GetFixAsync(static (_, name) => name + "X", static root => root.DescendantNodes().OfType().First()); + + Assert.Null(action); + } + + private sealed class StaticDiagnosticProvider : FixAllContext.DiagnosticProvider + { + private readonly ImmutableArray diagnostics; + + internal StaticDiagnosticProvider(ImmutableArray diagnostics) + { + this.diagnostics = diagnostics; + } + + public override Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) + { + return Task.FromResult>(diagnostics); + } + + public override Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) + { + return Task.FromResult>(diagnostics); + } + + public override Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) + { + return Task.FromResult>(diagnostics); + } + } +} diff --git a/tests/E128.Analyzers.Tests/SkipInitCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SkipInitCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..05d52f1 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SkipInitCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,61 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SkipInitCodeFixProviderBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCallIsNotAStatement() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Runtime.CompilerServices; + class C + { + void M() + { + int value; + void Local() => {|E128120:Unsafe.SkipInit(out value)|}; + Local(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheArgumentIsAnArrayElement() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Runtime.CompilerServices; + class C + { + void M(int[] values) + { + {|E128120:Unsafe.SkipInit(out values[0])|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheArgumentIsATypedDiscard() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Runtime.CompilerServices; + class C + { + void M() + { + {|E128120:Unsafe.SkipInit(out int _)|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/StackAllocSafetyAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/StackAllocSafetyAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..f919ea2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/StackAllocSafetyAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,25 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StackAllocSafetyAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheConstantSizeIsNotAnInt() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + class C + { + void M() + { + const byte size = 16; + Span buffer = stackalloc byte[size]; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/StaticNumericIncrementCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/StaticNumericIncrementCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..a1c7fb6 --- /dev/null +++ b/tests/E128.Analyzers.Tests/StaticNumericIncrementCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StaticNumericIncrementCodeFixProviderBranchCoverageGapTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_RemovesTheOnlyModifierOfTheField() + { + return CodeFixTestRunner.RunAsync( + "class C { static int _total; int M() { return _total {|E128087:+=|} 2; } }", + "class C { int _total; int M() { return _total += 2; } }"); + } +} diff --git a/tests/E128.Analyzers.Tests/StaticReadonlyFrozenCollectionAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/StaticReadonlyFrozenCollectionAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..f08fba8 --- /dev/null +++ b/tests/E128.Analyzers.Tests/StaticReadonlyFrozenCollectionAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,42 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StaticReadonlyFrozenCollectionAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStaticReadonlyFieldIsNotAGenericNamedType() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + class C + { + private static readonly string Name = "name"; + private static readonly int[] Numbers = [1, 2, 3]; + private static readonly List Items = [1, 2, 3]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFrameworkHasNoFrozenCollections() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + + class C + { + private static readonly HashSet Items = new HashSet(); + } + """, + expected: null, + options: new AnalyzerTestOptions { References = ReferenceAssemblies.NetStandard.NetStandard20 }); + } +} diff --git a/tests/E128.Analyzers.Tests/StaticReadonlyFrozenCollectionCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/StaticReadonlyFrozenCollectionCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..b3bfb2f --- /dev/null +++ b/tests/E128.Analyzers.Tests/StaticReadonlyFrozenCollectionCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,61 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StaticReadonlyFrozenCollectionCodeFixProviderBranchCoverageGapTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsAnExplicitCreationExpression() + { + return VerifyFixAsync( + """ + using System.Collections.Generic; + class C + { + private static readonly {|E128027:HashSet Tags = new HashSet { "a", "b" }|}; + } + """, + """ + using System.Collections.Frozen; + using System.Collections.Generic; + class C + { + private static readonly FrozenSet Tags = new HashSet { "a", "b" }.ToFrozenSet(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_WrapsAFactoryCallInitializer() + { + return VerifyFixAsync( + """ + using System.Collections.Generic; + class C + { + private static readonly {|E128027:Dictionary Lookup = Build()|}; + + private static Dictionary Build() => new(); + } + """, + """ + using System.Collections.Frozen; + using System.Collections.Generic; + class C + { + private static readonly FrozenDictionary Lookup = Build().ToFrozenDictionary(); + + private static Dictionary Build() => new(); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/StringBuilderPoolCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/StringBuilderPoolCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..54033fe --- /dev/null +++ b/tests/E128.Analyzers.Tests/StringBuilderPoolCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,94 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StringBuilderPoolCodeFixProviderBranchCoverageGapTests +{ + private const string Pool = """ + namespace Pug.Core.Text + { + public abstract class StringBuilderPool + { + public static StringBuilderPool Shared => null; + public abstract System.Text.StringBuilder Rent(); + public abstract System.Text.StringBuilder Rent(int capacity); + public abstract void Return(System.Text.StringBuilder builder); + } + } + """; + + private static string Source(string body) + { + return "using System.Text;\n" + Pool + "\nclass C\n{\n void M()\n {\n" + body + "\n }\n}\n"; + } + + private static string FixedSource(string body) + { + return "using Pug.Core.Text;\nusing System.Text;\n" + Pool + "\nclass C\n{\n void M()\n {\n" + body + "\n }\n}\n"; + } + + private static Task VerifyFixAsync(string body, string fixedBody) + { + return CodeFixTestRunner.RunAsync( + Source(body), + FixedSource(fixedBody)); + } + + private static Task VerifyNoFixAsync(string body) + { + return CodeFixTestRunner.NoFixAsync(Source(body)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesATargetTypedCreation() + { + return VerifyFixAsync( + " StringBuilder sb = {|E128081:new()|};\n _ = sb.Append('a');", + " StringBuilder sb = StringBuilderPool.Shared.Rent();\n _ = sb.Append('a');"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_DropsTheCapacityOfATargetTypedCreation() + { + return VerifyFixAsync( + " StringBuilder sb = {|E128081:new(64)|};\n _ = sb.Append('a');", + " StringBuilder sb = StringBuilderPool.Shared.Rent();\n _ = sb.Append('a');"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesACreationWithoutAnArgumentList() + { + return VerifyFixAsync( + " var sb = {|E128081:new StringBuilder { Capacity = 64 }|};\n _ = sb.Append('a');", + " var sb = StringBuilderPool.Shared.Rent();\n _ = sb.Append('a');"); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCreationCarriesASeedString() + { + return VerifyNoFixAsync( + " var sb = {|E128081:new StringBuilder(\"seed\")|};\n _ = sb.Append('a');"); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCreationCarriesTwoArguments() + { + return VerifyNoFixAsync( + " var sb = {|E128081:new StringBuilder(16, 1024)|};\n _ = sb.Append('a');"); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheTargetTypedCreationCarriesASeedString() + { + return VerifyNoFixAsync( + " StringBuilder sb = {|E128081:new(\"seed\")|};\n _ = sb.Append('a');"); + } +} diff --git a/tests/E128.Analyzers.Tests/StringConcatInLoopCodeFixBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/StringConcatInLoopCodeFixBranchCoverageGapTests.cs new file mode 100644 index 0000000..bca572d --- /dev/null +++ b/tests/E128.Analyzers.Tests/StringConcatInLoopCodeFixBranchCoverageGapTests.cs @@ -0,0 +1,75 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StringConcatInLoopCodeFixBranchCoverageGapTests +{ + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheSeedIsANonEmptyLiteralOrNull() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class C + { + string FromText(List lines) + { + var result = "seed"; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result; + } + + string FromNull(List lines) + { + string result = null; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheSeedIsAMemberAccessThatIsNotNamedEmpty() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class Holder + { + public static string Other { get; } = ""; + } + + class C + { + string M(List lines) + { + var result = Holder.Other; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/StringFormatToInterpolationCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/StringFormatToInterpolationCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..a4d675b --- /dev/null +++ b/tests/E128.Analyzers.Tests/StringFormatToInterpolationCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,45 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StringFormatToInterpolationCodeFixProviderBranchCoverageGapTests +{ + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAClosingBraceIsFollowedByText() + { + return VerifyNoFixAsync( + """ + class C + { + void M(int n) + { + var s = {|E128015:string.Format("} {0}", n)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnOpeningBraceEndsTheFormat() + { + return VerifyNoFixAsync( + """ + class C + { + void M(int n) + { + var s = {|E128015:string.Format("{0} {", n)|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SubstringLengthUnderflowAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SubstringLengthUnderflowAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..121185b --- /dev/null +++ b/tests/E128.Analyzers.Tests/SubstringLengthUnderflowAnalyzerBranchCoverageMoreTests.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 SubstringLengthUnderflowAnalyzerBranchCoverageMoreTests +{ + private static AnalyzerTestOptions Lenient => new() { CompilerDiagnostics = CompilerDiagnostics.None }; + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSubstringCallDoesNotResolve() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + string M(Missing s) => s.Substring(0, s.Length - 1); + } + """, + options: Lenient); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCallStartsItsOwnStatement() + { + return AnalyzerTestRunner.VerifyAsync(""" + class C + { + void M(string s) + { + {|E128198:s.Substring(0, s.Length - 1)|}.Trim(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheConditionOnlyCallsUnrelatedMethods() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + + class C + { + static bool Check() => true; + + string M(string s, List list) + { + if (Check() || s.ToUpper() == string.Empty || list.Contains(1) || Missing.Probe(2)) + { + return {|E128198:s.Substring(0, s.Length - 1)|}; + } + + return s; + } + } + """, + options: Lenient); + } +} diff --git a/tests/E128.Analyzers.Tests/SuppressionAuditAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SuppressionAuditAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..925e17d --- /dev/null +++ b/tests/E128.Analyzers.Tests/SuppressionAuditAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,72 @@ +using System.Threading.Tasks; +using E128.Analyzers.Style; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SuppressionAuditAnalyzerBranchCoverageMoreTests +{ + private static AnalyzerTestOptions Options => new() { TestBehaviors = TestBehaviors.SkipSuppressionCheck }; + + private static DiagnosticResult Diagnostic(int line, int column) + { + return new DiagnosticResult("E128047", DiagnosticSeverity.Warning) + .WithLocation(line, column); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenABlankLineSeparatesTheCommentFromThePragma() + { + const string code = """ + // The reason sits above a blank line. + + #pragma warning disable CS1591 + class C { } + #pragma warning restore CS1591 + """; + + return AnalyzerTestRunner.VerifyAsync(code, Diagnostic(3, 1), options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherDirectiveIsTheOnlyPrecedingTrivia() + { + const string code = """ + #nullable enable + #pragma warning disable CS1591 + class C { } + #pragma warning restore CS1591 + """; + + return AnalyzerTestRunner.VerifyAsync(code, Diagnostic(2, 1), options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALeadingBlankLineIsTheOnlyPrecedingTrivia() + { + const string code = "\n#pragma warning disable CS1591\nclass C { }\n#pragma warning restore CS1591\n"; + + return AnalyzerTestRunner.VerifyAsync(code, Diagnostic(2, 1), options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnIndentedPragmaHasNoComment() + { + const string code = """ + class C + { + #pragma warning disable CS1591 + public int Value; + #pragma warning restore CS1591 + } + """; + + return AnalyzerTestRunner.VerifyAsync(code, Diagnostic(3, 5), options: Options); + } +} diff --git a/tests/E128.Analyzers.Tests/SwitchEnumExhaustivenessAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/SwitchEnumExhaustivenessAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..418511f --- /dev/null +++ b/tests/E128.Analyzers.Tests/SwitchEnumExhaustivenessAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,89 @@ +using System.Threading.Tasks; +using E128.Analyzers.Maintainability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SwitchEnumExhaustivenessAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + "enum Color { Red, Green, Blue }\n" + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnExpressionWithAGuardedDiscardArm() + { + return VerifyAsync(""" + class C + { + int M(Color c, bool flag) => c {|E128088:switch|} + { + Color.Red => 1, + _ when flag => 2, + }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnExpressionWithAGuardedVarArm() + { + return VerifyAsync(""" + class C + { + int M(Color c, bool flag) => c {|E128088:switch|} + { + Color.Red => 1, + var other when flag => 2, + }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenThePatternIsNotAConstantOrAnOrPattern() + { + return VerifyAsync(""" + class C + { + void M(Color c) + { + {|E128088:switch|} (c) + { + case Color.Green and not Color.Blue: + break; + case > Color.Green: + break; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCaseNamesAConstantThatIsNotAnEnumField() + { + return VerifyAsync(""" + class C + { + void M(Color c) + { + const Color local = Color.Red; + {|E128088:switch|} (c) + { + case local: + break; + case (Color)7: + break; + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..2693fd2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,84 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TaskCompletionSourceOptionsAnalyzerBranchCoverageGapTests +{ + private static readonly AnalyzerTestOptions NoCompilerDiagnostics = new() { MarkupOptions = MarkupOptions.UseFirstDescriptor, CompilerDiagnostics = CompilerDiagnostics.None }; + + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + source, + expected: null, + options ?? new AnalyzerTestOptions { MarkupOptions = MarkupOptions.UseFirstDescriptor }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenSetResultBelongsToAnotherType() + { + return VerifyAsync(""" + class Signal + { + public void SetResult(int value) { } + } + + class C + { + private readonly Signal _signal = new(); + + void M() + { + _signal.SetResult(1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverTypeCannotBeBound() + { + return VerifyAsync( + """ + class C + { + private readonly Missing _source; + + void M() + { + _source.SetResult(1); + } + } + """, + NoCompilerDiagnostics); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnUnboundCallSitsInTheGuardCondition() + { + return VerifyAsync( + """ + using System.Threading.Tasks; + class C + { + private readonly TaskCompletionSource _source = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + void M(int value) + { + if (Missing() == 0) + { + {|E128159:_source.SetResult(value)|}; + } + } + } + """, + NoCompilerDiagnostics); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..f8d5d01 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,57 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TaskCompletionSourceOptionsCodeFixProviderBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheDiagnosticReportsASharedSetResultCall() + { + const string Code = """ + using System.Threading.Tasks; + class C + { + private static readonly TaskCompletionSource Shared = new(TaskCreationOptions.RunContinuationsAsynchronously); + + void M() + { + {|#0:Shared.SetResult(1)|}; + } + } + """; + + const string Unchanged = """ + using System.Threading.Tasks; + class C + { + private static readonly TaskCompletionSource Shared = new(TaskCreationOptions.RunContinuationsAsynchronously); + + void M() + { + Shared.SetResult(1); + } + } + """; + + var test = new CSharpCodeFixTest< + TaskCompletionSourceOptionsAnalyzer, + TaskCompletionSourceOptionsCodeFixProvider, + DefaultVerifier> + { + TestCode = Code, + FixedCode = Unchanged, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + }; + + test.ExpectedDiagnostics.Add(new DiagnosticResult("E128159", DiagnosticSeverity.Warning).WithLocation(0)); + test.FixedState.ExpectedDiagnostics.Add(new DiagnosticResult("E128159", DiagnosticSeverity.Warning).WithLocation(8, 9)); + + return test.RunAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskFromResultSyncIoAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/TaskFromResultSyncIoAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..3b28117 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskFromResultSyncIoAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,49 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TaskFromResultSyncIoAnalyzerBranchCoverageGapTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMethodAwaitsBeforeItReturnsAFromResultTask() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.IO; + using System.Threading.Tasks; + class C + { + async Task M(string path) + { + await Task.Delay(1); + File.WriteAllText(path, "x"); + return Task.FromResult(1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFromResultCallDoesNotBind() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.IO; + using System.Threading.Tasks; + class C + { + Task M(string path) + { + File.WriteAllText(path, "x"); + return Task.FromResult(); + } + } + """, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskFromResultSyncIoCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/TaskFromResultSyncIoCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..a951c4a --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskFromResultSyncIoCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,96 @@ +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 TaskFromResultSyncIoCodeFixProviderBranchCoverageMoreTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return new CSharpCodeFixTest + { + TestCode = source, + FixedCode = fixedCode, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + CompilerDiagnostics = CompilerDiagnostics.None, + NumberOfFixAllIterations = 1 + }.RunAsync(TestContext.Current.CancellationToken); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_LeavesAnUnresolvedCallThatSharesAMethodName() + { + return VerifyFixAsync( + """ + using System.IO; + using System.Threading.Tasks; + class C + { + Task M(string path) + { + var other = Missing.ReadAllText(path); + var text = File.ReadAllText(path); + return {|E128028:Task.FromResult(text)|}; + } + } + """, + """ + using System.IO; + using System.Threading.Tasks; + class C + { + async Task M(string path) + { + var other = Missing.ReadAllText(path); + var text = await File.ReadAllTextAsync(path); + return text; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_LeavesAFromResultCallWithoutExactlyOneArgument() + { + return VerifyFixAsync( + """ + using System.IO; + using System.Threading.Tasks; + class C + { + Task M(string path, bool flag) + { + if (flag) + { + return Task.FromResult(); + } + + var text = File.ReadAllText(path); + return {|E128028:Task.FromResult(text)|}; + } + } + """, + """ + using System.IO; + using System.Threading.Tasks; + class C + { + async Task M(string path, bool flag) + { + if (flag) + { + return Task.FromResult(); + } + + var text = await File.ReadAllTextAsync(path); + return text; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskRunAsyncLambdaAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/TaskRunAsyncLambdaAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..61ffed7 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskRunAsyncLambdaAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,122 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TaskRunAsyncLambdaAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenARunMethodTakesNoArguments() + { + return AnalyzerTestRunner.VerifyAsync(""" + class Worker + { + public void Run() + { + } + } + + class C + { + void M(Worker worker) + { + worker.Run(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRunCallDoesNotBind() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Threading.Tasks; + class C + { + async Task M() + { + await Task.Run(async () => await Task.Delay(1), 5, 6); + } + } + """, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAsyncLambdasPassedToOtherRunMethods() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + + class Other + { + public static Task Run(Func action) => action(1); + } + + class C + { + Func, Task> Run { get; } = action => action(); + + async Task M() + { + await Other.Run(async count => await Task.Delay(count)); + await this.Run(async () => await Task.Delay(1)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForATaskTypeInAnotherNamespace() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + + namespace Mine + { + class Task + { + public static System.Threading.Tasks.Task Run(Func action) => action(); + } + } + + class C + { + void M() + { + _ = Mine.Task.Run(async () => await System.Threading.Tasks.Task.Delay(1)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForSynchronousAnonymousMethodsAndMethodGroups() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading.Tasks; + class C + { + static void Work() + { + } + + async Task M() + { + await Task.Run(delegate { }); + await Task.Run(Work); + await Task.Run(delegate { return 1; }); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationCodeFixProviderBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationCodeFixProviderBranchCoverageGapTests.cs new file mode 100644 index 0000000..0444422 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationCodeFixProviderBranchCoverageGapTests.cs @@ -0,0 +1,101 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TaskWhenAllCancellationPropagationCodeFixProviderBranchCoverageGapTests +{ + private const string Header = """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + class Service + { + public Task GetAsync(string url) => Task.CompletedTask; + + public Task GetAsync(string url, CancellationToken token) => Task.CompletedTask; + + public Task GetAsync(string url) => Task.CompletedTask; + + public Task PutAsync(string url, object? body) => Task.CompletedTask; + + public Task PutAsync(string url, object? body, CancellationToken token) => Task.CompletedTask; + } + + """; + + [Fact] + [Trait("Category", "CI")] + public Task Fix_SkipsPlainAndGenericCallsInsideTheLambda() + { + return CodeFixTestRunner.RunAsync( + Header + """ + class C + { + static Task Pause(string url) => Task.CompletedTask; + + async Task M(IEnumerable urls, Service service, CancellationToken stopToken) + { + await {|E128038:Task.WhenAll(urls.Select(async url => + { + await Pause(url); + await service.GetAsync(url); + await service.GetAsync(url); + }))|}; + } + } + """, + Header + """ + class C + { + static Task Pause(string url) => Task.CompletedTask; + + async Task M(IEnumerable urls, Service service, CancellationToken stopToken) + { + await Task.WhenAll(urls.Select(async url => + { + await Pause(url); + await service.GetAsync(url); + await service.GetAsync(url, stopToken); + })); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AppendsTheTokenAfterANullArgument() + { + return CodeFixTestRunner.RunAsync( + Header + """ + class C + { + async Task M(IEnumerable urls, Service service, CancellationToken stopToken) + { + await {|E128038:Task.WhenAll(urls.Select(async url => + { + await service.PutAsync(url, null); + }))|}; + } + } + """, + Header + """ + class C + { + async Task M(IEnumerable urls, Service service, CancellationToken stopToken) + { + await Task.WhenAll(urls.Select(async url => + { + await service.PutAsync(url, null, stopToken); + })); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TempDirCleanupAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/TempDirCleanupAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..7988293 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TempDirCleanupAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,130 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TempDirCleanupAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheConstructorPassesThePathStraightToACall() + { + return VerifyAsync(""" + using System.IO; + + class {|E128054:MyTests|} + { + public MyTests() + { + Directory.CreateDirectory(Path.GetTempPath()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsInAnExpressionBodiedMemberOrOperator() + { + return VerifyAsync(""" + using System; + using System.IO; + + class MyTests + { + public string Root => Path.GetTempPath(); + + public Func Factory => () => + { + var path = Path.GetTempPath(); + return path; + }; + + public static MyTests operator +(MyTests left, MyTests right) + { + var path = Path.GetTempPath(); + return left; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsInAParameterDefault() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.IO; + + class MyTests + { + public void Run(string root = Path.GetTempPath()) + { + } + } + """, + expected: null, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheClassImplementsIAsyncDisposable() + { + return VerifyAsync(""" + using System; + using System.IO; + using System.Threading.Tasks; + + class MyTests : IAsyncDisposable + { + private readonly string _root = Path.GetTempPath(); + + public ValueTask DisposeAsync() => default; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheClassImplementsAnAsyncLifetimeStandIn() + { + return VerifyAsync(""" + using System.IO; + + interface IAsyncLifetime + { + } + + class MyTests : IAsyncLifetime + { + private readonly string _root = Path.GetTempPath(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheClassImplementsOnlyAnUnrelatedInterface() + { + return VerifyAsync(""" + using System; + using System.IO; + + class {|E128054:MyTests|} : IComparable + { + private readonly string _root = Path.GetTempPath(); + + public int CompareTo(object obj) => 0; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TimingSafeComparisonBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/TimingSafeComparisonBranchCoverageGapTests.cs new file mode 100644 index 0000000..8596a4c --- /dev/null +++ b/tests/E128.Analyzers.Tests/TimingSafeComparisonBranchCoverageGapTests.cs @@ -0,0 +1,269 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TimingSafeComparisonBranchCoverageGapTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForGenericAndUnresolvedInvocations() + { + return VerifyAsync(""" + class C + { + void M(byte[] data, byte[] tag) + { + Local(); + SequenceEqual(tag); + SequenceEqual(); + {|CS0103:Missing|}.SequenceEqual(data, tag); + {|CS0103:missing|}.Equals(tag); + } + + void Local() + { + } + + bool SequenceEqual(byte[] other) => true; + + bool SequenceEqual() => true; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForATwoArgumentInstanceMethodNamedSequenceEqual() + { + return VerifyAsync(""" + class Comparer + { + public bool SequenceEqual(byte[] left, byte[] right) => true; + } + + class C + { + bool M(Comparer comparer, byte[] computedTag, byte[] expectedTag) + { + return comparer.SequenceEqual(computedTag, expectedTag); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStringEqualsCallIsUnqualifiedOrBelongsToAnotherType() + { + return VerifyAsync(""" + class Other + { + public bool Equals(string left, string right) => true; + } + + class C + { + bool M(string computedTag, string expectedTag, Other other) + { + var a = Equals(computedTag); + var b = other.Equals(computedTag, expectedTag); + return a && b; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnOperandHasNoSymbolAndNoSecretName() + { + return VerifyAsync(""" + class C + { + bool M(bool flag, string left, string right, string other) + { + var a = (flag ? left : right) == other; + var b = other == (flag ? left : right); + return a && b; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWeakNameOperandIsAForeachOrUninitializedLocal() + { + return VerifyAsync(""" + using System.Collections.Generic; + class C + { + bool M(List tokens, string expectedToken) + { + var found = false; + foreach (var token in tokens) + { + found = {|E128157:token == expectedToken|}; + } + + string digest; + digest = tokens[0]; + return found && {|E128157:digest == expectedToken|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAStringInvocationDoesNotResolve() + { + return VerifyAsync(""" + class C + { + static string Compute(int value) => "x"; + + bool M(string left) + { + return left == Compute({|CS1503:"x"|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenHashMembersAreFieldsOrPlainProperties() + { + return VerifyAsync(""" + class Holder + { + public string Hash = ""; + } + + class Wrapper + { + public string Hash { get; set; } = ""; + } + + class C + { + bool M(Holder left, Holder right, Wrapper first, Wrapper second) + { + var a = left.Hash == right.Hash; + var b = first.Hash == second.Hash; + return a && b; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSecretFieldIsInitializedInAnotherSyntaxTree() + { + return AnalyzerTestRunner.VerifyAsync( + [ + """ + using System; + using System.Security.Cryptography; + + partial class C + { + private static readonly string Computed = Convert.ToHexString(new HMACSHA256(new byte[32]).ComputeHash(new byte[1])); + } + """, + """ + partial class C + { + bool M(string other) + { + return Computed == other; + } + } + """ + ]); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheIncrementalHashLocalHasNoHmacCreation() + { + return VerifyAsync(""" + using System; + using System.Collections.Generic; + using System.Security.Cryptography; + class C + { + private IncrementalHash field; + + bool M(List hashes, string text) + { + foreach (var each in hashes) + { + var a = Convert.ToHexString(each.GetHashAndReset()) == text; + } + + IncrementalHash declared; + declared = hashes[0]; + var b = Convert.ToHexString(declared.GetHashAndReset()) == text; + var c = Convert.ToHexString(field.GetHashAndReset()) == text; + return b && c; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheOperandIsAnUnqualifiedStringCall() + { + return VerifyAsync(""" + class C + { + static string Compute() => "x"; + + bool M(string other) + { + return Compute() == other; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_OnlyWhenTheEncoderChainStaysWithinTheDepthLimit() + { + return VerifyAsync(""" + using System.Security.Cryptography; + + namespace System + { + public static class Convert + { + public static string ToHexString(byte[] bytes) => string.Empty; + + public static string ToHexString(string text) => text; + } + } + + class C + { + bool M(HMACSHA256 hmac, byte[] data, string other) + { + var within = {|E128157:System.Convert.ToHexString(System.Convert.ToHexString(System.Convert.ToHexString(hmac.ComputeHash(data)))) == other|}; + var beyond = System.Convert.ToHexString(System.Convert.ToHexString(System.Convert.ToHexString(System.Convert.ToHexString(hmac.ComputeHash(data))))) == other; + return within && beyond; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnboundedTaskWhenAllAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/UnboundedTaskWhenAllAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..4247ed7 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnboundedTaskWhenAllAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,145 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnboundedTaskWhenAllAnalyzerBranchCoverageGapTests +{ + private const string Header = """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + + """; + + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(Header + source, expected: null, options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheAsyncSelectorIsAParenthesizedLambda() + { + return VerifyAsync(""" + class C + { + static Task Work(int item) => Task.CompletedTask; + + async Task M(IEnumerable items) + { + await {|E128037:Task.WhenAll(items.Select(async (x) => await Work(x)))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenASelectMethodTakesNoArguments() + { + return VerifyAsync(""" + class Source + { + public IEnumerable Select() => new List(); + } + + class C + { + async Task M(Source source) + { + await Task.WhenAll(source.Select()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSelectorReturnsATypeParameter() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable items, Func make) + where T : Task + { + await Task.WhenAll(items.Select(x => make(x))); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRunCallIsUnqualified() + { + return VerifyAsync(""" + class C + { + static Task Run(Func work) => Task.CompletedTask; + + async Task M(IReadOnlyList items) + { + var tasks = new List(); + foreach (var item in items) + { + tasks.Add(Run(() => item)); + } + + await Task.WhenAll(tasks); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRunCallDoesNotBind() + { + return VerifyAsync( + """ + class C + { + async Task M(IReadOnlyList items) + { + var tasks = new List(); + foreach (var item in items) + { + tasks.Add(Task.Run(1, 2, 3)); + } + + await Task.WhenAll(tasks); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitAsyncCallIsDynamic() + { + return VerifyAsync( + """ + class C + { + async Task M(IReadOnlyList items, dynamic gate) + { + var tasks = new List(); + foreach (var item in items) + { + tasks.Add({|E128037:Task.Run(async () => await gate.WaitAsync())|}); + } + + await Task.WhenAll(tasks); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/UncontainedRootJoinAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/UncontainedRootJoinAnalyzerBranchCoverageGapTests.cs new file mode 100644 index 0000000..df30cd0 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UncontainedRootJoinAnalyzerBranchCoverageGapTests.cs @@ -0,0 +1,104 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UncontainedRootJoinAnalyzerBranchCoverageGapTests +{ + private const string Guards = """ + static class Guard + { + public static bool IsInside(object path) => true; + } + + class Holder + { + public string Name = ""; + } + """; + + private static Task VerifyAsync(string code, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + code + "\n" + Guards, + expected: null, + options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCombineReceiverCannotBeBound() + { + return VerifyAsync( + """ + using System.IO; + class C + { + string M(DirectoryInfo root, string leaf) + { + return Missing.Combine(root.FullName, leaf); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnInterpolationHoleHasNoType() + { + return VerifyAsync(""" + using System.IO; + class C + { + string M(DirectoryInfo root) + { + return {|E128222:Path.Combine(root.FullName, $"{null}")|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAssignmentsBeforeTheGuardCarryOtherValues() + { + return VerifyAsync(""" + using System.IO; + class C + { + void M(DirectoryInfo root, string leaf, Holder holder) + { + string other; + other = leaf; + holder.Name = leaf; + var joined = {|E128222:Path.Combine(root.FullName, leaf)|}; + Guard.IsInside(other); + Guard.IsInside(holder.Name); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLeafIsAGenericOrDelegateCall() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + static T Identity(T value) => value; + + void M(DirectoryInfo root, string leaf, Func[] maps) + { + var first = {|E128222:Path.Combine(root.FullName, Identity(leaf))|}; + var second = {|E128222:Path.Combine(root.FullName, maps[0](leaf))|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UncontainedRootJoinCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/UncontainedRootJoinCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..8e5ea28 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UncontainedRootJoinCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,94 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UncontainedRootJoinCodeFixProviderBranchCoverageMoreTests +{ + private const string Containment = """ + namespace Pug.Core + { + public static class FilePathContainment + { + public static System.IO.FileInfo ResolveInside(System.IO.DirectoryInfo root, string leaf) + => new System.IO.FileInfo(leaf); + } + } + """; + + private static Task NoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync( + source + "\n" + Containment); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnAliasQualifiedFileInfoTypeIsNotSystemFileInfo() + { + return NoFixAsync(""" + using System.IO; + + class FileInfo + { + public FileInfo(string path) { } + } + + class C + { + object M(DirectoryInfo root, string leaf) + { + return new global::FileInfo({|E128222:Path.Combine(root.FullName, leaf)|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheJoinFeedsAGenericTypeConstruction() + { + return NoFixAsync(""" + using System.IO; + + class Wrapper + { + public Wrapper(string path) { } + } + + class C + { + object M(DirectoryInfo root, string leaf) + { + return new Wrapper({|E128222:Path.Combine(root.FullName, leaf)|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheJoinFeedsAQualifiedTypeThatIsNotNamedFileInfo() + { + return NoFixAsync(""" + using System.IO; + + namespace Other + { + public sealed class Reader + { + public Reader(string path) { } + } + } + + class C + { + object M(DirectoryInfo root, string leaf) + { + return new Other.Reader({|E128222:Path.Combine(root.FullName, leaf)|}); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..7ff5cf4 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,147 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnionSwitchDiscardArmAnalyzerBranchCoverageMoreTests +{ + private const string UnionSource = + """ + enum Greeting { Hello } + enum GreetingError { NotSubscribed, NotAllowed } + union GreetingResult(Greeting, GreetingError) + { + } + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions + { + LanguageVersion = LanguageVersion.Preview, + Sources = [UnionTestRuntime.StubSource], + SuppressedDiagnosticIds = ["RSEXPERIMENTAL006"], + }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenASwitchExpressionEndsInAVarArm() + { + return VerifyAsync( + UnionSource + """ + + internal static class Switcher + { + internal static int Switch(GreetingResult result) + { + return result switch + { + Greeting => 1, + GreetingError => 2, + {|E128220:var other|} => 0 + }; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenASwitchStatementGovernsANonUnionType() + { + return VerifyAsync( + """ + internal static class Switcher + { + internal static int Switch(int value) + { + switch (value) + { + case 0: return 1; + default: return 2; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenASwitchStatementEndsInANullArm() + { + return VerifyAsync( + UnionSource + """ + + internal static class Switcher + { + internal static int Switch(GreetingResult result) + { + switch (result) + { + case Greeting: return 1; + case GreetingError: return 2; + case null: return 0; + } + + return 3; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenASwitchStatementHasNoCatchAllArm() + { + return VerifyAsync( + UnionSource + """ + + internal static class Switcher + { + internal static int Switch(GreetingResult result) + { + switch (result) + { + case Greeting: return 1; + case GreetingError: return 2; + } + + return 3; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGoverningTypeIsAnArrayOrATypeParameter() + { + return VerifyAsync( + """ + internal static class Switcher + { + internal static int Switch(int[] values) + { + return values switch + { + [] => 0, + _ => 1 + }; + } + + internal static int Generic(T value) + { + return value switch + { + _ => 0 + }; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnsafeAsPointerEscapeAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/UnsafeAsPointerEscapeAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..84754b3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnsafeAsPointerEscapeAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,158 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnsafeAsPointerEscapeAnalyzerBranchCoverageMoreTests +{ + private static AnalyzerTestOptions Options => new() { AllowUnsafe = true }; + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePointerTargetsAStackLocalInAPlainLambdaOrLocalFunction() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Runtime.CompilerServices; + unsafe class C + { + void M() + { + Action action = () => + { + int number = 1; + void* pointer = Unsafe.AsPointer(ref number); + }; + + void Local() + { + int number = 2; + void* pointer = Unsafe.AsPointer(ref number); + } + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheStackLocalLivesInAnAsyncLambda() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + class C + { + void M() + { + Func action = async () => + { + int number = 1; + unsafe + { + void* pointer = {|E128125:Unsafe.AsPointer(ref number)|}; + } + + await Task.Yield(); + }; + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheStackLocalLivesInAnAsyncLocalFunction() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + class C + { + void M() + { + async Task Local() + { + int number = 1; + unsafe + { + void* pointer = {|E128125:Unsafe.AsPointer(ref number)|}; + } + + await Task.Yield(); + } + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePointerTargetsAStackLocalInAPropertyAccessor() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Runtime.CompilerServices; + unsafe class C + { + int Value + { + get + { + int number = 1; + void* pointer = Unsafe.AsPointer(ref number); + return number; + } + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenThePointerTargetsARefLocalOrARefParameter() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Runtime.CompilerServices; + unsafe class C + { + void M(ref int parameter) + { + int number = 1; + ref int alias = ref number; + void* first = {|E128125:Unsafe.AsPointer(ref alias)|}; + void* second = {|E128125:Unsafe.AsPointer(ref parameter)|}; + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFrameworkHasNoUnsafeClass() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M() + { + } + } + """, + expected: null, + options: new AnalyzerTestOptions { References = ReferenceAssemblies.NetStandard.NetStandard20 }); + } +} diff --git a/tests/E128.Analyzers.Tests/UnsafeBooleanConversionsCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/UnsafeBooleanConversionsCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..20b911c --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnsafeBooleanConversionsCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,54 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnsafeBooleanConversionsCodeFixProviderBranchCoverageMoreTests +{ + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCallUsesAStaticImportWithoutAMemberAccess() + { + return VerifyNoFixAsync(""" + using static System.Runtime.CompilerServices.Unsafe; + class C + { + bool M(ref int value) => {|E128115:As(ref value)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheSourceTypeIsSpelledWithItsFrameworkName() + { + return VerifyNoFixAsync(""" + using System; + using System.Runtime.CompilerServices; + class C + { + bool M(ref int value) => {|E128115:Unsafe.As(ref value)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheBoolSourceHasAFrameworkNamedTarget() + { + return VerifyNoFixAsync(""" + using System; + using System.Runtime.CompilerServices; + class C + { + int M(ref bool value) => {|E128115:Unsafe.As(ref value)|}; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnsafeUnalignedNonBlittableAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/UnsafeUnalignedNonBlittableAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..5a1647e --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnsafeUnalignedNonBlittableAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,80 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnsafeUnalignedNonBlittableAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInvokedExpressionHasNoSimpleName() + { + return VerifyAsync(""" + using System; + class C + { + int M(Func> factory) + { + return factory()(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTargetIsATypeParameter() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + class C + { + T M(ref byte source) + { + return Unsafe.ReadUnaligned(ref source); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnotherTypeDeclaresReadUnaligned() + { + return VerifyAsync(""" + class Own + { + public static T ReadUnaligned(int offset) => default!; + } + + class C + { + bool M() + { + return Own.ReadUnaligned(0); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsDynamic() + { + return VerifyAsync(""" + class C + { + object M(dynamic reader) + { + return reader.ReadUnaligned(0); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnsafeUnalignedNonBlittableCodeFixProviderBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/UnsafeUnalignedNonBlittableCodeFixProviderBranchCoverageMoreTests.cs new file mode 100644 index 0000000..697a8a3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnsafeUnalignedNonBlittableCodeFixProviderBranchCoverageMoreTests.cs @@ -0,0 +1,124 @@ +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 UnsafeUnalignedNonBlittableCodeFixProviderBranchCoverageMoreTests +{ + private static Task NoFixAsync(string source) + { + var test = new CSharpCodeFixTest< + UnsafeUnalignedNonBlittableAnalyzer, + UnsafeUnalignedNonBlittableCodeFixProvider, + DefaultVerifier> + { + TestCode = source, + FixedCode = source, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + }; + + test.SolutionTransforms.Add(CodeFixTestRunner.AllowUnsafe); + + return test.RunAsync(TestContext.Current.CancellationToken); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCallWritesInsteadOfReads() + { + return NoFixAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M(ref byte destination) + { + {|E128139:Unsafe.WriteUnaligned(ref destination, true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheTypeArgumentIsInferred() + { + return NoFixAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M(ref byte destination) + { + {|E128139:Unsafe.WriteUnaligned(ref destination, true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheTypeArgumentIsAnotherNonBlittableType() + { + return NoFixAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + string M(ref byte source) + { + return {|E128139:Unsafe.ReadUnaligned(ref source)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheTypeArgumentIsNotWrittenAsTheBoolKeyword() + { + return NoFixAsync(""" + using System; + using System.Runtime.CompilerServices; + unsafe class C + { + bool M(ref byte source) + { + return {|E128139:Unsafe.ReadUnaligned(ref source)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheReadIsAStatementByItself() + { + return NoFixAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M(ref byte source) + { + {|E128139:Unsafe.ReadUnaligned(ref source)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheArgumentIsAPointer() + { + return NoFixAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + bool M(byte* source) + { + return {|E128139:Unsafe.ReadUnaligned(source)|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnusedInterfaceParamAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/UnusedInterfaceParamAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..2c1ba23 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnusedInterfaceParamAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,77 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnusedInterfaceParamAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheImplementationHasNoParameters() + { + return AnalyzerTestRunner.VerifyAsync(""" + interface IProcessor + { + string Process(); + } + class Processor : IProcessor + { + public string Process() + { + return "constant"; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnExpressionBodiedImplementation() + { + return AnalyzerTestRunner.VerifyAsync(""" + interface IProcessor + { + string Process(string input); + } + class Processor : IProcessor + { + public string Process({|E128059:string input|}) => "constant"; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnAbstractImplementationWithoutABody() + { + return AnalyzerTestRunner.VerifyAsync(""" + interface IProcessor + { + string Process(string input); + } + abstract class Processor : IProcessor + { + public abstract string Process(string input); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForConstructorsAndRecordMembers() + { + return AnalyzerTestRunner.VerifyAsync(""" + interface IMarker + { + } + record Person(string Name) : IMarker; + class Holder : IMarker + { + public Holder(int count) + { + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..23ae89f --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,123 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnvalidatedJwtIdentityAnalyzerBranchCoverageMoreTests +{ + private const string TokenBaseStub = """ + namespace Microsoft.IdentityModel.Tokens + { + public class SecurityToken { } + public class TokenValidationParameters { } + public class TokenValidationResult { public bool IsValid { get; set; } } + } + """; + + private const string JwtStub = """ + namespace System.IdentityModel.Tokens.Jwt + { + public class JwtSecurityToken : Microsoft.IdentityModel.Tokens.SecurityToken + { + public JwtSecurityToken() { } + public JwtSecurityToken(string token) { } + public JwtSecurityToken(byte[] raw) { } + public System.Collections.Generic.IEnumerable Claims => []; + } + public class JwtSecurityTokenHandler + { + public virtual JwtSecurityToken ReadJwtToken(string token) => new(); + public virtual Microsoft.IdentityModel.Tokens.SecurityToken ReadToken(string token) => new JwtSecurityToken(); + public virtual System.Security.Claims.ClaimsPrincipal ValidateToken(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters, out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken) + { + validatedToken = new(); + return new(); + } + public virtual System.Threading.Tasks.Task ValidateTokenAsync(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters) => System.Threading.Tasks.Task.FromResult(new Microsoft.IdentityModel.Tokens.TokenValidationResult()); + } + } + """; + + private const string JsonStub = """ + namespace Microsoft.IdentityModel.JsonWebTokens + { + public class JsonWebToken : Microsoft.IdentityModel.Tokens.SecurityToken + { + public System.Collections.Generic.IEnumerable Claims => []; + } + public class JsonWebTokenHandler + { + public virtual JsonWebToken ReadJsonWebToken(string token) => new(); + public virtual Microsoft.IdentityModel.Tokens.TokenValidationResult ValidateToken(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters) => new(); + } + } + """; + + private const string HttpStub = """ + namespace Microsoft.AspNetCore.Http + { + public abstract class HttpContext + { + public abstract System.Security.Claims.ClaimsPrincipal User { get; set; } + } + } + """; + + private const string TicketStub = """ + namespace Microsoft.AspNetCore.Authentication + { + public class AuthenticationTicket + { + public AuthenticationTicket(System.Security.Claims.ClaimsPrincipal principal, string authenticationScheme) { } + } + } + """; + + private static readonly string FullStubs = string.Join("\n", TokenBaseStub, JwtStub, JsonStub, HttpStub, TicketStub); + + private static Task VerifyAsync(string source) + { + return VerifyWithAsync(source, FullStubs); + } + + private static Task VerifyWithAsync(string source, string stubs) + { + return AnalyzerTestRunner.VerifyAsync( + source, + options: new AnalyzerTestOptions { Sources = [stubs] }); + } + + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenClaimsAreAddedToAnIdentityThatIsNotAuthenticated() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + static ClaimsIdentity Create() + { + return new ClaimsIdentity(); + } + + void Empty(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var identity = new ClaimsIdentity(); + identity.AddClaims(handler.ReadJwtToken(token).Claims); + context.User = new ClaimsPrincipal(identity); + } + + void FromHelper(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var identity = Create(); + identity.AddClaims(handler.ReadJwtToken(token).Claims); + context.User = new ClaimsPrincipal(identity); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityBranchCoverageGapTests.cs new file mode 100644 index 0000000..8962da0 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityBranchCoverageGapTests.cs @@ -0,0 +1,539 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnvalidatedJwtIdentityBranchCoverageGapTests +{ + private const string TokenBaseStub = """ + namespace Microsoft.IdentityModel.Tokens + { + public class SecurityToken { } + public class TokenValidationParameters { } + public class TokenValidationResult { public bool IsValid { get; set; } } + } + """; + + private const string JwtStub = """ + namespace System.IdentityModel.Tokens.Jwt + { + public class JwtSecurityToken : Microsoft.IdentityModel.Tokens.SecurityToken + { + public JwtSecurityToken() { } + public JwtSecurityToken(string token) { } + public JwtSecurityToken(byte[] raw) { } + public System.Collections.Generic.IEnumerable Claims => []; + } + public class JwtSecurityTokenHandler + { + public virtual JwtSecurityToken ReadJwtToken(string token) => new(); + public virtual Microsoft.IdentityModel.Tokens.SecurityToken ReadToken(string token) => new JwtSecurityToken(); + public virtual System.Security.Claims.ClaimsPrincipal ValidateToken(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters, out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken) + { + validatedToken = new(); + return new(); + } + public virtual System.Threading.Tasks.Task ValidateTokenAsync(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters) => System.Threading.Tasks.Task.FromResult(new Microsoft.IdentityModel.Tokens.TokenValidationResult()); + } + } + """; + + private const string JsonStub = """ + namespace Microsoft.IdentityModel.JsonWebTokens + { + public class JsonWebToken : Microsoft.IdentityModel.Tokens.SecurityToken + { + public System.Collections.Generic.IEnumerable Claims => []; + } + public class JsonWebTokenHandler + { + public virtual JsonWebToken ReadJsonWebToken(string token) => new(); + public virtual Microsoft.IdentityModel.Tokens.TokenValidationResult ValidateToken(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters) => new(); + } + } + """; + + private const string HttpStub = """ + namespace Microsoft.AspNetCore.Http + { + public abstract class HttpContext + { + public abstract System.Security.Claims.ClaimsPrincipal User { get; set; } + } + } + """; + + private const string TicketStub = """ + namespace Microsoft.AspNetCore.Authentication + { + public class AuthenticationTicket + { + public AuthenticationTicket(System.Security.Claims.ClaimsPrincipal principal, string authenticationScheme) { } + } + } + """; + + private static readonly string FullStubs = string.Join("\n", TokenBaseStub, JwtStub, JsonStub, HttpStub, TicketStub); + + private static Task VerifyAsync(string source) + { + return VerifyWithAsync(source, FullStubs); + } + + private static Task VerifyWithAsync(string source, string stubs) + { + return AnalyzerTestRunner.VerifyAsync( + source, + options: new AnalyzerTestOptions { Sources = [stubs] }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnOutVariableLocalIsAssignedLater() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + void M(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + int.TryParse(token, out var number); + number = 3; + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTicketConstructorNamesItsPrincipalDifferently() + { + const string ticket = """ + namespace Microsoft.AspNetCore.Authentication + { + public class AuthenticationTicket + { + public AuthenticationTicket(System.Security.Claims.ClaimsPrincipal user) { } + } + } + """; + + return VerifyWithAsync( + """ + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Authentication; + class C + { + AuthenticationTicket M(JwtSecurityTokenHandler handler, string token) + { + return new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(handler.ReadJwtToken(token).Claims, "jwt"))); + } + } + """, + string.Join("\n", TokenBaseStub, JwtStub, JsonStub, HttpStub, ticket)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTokenIsBuiltFromBytes() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + void M(HttpContext context, byte[] raw) + { + context.User = new ClaimsPrincipal(new ClaimsIdentity(new JwtSecurityToken(raw).Claims, "jwt")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTokenComesFromReadersOfOtherTypes() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.JsonWebTokens; + class OwnReader + { + public JsonWebToken ReadJsonWebToken(string token) => new(); + + public JwtSecurityToken ReadToken(string token) => new(); + + public JwtSecurityToken Load(string token) => new(); + } + + class C + { + void M(HttpContext context, OwnReader reader, string token) + { + context.User = new ClaimsPrincipal(new ClaimsIdentity(reader.ReadJsonWebToken(token).Claims, "jwt")); + context.User = new ClaimsPrincipal(new ClaimsIdentity(reader.ReadToken(token).Claims, "jwt")); + context.User = new ClaimsPrincipal(new ClaimsIdentity(reader.Load(token).Claims, "jwt")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALambdaCapturesAnOutVariableClaimsLocal() + { + return VerifyAsync(""" + using System; + using System.Collections.Generic; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + static void Fill(out IEnumerable claims) { claims = []; } + + void M(HttpContext context) + { + Fill(out var claims); + Action apply = () => context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")); + apply(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALambdaReadsACapturedClaimsLocalTwice() + { + return VerifyAsync(""" + using System; + using System.IdentityModel.Tokens.Jwt; + using System.Linq; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + void M(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var claims = handler.ReadJwtToken(token).Claims; + Action apply = () => {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(claims.Concat(claims), "jwt"))|}; + apply(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALoopLambdaReadsTheTokenAfterTheUse() + { + return VerifyAsync(""" + using System; + using System.Collections.Generic; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + void M(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + IEnumerable claims = []; + while (token.Length > 0) + { + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"))|}; + Action load = () => claims = handler.ReadJwtToken(token).Claims; + load(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALambdaRewritesTheValidatedTokenBeforeTheUse() + { + return VerifyAsync(""" + using System; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + Action M(HttpContext context, JwtSecurityTokenHandler handler, string token, string other, TokenValidationParameters parameters) + { + handler.ValidateToken(token, parameters, out _); + return () => + { + token = other; + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(handler.ReadJwtToken(token).Claims, "jwt"))|}; + }; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALocalFunctionRunsInsideTheValidationGuard() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + async Task M(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (result.IsValid) + { + void Apply() + { + context.User = new ClaimsPrincipal(new ClaimsIdentity(handler.ReadJwtToken(token).Claims, "jwt")); + } + + Apply(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheSinkIsAnEmbeddedStatement() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + void Unvalidated(HttpContext context, JwtSecurityTokenHandler handler, string token, bool flag) + { + var parsed = handler.ReadJwtToken(token); + if (flag) + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + void Validated(HttpContext context, JwtSecurityTokenHandler handler, string token, bool flag, TokenValidationParameters parameters) + { + handler.ValidateToken(token, parameters, out _); + var parsed = handler.ReadJwtToken(token); + if (flag) + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALabelPrecedesTheGotoInTheBlock() + { + return VerifyAsync(""" + using System; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + void M(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + handler.ValidateToken(token, parameters, out _); + retry: Console.WriteLine(token); + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + if (token.Length > 100) goto retry; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTokenIsRewrittenInsideTheValidatingTry() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + void M(HttpContext context, JwtSecurityTokenHandler handler, string token, string other, TokenValidationParameters parameters) + { + try + { + handler.ValidateToken(token, parameters, out _); + token = other; + } + catch + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenDeclarationsWithoutASingleInitializerPrecedeTheValidatedUse() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + void M(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + string unused; + int first = 1, second = 2; + handler.ValidateToken(token, parameters, out _); + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheValidationResultComesFromAnOutVariable() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class Validator + { + public bool TryValidate(string token, out TokenValidationResult result) + { + result = new(); + return true; + } + } + + class C + { + void Failed(HttpContext context, JwtSecurityTokenHandler handler, Validator validator, string token) + { + validator.TryValidate(token, out var result); + if (!result.IsValid) + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + void Passed(HttpContext context, JwtSecurityTokenHandler handler, Validator validator, string token) + { + validator.TryValidate(token, out var result); + var parsed = handler.ReadJwtToken(token); + if (result.IsValid) + { + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheBaseIdentityComesFromAnOutArgument() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + static void Make(out ClaimsIdentity identity) { identity = new ClaimsIdentity("jwt"); } + + void M(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + Make(out var baseIdentity); + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(baseIdentity, parsed.Claims)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardDoesNotCoverTheUse() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + async Task Rewritten(HttpContext context, JwtSecurityTokenHandler handler, string token, string other, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (result.IsValid) + { + token = other; + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + + async Task RewrittenInLoop(HttpContext context, JwtSecurityTokenHandler handler, string token, string other, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (result.IsValid) + { + for (var i = 0; i < 2; i++) + { + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + token = other; + } + } + } + + async Task OutsideTheGuard(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (result.IsValid) + { + token.ToString(); + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/Utf8GetBytesLiteralAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/Utf8GetBytesLiteralAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..5e28da4 --- /dev/null +++ b/tests/E128.Analyzers.Tests/Utf8GetBytesLiteralAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,27 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class Utf8GetBytesLiteralAnalyzerBranchCoverageMoreTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLiteralFeedsAConstructorInitializer() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Text; + class Base + { + public Base(byte[] data) { } + } + + class Derived : Base + { + public Derived() : base({|E128141:Encoding.UTF8.GetBytes("abc")|}) { } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/Utf8StringParseAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/Utf8StringParseAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..162aaf5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/Utf8StringParseAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,38 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class Utf8StringParseAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheOnlyUtf8OverloadIsGeneric() + { + return VerifyAsync(""" + using System; + using System.Text; + + readonly struct Number + { + public static Number Parse(string text) => default; + + public static Number Parse(ReadOnlySpan utf8) => default; + } + + class C + { + Number M(byte[] bytes) + { + return Number.Parse(Encoding.UTF8.GetString(bytes)); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/WhenAnyResultUnobservedAnalyzerBranchCoverageMoreTests.cs b/tests/E128.Analyzers.Tests/WhenAnyResultUnobservedAnalyzerBranchCoverageMoreTests.cs new file mode 100644 index 0000000..adfef8c --- /dev/null +++ b/tests/E128.Analyzers.Tests/WhenAnyResultUnobservedAnalyzerBranchCoverageMoreTests.cs @@ -0,0 +1,70 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class WhenAnyResultUnobservedAnalyzerBranchCoverageMoreTests +{ + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Threading.Tasks;\n" + + "class Box { public int t; }\n" + + "class C\n{\n void M(Task a, Task b, Box box, Func factory, Func> WhenAny)\n {\n" + body + "\n }\n}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnInvokedDelegateResultAndADelegateNamedWhenAny() + { + return VerifyAsync(""" + factory()(); + _ = WhenAny(a, b); + WhenAny(a, b); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWhenAnyCallBindsDynamically() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading.Tasks; + class C + { + void M(Task a) + { + dynamic tasks = new object(); + tasks.WhenAny(a); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenOnlyAMemberWithTheLocalsNameIsRead() + { + return VerifyAsync(""" + var t = {|E128183:Task.WhenAny(a, b)|}; + _ = box.t; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalIsDeclaredOutsideAnyBlock() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Threading.Tasks; + + Task a = Task.CompletedTask; + Task b = Task.CompletedTask; + var first = Task.WhenAny(a, b); + """, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +}