From 2081bf44cab500594b3130472dff2e5c76947c14 Mon Sep 17 00:00:00 2001 From: Tim Pohlmann Date: Tue, 14 May 2024 17:47:55 +0200 Subject: [PATCH] Change `.Verify` to fail when no issues are reported (#9250) --- ...tractTypesShouldNotHaveConstructorsTest.cs | 2 +- ...ouldNotDeriveDirectlyFromControllerTest.cs | 62 +- .../Rules/AspNet/CallModelStateIsValidTest.cs | 6 +- ...outeTemplateShouldNotStartWithSlashTest.cs | 21 +- .../Rules/AssertionsShouldBeCompleteTest.cs | 20 +- .../Rules/AvoidExcessiveClassCouplingTest.cs | 799 +++++++++--------- .../Rules/BypassingAccessibilityTest.cs | 2 +- .../CalculationsShouldNotOverflowTest.cs | 4 +- ...erInformationParametersShouldBeLastTest.cs | 41 +- .../Rules/CastShouldNotBeDuplicatedTest.cs | 2 +- .../Rules/CheckFileLicenseTest.cs | 32 +- .../Rules/ClassNamedExceptionTest.cs | 8 +- .../Rules/ClassWithOnlyStaticMemberTest.cs | 47 +- .../AzureFunctionsLogFailuresTest.cs | 43 +- .../Rules/CognitiveComplexityTest.cs | 4 +- ...eShouldNotBeUsedasTypeForPrimaryKeyTest.cs | 14 +- .../Rules/DisposableNotDisposedTest.cs | 67 +- .../DisposableTypesNeedFinalizersTest.cs | 11 +- .../Rules/DoNotCopyArraysInPropertiesTest.cs | 37 +- .../DoNotDecreaseMemberVisibilityTest.cs | 2 +- .../Rules/DoNotExposeListTTest.cs | 21 +- .../Rules/DoNotHideBaseClassMethodsTest.cs | 43 +- .../Rules/DoNotOverloadOperatorEqualTest.cs | 37 +- .../Rules/DoNotShiftByZeroOrIntSizeTest.cs | 89 +- .../Rules/EmptyMethodTest.cs | 185 ++-- .../Rules/EmptyNestedBlockTest.cs | 37 +- .../ExceptionsNeedStandardConstructorsTest.cs | 20 +- .../ExceptionsShouldBeLoggedOrThrownTest.cs | 2 +- .../Rules/FinalizerShouldNotBeEmptyTest.cs | 13 +- .../Rules/ForLoopCounterChangedTest.cs | 37 +- .../Rules/FunctionComplexityTest.cs | 2 +- .../Rules/GenericTypeParameterUnusedTest.cs | 41 +- .../Rules/GetHashCodeEqualsOverrideTest.cs | 2 +- .../Rules/GetTypeWithIsAssignableFromTest.cs | 91 +- .../Rules/Hotspots/CommandPathTest.cs | 2 +- .../Hotspots/CreatingHashAlgorithmsTest.cs | 67 +- ...DeliveringDebugFeaturesInProductionTest.cs | 107 ++- .../ImplementIDisposableCorrectlyTest.cs | 35 +- ...lementSerializationMethodsCorrectlyTest.cs | 89 +- .../Rules/InfiniteRecursionTest.cs | 119 ++- .../Rules/InsteadOfAnyTest.cs | 2 +- .../JSInvokableMethodsShouldBePublicTest.cs | 2 +- .../Rules/LiteralSuffixUpperCaseTest.cs | 2 +- .../LoggerMembersNamesShouldComplyTest.cs | 2 +- ...oggersShouldBeNamedForEnclosingTypeTest.cs | 2 +- ...TemplatePlaceHoldersShouldBeInOrderTest.cs | 38 +- ...ssemblyWithAssemblyVersionAttributeTest.cs | 133 ++- ...rkAssemblyWithClsCompliantAttributeTest.cs | 37 +- ...MarkAssemblyWithComVisibleAttributeTest.cs | 37 +- ...thNeutralResourcesLanguageAttributeTest.cs | 4 +- .../MarkWindowsFormsMainWithStaThreadTest.cs | 3 +- .../Rules/MemberInitializedToDefaultTest.cs | 71 +- .../MemberOverrideCallsBaseMemberTest.cs | 7 +- .../Rules/MemberShouldBeStaticTest.cs | 103 +-- .../Rules/MethodOverrideNoParamsTest.cs | 2 +- ...ouldBeNamedAccordingToSynchronicityTest.cs | 105 ++- .../MethodShouldNotOnlyReturnConstantTest.cs | 29 +- .../MethodsShouldNotHaveTooManyLinesTest.cs | 39 +- .../Rules/MethodsShouldUseBaseTypesTest.cs | 35 +- .../Rules/NativeMethodsShouldBeWrappedTest.cs | 95 +-- ...atorsShouldBeOverloadedConsistentlyTest.cs | 29 +- .../Rules/OptionExplicitOnTest.cs | 68 +- .../Rules/OptionalParameterTest.cs | 37 +- ...errideGetHashCodeOnOverridingEqualsTest.cs | 23 +- .../Rules/ParametersCorrectOrderTest.cs | 81 +- .../Rules/PropertiesAccessCorrectFieldTest.cs | 65 +- ...opertyNamesShouldNotMatchGetMethodsTest.cs | 52 +- .../Rules/RedundantCastTest.cs | 80 +- ...edundantConditionalAroundAssignmentTest.cs | 2 +- .../Rules/RedundantDeclarationTest.cs | 237 +++--- .../Rules/RedundantNullCheckTest.cs | 2 +- ...lizationConstructorsShouldBeSecuredTest.cs | 60 +- .../Rules/SqlKeywordsDelimitedBySpaceTest.cs | 173 ++-- .../Rules/StreamReadStatementTest.cs | 29 +- .../StringOperationWithoutCultureTest.cs | 37 +- .../Rules/SwaggerActionReturnTypeTest.cs | 4 +- .../ConditionEvaluatesToConstantTest.cs | 8 +- ...ptyCollectionsShouldNotBeEnumeratedTest.cs | 8 +- .../HashesShouldHaveUnpredictableSaltTest.cs | 6 +- .../InitializationVectorShouldBeRandomTest.cs | 6 +- .../NullPointerDereferenceTest.cs | 177 ++-- .../SymbolicExecutionRunnerTest.cs | 136 +-- .../Rules/TaskConfigureAwaitTest.cs | 41 +- .../TestMethodShouldContainAssertionTest.cs | 297 +++---- .../Rules/TestMethodShouldNotBeIgnoredTest.cs | 144 ++-- .../Rules/ToStringShouldNotReturnNullTest.cs | 2 +- .../Rules/TypeMemberVisibilityTest.cs | 35 +- ...nchangedLocalVariablesShouldBeConstTest.cs | 23 +- .../Rules/UnnecessaryUsingsTest.cs | 257 +++--- .../UnusedPrivateMemberTest.Constructors.cs | 95 ++- .../Rules/UnusedPrivateMemberTest.Fields.cs | 2 +- .../Rules/UnusedPrivateMemberTest.Methods.cs | 95 +-- .../UnusedPrivateMemberTest.Properties.cs | 135 ++- .../Rules/UnusedPrivateMemberTest.Types.cs | 39 +- .../Rules/UnusedPrivateMemberTest.cs | 140 +-- .../Rules/UseAwaitableMethodTest.cs | 2 +- .../UseCharOverloadOfStringMethodsTest.cs | 2 +- .../Rules/UseFindSystemTimeZoneByIdTest.cs | 4 +- .../Rules/UseGenericWithRefParametersTest.cs | 33 +- .../ValueTypeShouldImplementIEquatableTest.cs | 2 +- .../Rules/VariableUnusedTest.cs | 2 +- .../Roslyn/CollectionConstraintTests.cs | 6 +- .../AspNet/AvoidUnderPosting.CSharp12.cs | 9 +- .../AspNet/ControllerReuseClient.CSharp12.cs | 7 +- ...uggerDisplayUsesExistingMembers.CSharp8.cs | 7 +- .../FindInsteadOfFirstOrDefault.Net.cs | 12 +- .../FindInsteadOfFirstOrDefault.Net.vb | 12 +- .../GenericTypeParameterUnused.CSharp11.cs | 11 +- .../DisablingCSRFProtection.CSharp11.cs | 3 +- ...rdcodeCredentials.DefaultValues.CSharp8.cs | 3 +- .../Hotspots/ExecutingSqlQueries.CSharp10.cs | 5 +- .../MemberInitializedToDefault.CSharp8.cs | 3 +- ...MethodOverloadsShouldBeGrouped.CSharp12.cs | 4 +- .../NativeMethodsShouldBeWrapped.CSharp10.cs | 7 - .../NativeMethodsShouldBeWrapped.CSharp9.cs | 6 + .../ConditionEvaluatesToConstant.CSharp12.cs | 27 +- ...mptyNullableValueAccess.NullableContext.cs | 13 +- ...ethodArgumentsShouldBeCheckedForNull.razor | 2 + .../Sonar/SymbolicExecutionRules.cs | 8 +- .../ThreadStaticNonStaticField.CSharp11.cs | 5 +- .../ThreadStaticWithInitializer.CSharp11.cs | 5 +- .../TestCases/UseCurlyBraces.CSharp7.cs | 2 + .../Verification/VerifierTest.cs | 90 +- .../Verification/DiagnosticVerifier.cs | 25 +- .../Verification/Verifier.cs | 16 +- .../Verification/VerifierBuilder.cs | 9 + 126 files changed, 3050 insertions(+), 2928 deletions(-) delete mode 100644 analyzers/tests/SonarAnalyzer.Test/TestCases/NativeMethodsShouldBeWrapped.CSharp10.cs diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/AbstractTypesShouldNotHaveConstructorsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/AbstractTypesShouldNotHaveConstructorsTest.cs index d0f1d6809d1..c6374a3206e 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/AbstractTypesShouldNotHaveConstructorsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/AbstractTypesShouldNotHaveConstructorsTest.cs @@ -49,7 +49,7 @@ public class AbstractTypesShouldNotHaveConstructorsTest public void AbstractTypesShouldNotHaveConstructors_CSharp12() => builder.AddPaths("AbstractTypesShouldNotHaveConstructors.CSharp12.cs") .WithOptions(ParseOptionsHelper.FromCSharp12) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/ApiControllersShouldNotDeriveDirectlyFromControllerTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/ApiControllersShouldNotDeriveDirectlyFromControllerTest.cs index e98d5a71cfa..a35b8c4d210 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/ApiControllersShouldNotDeriveDirectlyFromControllerTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/ApiControllersShouldNotDeriveDirectlyFromControllerTest.cs @@ -64,36 +64,32 @@ public class ApiControllersShouldNotDeriveDirectlyFromControllerTest [DataRow("""TempData["foo"]""")] [DataTestMethod] public void ApiControllersShouldNotDeriveDirectlyFromController_DoesNotRaiseWithViewFunctionality(string invocation) => - builder - .AddSnippet($$""" - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Filters; + builder.AddSnippet($$""" + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Mvc.Filters; - [ApiController] - public class Invocations : Controller // Compliant - { - object model = null; - public object Foo() => {{invocation}}; - } - """) - .Verify(); + [ApiController] + public class Invocations : Controller // Compliant + { + object model = null; + public object Foo() => {{invocation}}; + } + """).VerifyNoIssues(); [DataRow("""OnActionExecuted(default(ActionExecutedContext))""")] [DataRow("""OnActionExecuting(default(ActionExecutingContext))""")] [DataTestMethod] public void ApiControllersShouldNotDeriveDirectlyFromController_DoesNotRaiseWithVoidInvocations(string assignment) => - builder - .AddSnippet($$""" - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Filters; + builder.AddSnippet($$""" + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Mvc.Filters; - [ApiController] - public class VoidInvocations : Controller // Compliant - { - public void Foo() => {{assignment}}; - } - """) - .Verify(); + [ApiController] + public class VoidInvocations : Controller // Compliant + { + public void Foo() => {{assignment}}; + } + """).VerifyNoIssues(); [DataRow("public Test() => foo = View();", DisplayName = "Constructor")] [DataRow("~Test() => foo = View();", DisplayName = "Destructor")] @@ -102,18 +98,16 @@ public class VoidInvocations : Controller // Compliant [DataRow("object this[int index] => View();", DisplayName = "Indexer")] [DataTestMethod] public void ApiControllersShouldNotDeriveDirectlyFromController_DoesNotRaiseInDifferentConstructs(string code) => - builder - .AddSnippet($$""" - using Microsoft.AspNetCore.Mvc; + builder.AddSnippet($$""" + using Microsoft.AspNetCore.Mvc; - [ApiController] - public class Test : Controller // Compliant - { - object foo; - {{code}} - } - """) - .Verify(); + [ApiController] + public class Test : Controller // Compliant + { + object foo; + {{code}} + } + """).VerifyNoIssues(); [TestMethod] public void ApiControllersShouldNotDeriveDirectlyFromController_CodeFix() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/CallModelStateIsValidTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/CallModelStateIsValidTest.cs index 55805de6ef1..8ec69137821 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/CallModelStateIsValidTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/CallModelStateIsValidTest.cs @@ -62,7 +62,7 @@ public class ControllerWithApiAttributeAtTheAssemblyLevel : ControllerBase return "Hello!"; } } - """).Verify(); + """).VerifyNoIssues(); [TestMethod] public void CallModelStateIsValid_FluentValidation_CS() => @@ -134,7 +134,7 @@ public class NonValidatingMovieController : ControllerBase return "Hello!"; } } - """).AddReferences(NuGetMetadataReference.FluentValidation()).Verify(); + """).AddReferences(NuGetMetadataReference.FluentValidation()).VerifyNoIssues(); [DataTestMethod] [DataRow("!ModelState.IsValid")] @@ -173,7 +173,7 @@ public class MovieController : ControllerBase return Ok(); } } - """).WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + """).WithOptions(ParseOptionsHelper.FromCSharp10).VerifyNoIssues(); } #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/RouteTemplateShouldNotStartWithSlashTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/RouteTemplateShouldNotStartWithSlashTest.cs index f3cea1df245..f81a08d0a67 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/RouteTemplateShouldNotStartWithSlashTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/AspNet/RouteTemplateShouldNotStartWithSlashTest.cs @@ -159,7 +159,7 @@ public class BasicsController : Controller {{(compliant ? string.Empty : " // No builderVB .AddPaths("RouteTemplateShouldNotStartWithSlash.AspNetCore.vb") .AddReferences(AspNetCoreReferences) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void RouteTemplateShouldNotStartWithSlash_CSharp12() => @@ -194,7 +194,7 @@ public class BasicsController : Controller {{(compliant ? string.Empty : " // No builderVB .AddPaths("RouteTemplateShouldNotStartWithSlash.AspNet4x.vb") .AddReferences(AspNet4xReferences(aspNetMvcVersion)) - .Verify(); + .VerifyNoIssues(); [DataRow("/Index2", false)] [DataRow(@"\Index2", true)] @@ -231,8 +231,9 @@ public class BasicsController : Controller {{(compliant ? string.Empty : " // No [DataRow("""[System.Web.Mvc.RouteAttribute(@"/[action]")]""", false)] [DataRow("""[method:Route(@"/[action]")]""", false)] [DataTestMethod] - public void RouteTemplateShouldNotStartWithSlash_WithAttributeSyntaxVariations(string attribute, bool compliant) => - builderCS.AddReferences(AspNet4xReferences("5.2.7")) + public void RouteTemplateShouldNotStartWithSlash_WithAttributeSyntaxVariations(string attribute, bool compliant) + { + var builder = builderCS.AddReferences(AspNet4xReferences("5.2.7")) .WithOptions(ParseOptionsHelper.FromCSharp11) .AddSnippet($$""" using System.Web.Mvc; @@ -243,8 +244,16 @@ public class BasicsController : Controller {{(compliant ? string.Empty : " // No {{attribute}} {{(compliant ? string.Empty : " // Secondary")}} public ActionResult SomeAction() => View(); } - """) - .Verify(); + """); + if (compliant) + { + builder.VerifyNoIssues(); + } + else + { + builder.Verify(); + } + } [DataRow("""(@"/[action]")""", false)] [DataRow("""("/[action]")""", false)] diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/AssertionsShouldBeCompleteTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/AssertionsShouldBeCompleteTest.cs index 814963c0dd8..82e742196d9 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/AssertionsShouldBeCompleteTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/AssertionsShouldBeCompleteTest.cs @@ -60,18 +60,18 @@ public AssertionsShouldBeCompleteTest() [TestMethod] public void AssertionsShouldBeComplete_FluentAssertions_MissingParen() => fluentAssertions - .AddSnippet(""" - using FluentAssertions; - public class Test - { - public void MissingParen() + .AddSnippet(""" + using FluentAssertions; + public class Test { - var s = "Test"; - s.Should(; // Error [CS1026] + public void MissingParen() + { + var s = "Test"; + s.Should(; // Error [CS1026] + } } - } - """) - .Verify(); + """) + .Verify(); [TestMethod] public void AssertionsShouldBeComplete_FluentAssertions_CSharp8() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/AvoidExcessiveClassCouplingTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/AvoidExcessiveClassCouplingTest.cs index a05536c5546..da32d6b561f 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/AvoidExcessiveClassCouplingTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/AvoidExcessiveClassCouplingTest.cs @@ -20,412 +20,411 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules -{ - [TestClass] - public class AvoidExcessiveClassCouplingTest - { - private readonly VerifierBuilder withThreshold0 = new VerifierBuilder().AddAnalyzer(() => new AvoidExcessiveClassCoupling { Threshold = 0 }); - private readonly VerifierBuilder withThreshold1 = new VerifierBuilder().AddAnalyzer(() => new AvoidExcessiveClassCoupling { Threshold = 1 }); - - [TestMethod] - public void AvoidExcessiveClassCoupling() => - withThreshold1.AddPaths("AvoidExcessiveClassCoupling.cs").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Generic_No_Constraints() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Generics1 // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} -{ - public void Foo(IDictionary dictionary) { } // +1 for dictionary -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Generic_With_Constraints() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Generics1 // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 4 to the maximum authorized 0 or less.}} -{ - public void Foo1(IDictionary dictionary) // +1 for IDictionary - where T : IEnumerable // +1 for IEnumerable, +1 for IDisposable - where V : ICloneable // +1 for ICloneable - { - } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Generic_Bounded() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Generics1 // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 3 to the maximum authorized 0 or less.}} -{ - public void Foo(IDictionary dictionary) // +1 for IDictionary, +1 for IDisposable, +1 for ICloneable - { - } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Generic_Bounded_Deep_Nesting() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Generics1 // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 6 to the maximum authorized 0 or less.}} -{ - public void Foo(IList>>>>> dictionary) - // +1 for IList, +1 for ICollection, +1 for IEnumerable, +1 for IComparer, +1 for Stack, +1 for Queue - { - } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Task_Not_Counted() => - withThreshold0.AddSnippet(@" -using System.Threading.Tasks; -public class Tasks // Compliant, Task types are not counted -{ - public void Foo(Task task1, Task task2) { } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Action_Not_Counted() => - withThreshold0.AddSnippet(@" -using System; -public class Actions // Compliant, Action types are not counted -{ - public void Foo(Action action1, Action action2, Action action3, Action action4, Action action5) { } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Func_Not_Counted() => - withThreshold0.AddSnippet(@" -using System; -public class Functions // Compliant, Func types are not counted -{ - public void Foo(Func func1, Func func2, Func func3, Func func4) { } -} -").Verify(); +namespace SonarAnalyzer.Test.Rules; - [TestMethod] - public void AvoidExcessiveClassCoupling_Pointers_Not_Counted() => - withThreshold0.AddSnippet(@" -using System; -public class Pointers // Compliant, pointers are not counted +[TestClass] +public class AvoidExcessiveClassCouplingTest { - public void Foo(int* pointer) { } // Error [CS0214] -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Enums_Not_Counted() => - withThreshold0.AddSnippet(@" -using System; -public class Pointers // Compliant, enums are not counted -{ - public ConsoleColor Foo(ConsoleColor c) { return ConsoleColor.Black; } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Lazy_Not_Counted() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Lazyness // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} -{ - public void Foo(Lazy> lazy) { } // +1 IEnumerable -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Fields_Are_Counted() => - withThreshold0.AddSnippet(@" -using System.Collections.Generic; -public class Fields // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 5 to the maximum authorized 0 or less.}} -{ - // accessibility - private IList c1; - public ICollection c2; - internal IEnumerable c3; - protected IEnumerator c4; - // static - public static IEqualityComparer c5; -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Properties_Are_Counted() => - withThreshold0.AddSnippet(@" -using System.Collections.Generic; -public class Properties // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 9 to the maximum authorized 0 or less.}} -{ - // accessibility - private IList C1 { get; set; } - public ICollection C2 { get; set; } - internal IEnumerable C3 { get; set; } - protected IEnumerator C4 { get; set; } - // static - public static IEqualityComparer C5 { get; set; } - // accessor bodies - public Stack C6 - { - get - { - Queue q; - return null; - } - set - { - List l; - } - } - // expression body - public object C7 => new Dictionary(); -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Indexers_Are_Counted() => - withThreshold0.AddSnippet(@" -using System.Collections.Generic; -public class Indexers // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 6 to the maximum authorized 0 or less.}} -{ - // accessibility - public IList this[int i] { get { return null; } } // +1 IList - private ICollection this[int i, int j] { get { return null; } } // +1 ICollection - protected IEnumerable this[int i, int j, int k] { get { return null; } } // +1 IEnumerable - internal IEnumerator this[int i, int j, int k, int l] { get { return null; } } // +1 IEnumerator - // parameters - public int this[IEqualityComparer i, Stack j] { get { return 0; } } // +1 IEqualityComparer, +1 Stack -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Events_Are_Counted() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Events // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 9 to the maximum authorized 0 or less.}} -{ - // accessibility - private event EventHandler> e1; // +1 EventHandler, +1 IList - public event EventHandler> e2; // +1 ICollection - internal event EventHandler> e3; // +1 IEnumerable - protected event EventHandler> e4; // +1 IEnumerator - // static - public static event EventHandler> e5; // +1 IEqualityComparer - // accessor bodies - public event EventHandler> E6 // +1 Stack - { - add - { - Queue q; // +1 Queue - } - remove - { - List l; // +1 List - } - } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Methods_Are_Counted() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -using System.Diagnostics; -public class Methods // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 10 to the maximum authorized 0 or less.}} -{ - // accessibility - private void M1(IList l1) { } // +1 IList - public void M2(ICollection l1) { } // +1 ICollection - internal void M3(IEnumerable l1) { } // +1 IEnumerable - protected void M4(IEnumerator l1) { } // +1 IEnumerator - // return type - private IEqualityComparer M5() { return null; } // +1 IEqualityComparer - // generic constraints - private void M6() where T : Stack { return; } // +1 Stack - // method body - private void M8() - { - Queue q; // +1 Queue - Console.Clear(); // +1 Console -} - // expression body - private object M9() => new List(); // +1 List - private void M10() => Debug.Write(1); // +1 Debug -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Inner_Classes_And_Structs_Are_Not_Counted() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class OuterClass // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} -{ - private void M1(IList l1) { } // +1 IList - - public class InnerClass // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} - { - private void M1(ICollection l1) { } // +1 ICollection - } -} -public struct OuterStruct // Noncompliant {{Split this struct into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} -{ - private void M1(IList l1) { } // +1 IList - - public struct InnerStruct // Noncompliant {{Split this struct into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} - { - private void M1(ICollection l1) { } // +1 ICollection - } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Interface_Declaration() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public interface I // Noncompliant {{Split this interface into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} -{ - void M1(IList l1); // +1 IList - // interfaces cannot contain other types -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Self_Reference() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Self // Compliant, self references are not counted -{ - void M1(Self other) { } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Base_Classes_Interfaces_NotCounted() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Base {} -public class Self // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 2 to the maximum authorized 0 or less.}} - : Base, ICloneable -{ - public object Clone() { return null; } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Catch_Statements() => - withThreshold0.AddSnippet(@" -using System; -using System.Collections.Generic; -public class Self // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 2 to the maximum authorized 0 or less.}} -{ - void M1() - { - try { } catch (Exception) { } // +1 Exception - try { } catch (Exception e) when (e is InvalidOperationException) { } // +1 InvalidOperationException - } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Attributes() => - withThreshold0.AddSnippet(@" -using System; -[Serializable] -public class Self // Compliant, attributes are not counted -{ - [Obsolete] - void M1() - { - } -} -").Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Nameof() => - withThreshold0.AddSnippet(@" -public class A // Compliant, types referenced by the nameof expression are not counted -{ - public A() - { - var s1 = nameof(System.Type); - var s2 = nameof(System.Action); - } -} -").Verify(); + private readonly VerifierBuilder withThreshold0 = new VerifierBuilder().AddAnalyzer(() => new AvoidExcessiveClassCoupling { Threshold = 0 }); + private readonly VerifierBuilder withThreshold1 = new VerifierBuilder().AddAnalyzer(() => new AvoidExcessiveClassCoupling { Threshold = 1 }); + + [TestMethod] + public void AvoidExcessiveClassCoupling() => + withThreshold1.AddPaths("AvoidExcessiveClassCoupling.cs").Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Generic_No_Constraints() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Generics1 // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} + { + public void Foo(IDictionary dictionary) { } // +1 for dictionary + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Generic_With_Constraints() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Generics1 // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 4 to the maximum authorized 0 or less.}} + { + public void Foo1(IDictionary dictionary) // +1 for IDictionary + where T : IEnumerable // +1 for IEnumerable, +1 for IDisposable + where V : ICloneable // +1 for ICloneable + { + } + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Generic_Bounded() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Generics1 // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 3 to the maximum authorized 0 or less.}} + { + public void Foo(IDictionary dictionary) // +1 for IDictionary, +1 for IDisposable, +1 for ICloneable + { + } + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Generic_Bounded_Deep_Nesting() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Generics1 // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 6 to the maximum authorized 0 or less.}} + { + public void Foo(IList>>>>> dictionary) + // +1 for IList, +1 for ICollection, +1 for IEnumerable, +1 for IComparer, +1 for Stack, +1 for Queue + { + } + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Task_Not_Counted() => + withThreshold0.AddSnippet(""" + using System.Threading.Tasks; + public class Tasks // Compliant, Task types are not counted + { + public void Foo(Task task1, Task task2) { } + } + """).VerifyNoIssues(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Action_Not_Counted() => + withThreshold0.AddSnippet(""" + using System; + public class Actions // Compliant, Action types are not counted + { + public void Foo(Action action1, Action action2, Action action3, Action action4, Action action5) { } + } + """).VerifyNoIssues(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Func_Not_Counted() => + withThreshold0.AddSnippet(""" + using System; + public class Functions // Compliant, Func types are not counted + { + public void Foo(Func func1, Func func2, Func func3, Func func4) { } + } + """).VerifyNoIssues(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Pointers_Not_Counted() => + withThreshold0.AddSnippet(""" + using System; + public class Pointers // Compliant, pointers are not counted + { + public void Foo(int* pointer) { } // Error [CS0214] + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Enums_Not_Counted() => + withThreshold0.AddSnippet(""" + using System; + public class Pointers // Compliant, enums are not counted + { + public ConsoleColor Foo(ConsoleColor c) { return ConsoleColor.Black; } + } + """).VerifyNoIssues(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Lazy_Not_Counted() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Lazyness // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} + { + public void Foo(Lazy> lazy) { } // +1 IEnumerable + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Fields_Are_Counted() => + withThreshold0.AddSnippet(""" + using System.Collections.Generic; + public class Fields // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 5 to the maximum authorized 0 or less.}} + { + // accessibility + private IList c1; + public ICollection c2; + internal IEnumerable c3; + protected IEnumerator c4; + // static + public static IEqualityComparer c5; + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Properties_Are_Counted() => + withThreshold0.AddSnippet(""" + using System.Collections.Generic; + public class Properties // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 9 to the maximum authorized 0 or less.}} + { + // accessibility + private IList C1 { get; set; } + public ICollection C2 { get; set; } + internal IEnumerable C3 { get; set; } + protected IEnumerator C4 { get; set; } + // static + public static IEqualityComparer C5 { get; set; } + // accessor bodies + public Stack C6 + { + get + { + Queue q; + return null; + } + set + { + List l; + } + } + // expression body + public object C7 => new Dictionary(); + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Indexers_Are_Counted() => + withThreshold0.AddSnippet(""" + using System.Collections.Generic; + public class Indexers // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 6 to the maximum authorized 0 or less.}} + { + // accessibility + public IList this[int i] { get { return null; } } // +1 IList + private ICollection this[int i, int j] { get { return null; } } // +1 ICollection + protected IEnumerable this[int i, int j, int k] { get { return null; } } // +1 IEnumerable + internal IEnumerator this[int i, int j, int k, int l] { get { return null; } } // +1 IEnumerator + // parameters + public int this[IEqualityComparer i, Stack j] { get { return 0; } } // +1 IEqualityComparer, +1 Stack + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Events_Are_Counted() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Events // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 9 to the maximum authorized 0 or less.}} + { + // accessibility + private event EventHandler> e1; // +1 EventHandler, +1 IList + public event EventHandler> e2; // +1 ICollection + internal event EventHandler> e3; // +1 IEnumerable + protected event EventHandler> e4; // +1 IEnumerator + // static + public static event EventHandler> e5; // +1 IEqualityComparer + // accessor bodies + public event EventHandler> E6 // +1 Stack + { + add + { + Queue q; // +1 Queue + } + remove + { + List l; // +1 List + } + } + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Methods_Are_Counted() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + using System.Diagnostics; + public class Methods // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 10 to the maximum authorized 0 or less.}} + { + // accessibility + private void M1(IList l1) { } // +1 IList + public void M2(ICollection l1) { } // +1 ICollection + internal void M3(IEnumerable l1) { } // +1 IEnumerable + protected void M4(IEnumerator l1) { } // +1 IEnumerator + // return type + private IEqualityComparer M5() { return null; } // +1 IEqualityComparer + // generic constraints + private void M6() where T : Stack { return; } // +1 Stack + // method body + private void M8() + { + Queue q; // +1 Queue + Console.Clear(); // +1 Console + } + // expression body + private object M9() => new List(); // +1 List + private void M10() => Debug.Write(1); // +1 Debug + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Inner_Classes_And_Structs_Are_Not_Counted() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class OuterClass // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} + { + private void M1(IList l1) { } // +1 IList + + public class InnerClass // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} + { + private void M1(ICollection l1) { } // +1 ICollection + } + } + public struct OuterStruct // Noncompliant {{Split this struct into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} + { + private void M1(IList l1) { } // +1 IList + + public struct InnerStruct // Noncompliant {{Split this struct into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} + { + private void M1(ICollection l1) { } // +1 ICollection + } + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Interface_Declaration() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public interface I // Noncompliant {{Split this interface into smaller and more specialized ones to reduce its dependencies on other types from 1 to the maximum authorized 0 or less.}} + { + void M1(IList l1); // +1 IList + // interfaces cannot contain other types + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Self_Reference() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Self // Compliant, self references are not counted + { + void M1(Self other) { } + } + """).VerifyNoIssues(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Base_Classes_Interfaces_NotCounted() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Base {} + public class Self // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 2 to the maximum authorized 0 or less.}} + : Base, ICloneable + { + public object Clone() { return null; } + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Catch_Statements() => + withThreshold0.AddSnippet(""" + using System; + using System.Collections.Generic; + public class Self // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other types from 2 to the maximum authorized 0 or less.}} + { + void M1() + { + try { } catch (Exception) { } // +1 Exception + try { } catch (Exception e) when (e is InvalidOperationException) { } // +1 InvalidOperationException + } + } + """).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Attributes() => + withThreshold0.AddSnippet(""" + using System; + [Serializable] + public class Self // Compliant, attributes are not counted + { + [Obsolete] + void M1() + { + } + } + """).VerifyNoIssues(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Nameof() => + withThreshold0.AddSnippet(""" + public class A // Compliant, types referenced by the nameof expression are not counted + { + public A() + { + var s1 = nameof(System.Type); + var s2 = nameof(System.Action); + } + } + """).VerifyNoIssues(); #if NET - [TestMethod] - public void AvoidExcessiveClassCoupling_CSharp9() => - withThreshold1.AddPaths("AvoidExcessiveClassCoupling.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_InRecord_Enums_Not_Counted() => - withThreshold0.AddSnippet(@" -using System; -public record Pointers // Compliant, enums are not counted -{ - public ConsoleColor Foo(ConsoleColor c) { return ConsoleColor.Black; } -} -").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Base_Records_Interfaces_NotCounted() => - withThreshold0.AddSnippet(@" -using System; -using System.Runtime.Serialization; -public record Base {} -public record Self // Noncompliant - : Base, ISerializable -{ - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - } -} -").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_Primitive_Types_Not_Counted() => - withThreshold0.AddSnippet(@" -using System; -public class Types // Compliant, pointers are not counted -{ - public void Foo(bool b1, - byte b2, sbyte b3, int i1, uint i2, long i3, ulong i4, - nint ni1, nuint ni2, - IntPtr p1, UIntPtr p2, - char c1, float d1, - double d2, string s1, - object o1) { } -} -").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_CSharp10() => - withThreshold1.AddPaths("AvoidExcessiveClassCoupling.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); - - [TestMethod] - public void AvoidExcessiveClassCoupling_CSharp11() => - withThreshold1.AddPaths("AvoidExcessiveClassCoupling.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void AvoidExcessiveClassCoupling_CSharp9() => + withThreshold1.AddPaths("AvoidExcessiveClassCoupling.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_InRecord_Enums_Not_Counted() => + withThreshold0.AddSnippet(""" + using System; + public record Pointers // Compliant, enums are not counted + { + public ConsoleColor Foo(ConsoleColor c) { return ConsoleColor.Black; } + } + """).WithOptions(ParseOptionsHelper.FromCSharp9).VerifyNoIssues(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Base_Records_Interfaces_NotCounted() => + withThreshold0.AddSnippet(""" + using System; + using System.Runtime.Serialization; + public record Base {} + public record Self // Noncompliant + : Base, ISerializable + { + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + } + } + """).WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_Primitive_Types_Not_Counted() => + withThreshold0.AddSnippet(""" + using System; + public class Types // Compliant, pointers are not counted + { + public void Foo(bool b1, + byte b2, sbyte b3, int i1, uint i2, long i3, ulong i4, + nint ni1, nuint ni2, + IntPtr p1, UIntPtr p2, + char c1, float d1, + double d2, string s1, + object o1) { } + } + """).WithOptions(ParseOptionsHelper.FromCSharp9).VerifyNoIssues(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_CSharp10() => + withThreshold1.AddPaths("AvoidExcessiveClassCoupling.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + + [TestMethod] + public void AvoidExcessiveClassCoupling_CSharp11() => + withThreshold1.AddPaths("AvoidExcessiveClassCoupling.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/BypassingAccessibilityTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/BypassingAccessibilityTest.cs index 1266a105689..4ed67bc4fbc 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/BypassingAccessibilityTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/BypassingAccessibilityTest.cs @@ -45,7 +45,7 @@ public class BypassingAccessibilityTest [TestMethod] public void BypassingAccessibility_CSharp12() => - builderCS.AddPaths("BypassingAccessibility.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + builderCS.AddPaths("BypassingAccessibility.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/CalculationsShouldNotOverflowTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/CalculationsShouldNotOverflowTest.cs index 34ce916502f..ce640e047e3 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/CalculationsShouldNotOverflowTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/CalculationsShouldNotOverflowTest.cs @@ -47,7 +47,7 @@ public class CalculationsShouldNotOverflowTest [TestMethod] public void CalculationsShouldNotOverflow_CSharp8() => - builderCS.AddPaths("CalculationsShouldNotOverflow.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + builderCS.AddPaths("CalculationsShouldNotOverflow.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).VerifyNoIssues(); #if NET @@ -61,7 +61,7 @@ public class CalculationsShouldNotOverflowTest [TestMethod] public void CalculationsShouldNotOverflow_CSharp11() => - builderCS.AddPaths("CalculationsShouldNotOverflow.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + builderCS.AddPaths("CalculationsShouldNotOverflow.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).VerifyNoIssues(); #endif } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/CallerInformationParametersShouldBeLastTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/CallerInformationParametersShouldBeLastTest.cs index b9d1426a831..ae4e93b79ab 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/CallerInformationParametersShouldBeLastTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/CallerInformationParametersShouldBeLastTest.cs @@ -21,35 +21,34 @@ using Microsoft.CodeAnalysis.CSharp; using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class CallerInformationParametersShouldBeLastTest { - [TestClass] - public class CallerInformationParametersShouldBeLastTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void CallerInformationParametersShouldBeLast() => - builder.AddPaths("CallerInformationParametersShouldBeLast.cs").Verify(); + [TestMethod] + public void CallerInformationParametersShouldBeLast() => + builder.AddPaths("CallerInformationParametersShouldBeLast.cs").Verify(); #if NET - [TestMethod] - public void CallerInformationParametersShouldBeLast_CSharp9() => - builder.AddPaths("CallerInformationParametersShouldBeLast.CSharp9.cs").WithTopLevelStatements().Verify(); + [TestMethod] + public void CallerInformationParametersShouldBeLast_CSharp9() => + builder.AddPaths("CallerInformationParametersShouldBeLast.CSharp9.cs").WithTopLevelStatements().Verify(); - [TestMethod] - public void CallerInformationParametersShouldBeLast_CSharp10() => - builder.AddPaths("CallerInformationParametersShouldBeLast.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void CallerInformationParametersShouldBeLast_CSharp10() => + builder.AddPaths("CallerInformationParametersShouldBeLast.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); - [TestMethod] - public void CallerInformationParametersShouldBeLast_CSharp11() => - builder.AddPaths("CallerInformationParametersShouldBeLast.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void CallerInformationParametersShouldBeLast_CSharp11() => + builder.AddPaths("CallerInformationParametersShouldBeLast.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).VerifyNoIssues(); #endif - [TestMethod] - public void CallerInformationParametersShouldBeLastInvalidSyntax() => - builder.AddPaths("CallerInformationParametersShouldBeLastInvalidSyntax.cs").WithLanguageVersion(LanguageVersion.CSharp7).WithConcurrentAnalysis(false).Verify(); - } + [TestMethod] + public void CallerInformationParametersShouldBeLastInvalidSyntax() => + builder.AddPaths("CallerInformationParametersShouldBeLastInvalidSyntax.cs").WithLanguageVersion(LanguageVersion.CSharp7).WithConcurrentAnalysis(false).Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/CastShouldNotBeDuplicatedTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/CastShouldNotBeDuplicatedTest.cs index 9a0f49243bb..0e9dd100bb7 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/CastShouldNotBeDuplicatedTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/CastShouldNotBeDuplicatedTest.cs @@ -70,7 +70,7 @@ public class Derived: Base """) .AddPaths("CastShouldNotBeDuplicated.cshtml") .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/CheckFileLicenseTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/CheckFileLicenseTest.cs index 9a31ef7ec9c..69d639deabe 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/CheckFileLicenseTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/CheckFileLicenseTest.cs @@ -86,25 +86,25 @@ public class CheckFileLicenseTest public void CheckFileLicense_WhenLicensedFileStartingWithUsing_ShouldBeCompliant_CS() => Builder(SingleLineHeader).AddPaths("CheckFileLicense_SingleLineLicenseStartWithUsing.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedFileStartingWithUsingAndUsingCustomValues_ShouldBeCompliant_CS() => Builder(SingleLineRegexHeader, true).AddPaths("CheckFileLicense_SingleLineLicenseStartWithUsing.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultilineCommentStartingWithUsing_ShouldBeCompliant_CS() => Builder(MultiLineHeader).AddPaths("CheckFileLicense_MultiLineLicenseStartWithUsing.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultilineCommentStartingWithUsingWithCustomValues_ShouldBeCompliant_CS() => Builder(MultiLineRegexHeader, true).AddPaths("CheckFileLicense_MultiLineLicenseStartWithUsing.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenNoLicenseStartingWithNamespace_ShouldBeNonCompliant_CS() => @@ -114,37 +114,37 @@ public class CheckFileLicenseTest public void CheckFileLicense_WhenLicensedWithSingleLineCommentStartingWithNamespace_ShouldBeCompliant_CS() => Builder(SingleLineHeader).AddPaths("CheckFileLicense_SingleLineLicenseStartWithNamespace.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithSingleLineCommentStartingWithNamespaceAndUsingCustomValues_ShouldBeCompliant_CS() => Builder(SingleLineRegexHeader, true).AddPaths("CheckFileLicense_SingleLineLicenseStartWithNamespace.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultilineCommentStartingWithNamespace_ShouldBeCompliant_CS() => Builder(MultiLineHeader).AddPaths("CheckFileLicense_MultiLineLicenseStartWithNamespace.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultilineCommentStartingWithNamespaceAndUsingCustomValues_ShouldBeCompliant_CS() => Builder(MultiLineRegexHeader, true).AddPaths("CheckFileLicense_MultiLineLicenseStartWithNamespace.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultiSingleLineCommentStartingWithNamespaceAndNoRegex_ShouldBeCompliant_CS() => Builder(MultiSingleLineCommentHeader).AddPaths("CheckFileLicense_MultiSingleLineLicenseStartWithNamespace.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultiSingleLineCommentStartingWithAdditionalComments_ShouldBeCompliant_CS() => Builder(MultiSingleLineCommentHeader).AddPaths("CheckFileLicense_MultiSingleLineLicenseStartWithAdditionalComment.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultiSingleLineCommentStartingWithAdditionalCommentOnSameLine_ShouldBeNonCompliant_CS() => @@ -158,19 +158,19 @@ public class CheckFileLicenseTest public void CheckFileLicense_WithForcingEmptyLines_ShouldBeCompliant_CS() => Builder(HeaderForcingLineBreak).AddPaths("CheckFileLicense_ForcingEmptyLinesOk.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultiSingleLineCommentStartingWithNamespaceAndMultiLineRegexWithNewLine_ShouldBeCompliant_CS() => Builder(MultiLineRegexWithNewLine, true).AddPaths("CheckFileLicense_MultiSingleLineLicenseStartWithNamespace.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenLicensedWithMultiSingleLineCommentStartingWithNamespaceAndMultiLineRegexWithDot_ShouldBeCompliant_CS() => Builder(MultiLineRegexWithDot, true).AddPaths("CheckFileLicense_MultiSingleLineLicenseStartWithNamespace.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenEmptyFile_ShouldBeNonCompliant_CS() => @@ -202,14 +202,14 @@ public void CheckFileLicense_WhenProvidingAnInvalidRegex_ShouldThrowException_CS Builder(@"// \r\n// Copyright \(c\) 2012 All Rights Reserved\r\n// \r\n// .*\r\n// .*\r\n// .*\r\n", true) .AddPaths("CheckFileLicense_ComplexRegex.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicense_WhenUsingMultilinesHeaderAsSingleLineString_ShouldBeCompliant_CS() => Builder(@"// \r\n// Copyright (c) 2012 All Rights Reserved\r\n// \r\n// Name of the Author\r\n// 08/22/2017 12:39:58 AM \r\n// Class representing a Sample entity\r\n", false) .AddPaths("CheckFileLicense_ComplexRegex.cs") .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CheckFileLicenseCodeFix_WhenNoLicenseStartWithNamespaceAndUsesDefaultValues_ShouldBeNoncompliant_CS() => @@ -290,7 +290,7 @@ public void CheckFileLicense_WhenProvidingAnInvalidRegex_ShouldThrowException_CS IsRegularExpression = true }) .AddPaths("CheckFileLicense_Compliant.vb") - .Verify(); + .VerifyNoIssues(); private static VerifierBuilder Builder(string headerFormat, bool isRegularExpression = false) => new VerifierBuilder().AddAnalyzer(() => new CS.CheckFileLicense { HeaderFormat = headerFormat, IsRegularExpression = isRegularExpression }); diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ClassNamedExceptionTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ClassNamedExceptionTest.cs index 056b13f49d5..523f6245ce0 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ClassNamedExceptionTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ClassNamedExceptionTest.cs @@ -40,14 +40,14 @@ public class ClassNamedExceptionTest builderCS .AddPaths("ClassNamedException.CSharp9.cs") .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void ClassNamedException_FromCSharp10() => builderCS .AddPaths("ClassNamedException.CSharp10.cs") .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void ClassNamedException_VB() => @@ -61,13 +61,13 @@ public class ClassNamedExceptionTest public void ClassNamedException_Interop_CS() => builderCS .AddPaths("ClassNamedException.Interop.cs") - .Verify(); + .VerifyNoIssues(); [TestMethod] public void ClassNamedException_Interop_VB() => builderVB .AddPaths("ClassNamedException.Interop.vb") - .Verify(); + .VerifyNoIssues(); #endif } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ClassWithOnlyStaticMemberTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ClassWithOnlyStaticMemberTest.cs index 8244f7b2627..db355c6a6f4 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ClassWithOnlyStaticMemberTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ClassWithOnlyStaticMemberTest.cs @@ -20,38 +20,37 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class ClassWithOnlyStaticMemberTest { - [TestClass] - public class ClassWithOnlyStaticMemberTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void ClassWithOnlyStaticMember() => - builder.AddPaths("ClassWithOnlyStaticMember.cs").Verify(); + [TestMethod] + public void ClassWithOnlyStaticMember() => + builder.AddPaths("ClassWithOnlyStaticMember.cs").Verify(); #if NET - [TestMethod] - public void ClassWithOnlyStaticMember_CSharp9() => - builder.AddPaths("ClassWithOnlyStaticMember.CSharp9.cs") - .WithTopLevelStatements() - .Verify(); + [TestMethod] + public void ClassWithOnlyStaticMember_CSharp9() => + builder.AddPaths("ClassWithOnlyStaticMember.CSharp9.cs") + .WithTopLevelStatements() + .VerifyNoIssues(); - [TestMethod] - public void ClassWithOnlyStaticMember_CSharp11() => - builder.AddPaths("ClassWithOnlyStaticMember.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void ClassWithOnlyStaticMember_CSharp11() => + builder.AddPaths("ClassWithOnlyStaticMember.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .VerifyNoIssues(); - [TestMethod] - public void ClassWithOnlyStaticMember_CSharp12() => - builder.AddPaths("ClassWithOnlyStaticMember.CSharp12.cs") - .WithOptions(ParseOptionsHelper.FromCSharp12) - .Verify(); + [TestMethod] + public void ClassWithOnlyStaticMember_CSharp12() => + builder.AddPaths("ClassWithOnlyStaticMember.CSharp12.cs") + .WithOptions(ParseOptionsHelper.FromCSharp12) + .Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/CloudNative/AzureFunctionsLogFailuresTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/CloudNative/AzureFunctionsLogFailuresTest.cs index 1e018e0d4f0..dcc02173993 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/CloudNative/AzureFunctionsLogFailuresTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/CloudNative/AzureFunctionsLogFailuresTest.cs @@ -67,25 +67,32 @@ public class AzureFunctionsLogFailuresTest [DataRow(false, "log.IsEnabled(LogLevel.Warning);")] public void AzureFunctionsLogFailures_VerifyLoggerCalls(bool isCompliant, string loggerInvocation) { - var code = @$" -using Microsoft.Azure.WebJobs; -using Microsoft.Extensions.Logging; -using System; + var snippet = builder.AddSnippet($$""" + using Microsoft.Azure.WebJobs; + using Microsoft.Extensions.Logging; + using System; - public static class Function1 - {{ - [FunctionName(""Function1"")] - public static void Run(ILogger log) - {{ - try {{ }} - catch(Exception ex) // {(isCompliant ? "Compliant" : "Noncompliant")} - {{ - {loggerInvocation} // {(isCompliant ? string.Empty : "Secondary")} - }} - }} - }} -"; - builder.AddSnippet(code).Verify(); + public static class Function1 + { + [FunctionName("Function1")] + public static void Run(ILogger log) + { + try { } + catch(Exception ex) // {{(isCompliant ? "Compliant" : "Noncompliant")}} + { + {{loggerInvocation}} // {{(isCompliant ? string.Empty : "Secondary")}} + } + } + } + """); + if (isCompliant) + { + snippet.VerifyNoIssues(); + } + else + { + snippet.Verify(); + } } } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/CognitiveComplexityTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/CognitiveComplexityTest.cs index 7552a8e079c..4653a4cf8cf 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/CognitiveComplexityTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/CognitiveComplexityTest.cs @@ -74,7 +74,7 @@ public void CognitiveComplexity_StackOverflow_CS() { if (!TestContextHelper.IsAzureDevOpsContext) // ToDo: Test throws OOM on Azure DevOps { - builderCS.AddPaths("SyntaxWalker_InsufficientExecutionStackException.cs").Verify(); + builderCS.AddPaths("SyntaxWalker_InsufficientExecutionStackException.cs").VerifyNoIssues(); } } @@ -83,7 +83,7 @@ public void CognitiveComplexity_StackOverflow_VB() { if (!TestContextHelper.IsAzureDevOpsContext) // ToDO: Test throws OOM on Azure DevOps { - builderVB.AddPaths("SyntaxWalker_InsufficientExecutionStackException.vb").Verify(); + builderVB.AddPaths("SyntaxWalker_InsufficientExecutionStackException.vb").VerifyNoIssues(); } } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DateAndTimeShouldNotBeUsedasTypeForPrimaryKeyTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DateAndTimeShouldNotBeUsedasTypeForPrimaryKeyTest.cs index 163464affb1..deb2dfd32a3 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DateAndTimeShouldNotBeUsedasTypeForPrimaryKeyTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DateAndTimeShouldNotBeUsedasTypeForPrimaryKeyTest.cs @@ -39,18 +39,22 @@ public class DateAndTimeShouldNotBeUsedAsTypeForPrimaryKeyTest [TestMethod] public void DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey_NoReferenceToEntityFramework_CS() => - new VerifierBuilder().AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.NoReferenceToEntityFramework.cs").Verify(); + new VerifierBuilder() + .AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.NoReferenceToEntityFramework.cs") + .VerifyNoIssues(); [TestMethod] public void DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey_NoReferenceToEntityFramework_VB() => - new VerifierBuilder().AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.NoReferenceToEntityFramework.vb").Verify(); + new VerifierBuilder() + .AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.NoReferenceToEntityFramework.vb") + .VerifyNoIssues(); [TestMethod] public void DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey_CSharp9() => verifierCS .AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.CSharp9.cs") .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); + .VerifyNoIssues(); #if NET @@ -64,11 +68,11 @@ public class DateAndTimeShouldNotBeUsedAsTypeForPrimaryKeyTest [TestMethod] public void DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey_FluentApi_CS() => - verifierCS.AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.FluentApi.cs").Verify(); + verifierCS.AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.FluentApi.cs").VerifyNoIssues(); [TestMethod] public void DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey_FluentApi_VB() => - verifierVB.AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.FluentApi.vb").Verify(); + verifierVB.AddPaths("DateAndTimeShouldNotBeUsedAsTypeForPrimaryKey.FluentApi.vb").VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DisposableNotDisposedTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DisposableNotDisposedTest.cs index 49b3c035a99..bf8fa2e2f18 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DisposableNotDisposedTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DisposableNotDisposedTest.cs @@ -20,49 +20,48 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class DisposableNotDisposedTest { - [TestClass] - public class DisposableNotDisposedTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void DisposableNotDisposed() => - builder.AddPaths("DisposableNotDisposed.cs") - .WithOptions(ParseOptionsHelper.FromCSharp7) - .AddReferences(MetadataReferenceFacade.SystemNetHttp) - .Verify(); + [TestMethod] + public void DisposableNotDisposed() => + builder.AddPaths("DisposableNotDisposed.cs") + .WithOptions(ParseOptionsHelper.FromCSharp7) + .AddReferences(MetadataReferenceFacade.SystemNetHttp) + .Verify(); - [TestMethod] - public void DisposableNotDisposed_ILogger() => - builder.AddPaths("DisposableNotDisposed.ILogger.cs") - .AddReferences(NuGetMetadataReference.MicrosoftExtensionsLoggingPackages(Constants.NuGetLatestVersion).ToArray()) - .Verify(); + [TestMethod] + public void DisposableNotDisposed_ILogger() => + builder.AddPaths("DisposableNotDisposed.ILogger.cs") + .AddReferences(NuGetMetadataReference.MicrosoftExtensionsLoggingPackages(Constants.NuGetLatestVersion).ToArray()) + .VerifyNoIssues(); #if NET - [TestMethod] - public void DisposableNotDisposed_CSharp8() => - builder.AddPaths("DisposableNotDisposed.CSharp8.cs") - .WithOptions(ParseOptionsHelper.FromCSharp8) - .AddReferences(NuGetMetadataReference.FluentAssertions("5.9.0")) - .Verify(); + [TestMethod] + public void DisposableNotDisposed_CSharp8() => + builder.AddPaths("DisposableNotDisposed.CSharp8.cs") + .WithOptions(ParseOptionsHelper.FromCSharp8) + .AddReferences(NuGetMetadataReference.FluentAssertions("5.9.0")) + .Verify(); - [TestMethod] - public void DisposableNotDisposed_CSharp9() => - builder.AddPaths("DisposableNotDisposed.CSharp9.cs") - .WithTopLevelStatements() - .AddReferences(MetadataReferenceFacade.SystemNetHttp) - .Verify(); + [TestMethod] + public void DisposableNotDisposed_CSharp9() => + builder.AddPaths("DisposableNotDisposed.CSharp9.cs") + .WithTopLevelStatements() + .AddReferences(MetadataReferenceFacade.SystemNetHttp) + .Verify(); - [TestMethod] - public void DisposableNotDisposed_CSharp10() => - builder.AddPaths("DisposableNotDisposed.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + [TestMethod] + public void DisposableNotDisposed_CSharp10() => + builder.AddPaths("DisposableNotDisposed.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DisposableTypesNeedFinalizersTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DisposableTypesNeedFinalizersTest.cs index 2e8eb50bf7f..6c39013ba0d 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DisposableTypesNeedFinalizersTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DisposableTypesNeedFinalizersTest.cs @@ -45,10 +45,11 @@ public class DisposableTypesNeedFinalizersTest [TestMethod] public void DisposableTypesNeedFinalizers_InvalidCode() => - builder.AddSnippet(@" -public class Foo_05 : IDisposable -{ - private HandleRef; -}").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); + builder.AddSnippet(""" + public class Foo_05 : IDisposable + { + private HandleRef; + } + """).VerifyNoIssuesIgnoreErrors(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotCopyArraysInPropertiesTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotCopyArraysInPropertiesTest.cs index d192b8be56a..a9894770e8c 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotCopyArraysInPropertiesTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotCopyArraysInPropertiesTest.cs @@ -20,32 +20,31 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class DoNotCopyArraysInPropertiesTest { - [TestClass] - public class DoNotCopyArraysInPropertiesTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void DoNotCopyArraysInProperties() => - builder.AddPaths("DoNotCopyArraysInProperties.cs").Verify(); + [TestMethod] + public void DoNotCopyArraysInProperties() => + builder.AddPaths("DoNotCopyArraysInProperties.cs").Verify(); #if NET - [TestMethod] - public void DoNotCopyArraysInProperties_CSharp9() => - builder.AddPaths("DoNotCopyArraysInProperties.CSharp9.cs") - .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); + [TestMethod] + public void DoNotCopyArraysInProperties_CSharp9() => + builder.AddPaths("DoNotCopyArraysInProperties.CSharp9.cs") + .WithOptions(ParseOptionsHelper.FromCSharp9) + .Verify(); - [TestMethod] - public void DoNotCopyArraysInProperties_CSharp12() => - builder.AddPaths("DoNotCopyArraysInProperties.CSharp12.cs") - .WithOptions(ParseOptionsHelper.FromCSharp12) - .Verify(); + [TestMethod] + public void DoNotCopyArraysInProperties_CSharp12() => + builder.AddPaths("DoNotCopyArraysInProperties.CSharp12.cs") + .WithOptions(ParseOptionsHelper.FromCSharp12) + .VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotDecreaseMemberVisibilityTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotDecreaseMemberVisibilityTest.cs index 047c838bc9f..dfdfa2b0a7d 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotDecreaseMemberVisibilityTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotDecreaseMemberVisibilityTest.cs @@ -46,7 +46,7 @@ public class DoNotDecreaseMemberVisibilityTest public void DoNotDecreaseMemberVisibility_CSharp11() => builder.AddPaths("DoNotDecreaseMemberVisibility.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotExposeListTTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotExposeListTTest.cs index 8abbbe3e260..e4e7bbdc38d 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotExposeListTTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotExposeListTTest.cs @@ -51,19 +51,18 @@ public class DoNotExposeListTTest [TestMethod] public void DoNotExposeListT_InvalidCode() => - builder.AddSnippet( - @" -public class InvalidCode -{ - public List () => null; + builder.AddSnippet(""" + public class InvalidCode + { + public List () => null; - public List { get; set; } + public List { get; set; } - public List Method() => null; + public List Method() => null; - public InvalidType Method2() => null; -}") - .WithErrorBehavior(CompilationErrorBehavior.Ignore) - .Verify(); + public InvalidType Method2() => null; + } + """) + .VerifyNoIssuesIgnoreErrors(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotHideBaseClassMethodsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotHideBaseClassMethodsTest.cs index cec891552ae..eafc8ed6e04 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotHideBaseClassMethodsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotHideBaseClassMethodsTest.cs @@ -20,35 +20,34 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class DoNotHideBaseClassMethodsTest { - [TestClass] - public class DoNotHideBaseClassMethodsTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void DoNotHideBaseClassMethods() => - builder.AddPaths("DoNotHideBaseClassMethods.cs", "DoNotHideBaseClassMethods2.cs") - .WithAutogenerateConcurrentFiles(false) - .Verify(); + [TestMethod] + public void DoNotHideBaseClassMethods() => + builder.AddPaths("DoNotHideBaseClassMethods.cs", "DoNotHideBaseClassMethods2.cs") + .WithAutogenerateConcurrentFiles(false) + .Verify(); #if NET - [TestMethod] - public void DoNotHideBaseClassMethods_CSharp9() => - builder.AddPaths("DoNotHideBaseClassMethods.CSharp9.cs") - .WithOptions(ParseOptionsHelper.FromCSharp9) - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void DoNotHideBaseClassMethods_CSharp9() => + builder.AddPaths("DoNotHideBaseClassMethods.CSharp9.cs") + .WithOptions(ParseOptionsHelper.FromCSharp9) + .WithConcurrentAnalysis(false) + .Verify(); - [TestMethod] - public void DoNotHideBaseClassMethods_CSharp11() => - builder.AddPaths("DoNotHideBaseClassMethods.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void DoNotHideBaseClassMethods_CSharp11() => + builder.AddPaths("DoNotHideBaseClassMethods.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotOverloadOperatorEqualTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotOverloadOperatorEqualTest.cs index cfe34d2d7f6..46371d34092 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotOverloadOperatorEqualTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotOverloadOperatorEqualTest.cs @@ -20,32 +20,31 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class DoNotOverloadOperatorEqualTest { - [TestClass] - public class DoNotOverloadOperatorEqualTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void DoNotOverloadOperatorEqual() => - builder.AddPaths("DoNotOverloadOperatorEqual.cs").Verify(); + [TestMethod] + public void DoNotOverloadOperatorEqual() => + builder.AddPaths("DoNotOverloadOperatorEqual.cs").Verify(); #if NET - [TestMethod] - public void DoNotOverloadOperatorEqual_CSharp9() => - builder.AddPaths("DoNotOverloadOperatorEqual.CSharp9.cs") - .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); + [TestMethod] + public void DoNotOverloadOperatorEqual_CSharp9() => + builder.AddPaths("DoNotOverloadOperatorEqual.CSharp9.cs") + .WithOptions(ParseOptionsHelper.FromCSharp9) + .Verify(); - [TestMethod] - public void DoNotOverloadOperatorEqual_CSharp11() => - builder.AddPaths("DoNotOverloadOperatorEqual.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void DoNotOverloadOperatorEqual_CSharp11() => + builder.AddPaths("DoNotOverloadOperatorEqual.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotShiftByZeroOrIntSizeTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotShiftByZeroOrIntSizeTest.cs index 2e23d206b43..a092ecfd304 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotShiftByZeroOrIntSizeTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/DoNotShiftByZeroOrIntSizeTest.cs @@ -20,65 +20,64 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class DoNotShiftByZeroOrIntSizeTest { - [TestClass] - public class DoNotShiftByZeroOrIntSizeTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - public TestContext TestContext { get; set; } + public TestContext TestContext { get; set; } - [TestMethod] - public void DoNotShiftByZeroOrIntSize() => - builder.AddPaths("DoNotShiftByZeroOrIntSize.cs").Verify(); + [TestMethod] + public void DoNotShiftByZeroOrIntSize() => + builder.AddPaths("DoNotShiftByZeroOrIntSize.cs").Verify(); #if NET - [TestMethod] - public void DoNotShiftByZeroOrIntSize_CSharp9() => - builder.AddPaths("DoNotShiftByZeroOrIntSize.CSharp9.cs") - .WithTopLevelStatements() - .Verify(); + [TestMethod] + public void DoNotShiftByZeroOrIntSize_CSharp9() => + builder.AddPaths("DoNotShiftByZeroOrIntSize.CSharp9.cs") + .WithTopLevelStatements() + .VerifyNoIssues(); - [TestMethod] - public void DoNotShiftByZeroOrIntSize_CSharp10() => - builder.AddPaths("DoNotShiftByZeroOrIntSize.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + [TestMethod] + public void DoNotShiftByZeroOrIntSize_CSharp10() => + builder.AddPaths("DoNotShiftByZeroOrIntSize.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .Verify(); - [TestMethod] - public void DoNotShiftByZeroOrIntSize_CSharp11() => - builder.AddPaths("DoNotShiftByZeroOrIntSize.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void DoNotShiftByZeroOrIntSize_CSharp11() => + builder.AddPaths("DoNotShiftByZeroOrIntSize.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .Verify(); - [TestMethod] - public void DoNotShiftByZeroOrIntSize_RazorFile_CorrectMessage() => - builder.AddSnippet( - """ - @code + [TestMethod] + public void DoNotShiftByZeroOrIntSize_RazorFile_CorrectMessage() => + builder.AddSnippet( + """ + @code + { + public void Method() { - public void Method() - { - byte b = 1; - b = (byte)(b << 10); - b = (byte)(b << 10); - b = 1 << 0; + byte b = 1; + b = (byte)(b << 10); + b = (byte)(b << 10); + b = 1 << 0; - sbyte sb = 1; - sb = (sbyte)(sb << 10); + sbyte sb = 1; + sb = (sbyte)(sb << 10); - int i = 1 << 10; - i = i << 32; // Noncompliant - } + int i = 1 << 10; + i = i << 32; // Noncompliant } - """, - "SomeRazorFile.razor") - .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) - .Verify(); + } + """, + "SomeRazorFile.razor") + .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) + .Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/EmptyMethodTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/EmptyMethodTest.cs index 48209d12095..41c08650f30 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/EmptyMethodTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/EmptyMethodTest.cs @@ -21,104 +21,103 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class EmptyMethodTest { - [TestClass] - public class EmptyMethodTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder(); - private readonly VerifierBuilder builderVB = new VerifierBuilder(); - - [TestMethod] - public void EmptyMethod() => - builderCS.AddPaths("EmptyMethod.cs") - .WithOptions(ParseOptionsHelper.FromCSharp8) - .AddReferences(MetadataReferenceFacade.NetStandard21) - .Verify(); + private readonly VerifierBuilder builderCS = new VerifierBuilder(); + private readonly VerifierBuilder builderVB = new VerifierBuilder(); + + [TestMethod] + public void EmptyMethod() => + builderCS.AddPaths("EmptyMethod.cs") + .WithOptions(ParseOptionsHelper.FromCSharp8) + .AddReferences(MetadataReferenceFacade.NetStandard21) + .Verify(); #if NET - [TestMethod] - public void EmptyMethod_CSharp9() => - builderCS.AddPaths("EmptyMethod.CSharp9.cs") - .WithTopLevelStatements() - .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); - - [TestMethod] - public void EmptyMethod_CSharp9_CodeFix_Throw() => - builderCS.WithCodeFix() - .AddPaths("EmptyMethod.CSharp9.cs") - .WithTopLevelStatements() - .WithCodeFixedPaths("EmptyMethod.CSharp9.Throw.Fixed.cs") - .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleThrow) - .VerifyCodeFix(); - - [TestMethod] - public void EmptyMethod_CSharp9_CodeFix_Comment() => - builderCS.WithCodeFix() - .AddPaths("EmptyMethod.CSharp9.cs") - .WithTopLevelStatements() - .WithCodeFixedPaths("EmptyMethod.CSharp9.Comment.Fixed.cs") - .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleComment) - .VerifyCodeFix(); - - [TestMethod] - public void EmptyMethod_CSharp10() => - builderCS.AddPaths("EmptyMethod.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); - - [TestMethod] - public void EmptyMethod_CSharp11() => - builderCS.AddPaths("EmptyMethod.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void EmptyMethod_CSharp9() => + builderCS.AddPaths("EmptyMethod.CSharp9.cs") + .WithTopLevelStatements() + .WithOptions(ParseOptionsHelper.FromCSharp9) + .Verify(); + + [TestMethod] + public void EmptyMethod_CSharp9_CodeFix_Throw() => + builderCS.WithCodeFix() + .AddPaths("EmptyMethod.CSharp9.cs") + .WithTopLevelStatements() + .WithCodeFixedPaths("EmptyMethod.CSharp9.Throw.Fixed.cs") + .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleThrow) + .VerifyCodeFix(); + + [TestMethod] + public void EmptyMethod_CSharp9_CodeFix_Comment() => + builderCS.WithCodeFix() + .AddPaths("EmptyMethod.CSharp9.cs") + .WithTopLevelStatements() + .WithCodeFixedPaths("EmptyMethod.CSharp9.Comment.Fixed.cs") + .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleComment) + .VerifyCodeFix(); + + [TestMethod] + public void EmptyMethod_CSharp10() => + builderCS.AddPaths("EmptyMethod.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .VerifyNoIssues(); + + [TestMethod] + public void EmptyMethod_CSharp11() => + builderCS.AddPaths("EmptyMethod.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .Verify(); #endif - [TestMethod] - public void EmptyMethod_CodeFix_Throw() => - builderCS.WithCodeFix() - .AddPaths("EmptyMethod.cs") - .WithCodeFixedPaths("EmptyMethod.Throw.Fixed.cs") - .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleThrow) - .VerifyCodeFix(); - - [TestMethod] - public void EmptyMethod_CodeFix_Comment() => - builderCS.WithCodeFix() - .AddPaths("EmptyMethod.cs") - .WithCodeFixedPaths("EmptyMethod.Comment.Fixed.cs") - .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleComment) - .VerifyCodeFix(); - - [TestMethod] - public void EmptyMethod_WithoutClosingBracket_CodeFix_Comment() => - builderCS.WithCodeFix() - .AddPaths("EmptyMethod.WithoutClosingBracket.cs") - .WithCodeFixedPaths("EmptyMethod.WithoutClosingBracket.Comment.Fixed.cs") - .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleComment) - .VerifyCodeFix(); - - [TestMethod] - public void EmptyMethod_VB() => - builderVB.AddPaths("EmptyMethod.vb").Verify(); - - [TestMethod] - public void EmptyMethod_WithVirtualOverride_RaisesIssueForMainProject_CS() => - builderCS.AddPaths("EmptyMethod.OverrideVirtual.cs").Verify(); - - [TestMethod] - public void EmptyMethod_WithVirtualOverride_DoesNotRaiseIssuesForTestProject_CS() => - builderCS.AddPaths("EmptyMethod.OverrideVirtual.cs").AddTestReference().VerifyNoIssues(); - - [TestMethod] - public void EmptyMethod_WithVirtualOverride_RaisesIssueForMainProject_VB() => - builderVB.AddPaths("EmptyMethod.OverrideVirtual.vb").Verify(); - - [TestMethod] - public void EmptyMethod_WithVirtualOverride_DoesNotRaiseIssuesForTestProject_VB() => - builderVB.AddPaths("EmptyMethod.OverrideVirtual.vb").AddTestReference().VerifyNoIssues(); - } + [TestMethod] + public void EmptyMethod_CodeFix_Throw() => + builderCS.WithCodeFix() + .AddPaths("EmptyMethod.cs") + .WithCodeFixedPaths("EmptyMethod.Throw.Fixed.cs") + .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleThrow) + .VerifyCodeFix(); + + [TestMethod] + public void EmptyMethod_CodeFix_Comment() => + builderCS.WithCodeFix() + .AddPaths("EmptyMethod.cs") + .WithCodeFixedPaths("EmptyMethod.Comment.Fixed.cs") + .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleComment) + .VerifyCodeFix(); + + [TestMethod] + public void EmptyMethod_WithoutClosingBracket_CodeFix_Comment() => + builderCS.WithCodeFix() + .AddPaths("EmptyMethod.WithoutClosingBracket.cs") + .WithCodeFixedPaths("EmptyMethod.WithoutClosingBracket.Comment.Fixed.cs") + .WithCodeFixTitle(CS.EmptyMethodCodeFix.TitleComment) + .VerifyCodeFix(); + + [TestMethod] + public void EmptyMethod_VB() => + builderVB.AddPaths("EmptyMethod.vb").Verify(); + + [TestMethod] + public void EmptyMethod_WithVirtualOverride_RaisesIssueForMainProject_CS() => + builderCS.AddPaths("EmptyMethod.OverrideVirtual.cs").Verify(); + + [TestMethod] + public void EmptyMethod_WithVirtualOverride_DoesNotRaiseIssuesForTestProject_CS() => + builderCS.AddPaths("EmptyMethod.OverrideVirtual.cs").AddTestReference().VerifyNoIssues(); + + [TestMethod] + public void EmptyMethod_WithVirtualOverride_RaisesIssueForMainProject_VB() => + builderVB.AddPaths("EmptyMethod.OverrideVirtual.vb").Verify(); + + [TestMethod] + public void EmptyMethod_WithVirtualOverride_DoesNotRaiseIssuesForTestProject_VB() => + builderVB.AddPaths("EmptyMethod.OverrideVirtual.vb").AddTestReference().VerifyNoIssues(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/EmptyNestedBlockTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/EmptyNestedBlockTest.cs index 41a87036f66..e26de171799 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/EmptyNestedBlockTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/EmptyNestedBlockTest.cs @@ -21,31 +21,30 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class EmptyNestedBlockTest { - [TestClass] - public class EmptyNestedBlockTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder(); + private readonly VerifierBuilder builderCS = new VerifierBuilder(); - [TestMethod] - public void EmptyNestedBlock_CS() => - builderCS.AddPaths("EmptyNestedBlock.cs", "EmptyNestedBlock2.cs") - .WithAutogenerateConcurrentFiles(false) - .Verify(); + [TestMethod] + public void EmptyNestedBlock_CS() => + builderCS.AddPaths("EmptyNestedBlock.cs", "EmptyNestedBlock2.cs") + .WithAutogenerateConcurrentFiles(false) + .Verify(); #if NET - [TestMethod] - public void EmptyNestedBlock_CSharp10() => - builderCS.AddPaths("EmptyNestedBlock.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + [TestMethod] + public void EmptyNestedBlock_CSharp10() => + builderCS.AddPaths("EmptyNestedBlock.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .VerifyNoIssues(); #endif - [TestMethod] - public void EmptyNestedBlock_VB() => - new VerifierBuilder().AddPaths("EmptyNestedBlock.vb").Verify(); - } + [TestMethod] + public void EmptyNestedBlock_VB() => + new VerifierBuilder().AddPaths("EmptyNestedBlock.vb").Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ExceptionsNeedStandardConstructorsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ExceptionsNeedStandardConstructorsTest.cs index 4288ed7fe07..f10bf01ca77 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ExceptionsNeedStandardConstructorsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ExceptionsNeedStandardConstructorsTest.cs @@ -33,18 +33,18 @@ public class ExceptionsNeedStandardConstructorsTest [TestMethod] public void ExceptionsNeedStandardConstructors_InvalidCode() => - builder.AddSnippet(@" -public class : Exception -{ - My_07_Exception() {} + builder.AddSnippet(""" + public class : Exception + { + My_07_Exception() {} - My_07_Exception(string message) { } + My_07_Exception(string message) { } - My_07_Exception(string message, Exception innerException) {} + My_07_Exception(string message, Exception innerException) {} - My_07_Exception(SerializationInfo info, StreamingContext context) {} -}") - .WithErrorBehavior(CompilationErrorBehavior.Ignore) - .Verify(); + My_07_Exception(SerializationInfo info, StreamingContext context) {} + } + """) + .VerifyNoIssuesIgnoreErrors(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ExceptionsShouldBeLoggedOrThrownTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ExceptionsShouldBeLoggedOrThrownTest.cs index 62d78df398b..fb0aa5e9c13 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ExceptionsShouldBeLoggedOrThrownTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ExceptionsShouldBeLoggedOrThrownTest.cs @@ -56,7 +56,7 @@ public void Method(ILogger logger, object x) """) .AddReferences(NuGetMetadataReference.MicrosoftExtensionsLoggingAbstractions()) .WithOptions(ParseOptionsHelper.FromCSharp8) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void ExceptionsShouldBeLoggedOrThrown_Log4net_CS() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/FinalizerShouldNotBeEmptyTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/FinalizerShouldNotBeEmptyTest.cs index 05d68eeefd1..09b79560c0d 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/FinalizerShouldNotBeEmptyTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/FinalizerShouldNotBeEmptyTest.cs @@ -43,11 +43,12 @@ public class FinalizerShouldNotBeEmptyTest [TestMethod] public void FinalizerShouldNotBeEmpty_InvalidCode() => - builder.AddSnippet(@"class Program4 - { - ~Program4() => - }") - .WithErrorBehavior(CompilationErrorBehavior.Ignore) - .Verify(); + builder.AddSnippet(""" + class Program4 + { + ~Program4() => + } + """) + .VerifyNoIssuesIgnoreErrors(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ForLoopCounterChangedTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ForLoopCounterChangedTest.cs index f3417a88e16..b0947dfe6d0 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ForLoopCounterChangedTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ForLoopCounterChangedTest.cs @@ -20,32 +20,31 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class ForLoopCounterChangedTest { - [TestClass] - public class ForLoopCounterChangedTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void ForLoopCounterChanged() => - builder.AddPaths("ForLoopCounterChanged.cs").Verify(); + [TestMethod] + public void ForLoopCounterChanged() => + builder.AddPaths("ForLoopCounterChanged.cs").Verify(); #if NET - [TestMethod] - public void ForLoopCounterChanged_CSharp10() => - builder.AddPaths("ForLoopCounterChanged.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + [TestMethod] + public void ForLoopCounterChanged_CSharp10() => + builder.AddPaths("ForLoopCounterChanged.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .Verify(); - [TestMethod] - public void ForLoopCounterChanged_CSharp11() => - builder.AddPaths("ForLoopCounterChanged.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void ForLoopCounterChanged_CSharp11() => + builder.AddPaths("ForLoopCounterChanged.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/FunctionComplexityTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/FunctionComplexityTest.cs index 6a56ebe2d36..ad646dec252 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/FunctionComplexityTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/FunctionComplexityTest.cs @@ -50,7 +50,7 @@ public void FunctionComplexity_InsufficientExecutionStack_CS() { if (!TestContextHelper.IsAzureDevOpsContext) // ToDo: Test doesn't work on Azure DevOps { - CreateCSBuilder(3).AddPaths("SyntaxWalker_InsufficientExecutionStackException.cs").Verify(); + CreateCSBuilder(3).AddPaths("SyntaxWalker_InsufficientExecutionStackException.cs").VerifyNoIssues(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/GenericTypeParameterUnusedTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/GenericTypeParameterUnusedTest.cs index dcd7bc9513c..9c032aea90c 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/GenericTypeParameterUnusedTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/GenericTypeParameterUnusedTest.cs @@ -20,36 +20,35 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class GenericTypeParameterUnusedTest { - [TestClass] - public class GenericTypeParameterUnusedTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void GenericTypeParameterUnused() => - builder.AddPaths("GenericTypeParameterUnused.cs", "GenericTypeParameterUnused.Partial.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + [TestMethod] + public void GenericTypeParameterUnused() => + builder.AddPaths("GenericTypeParameterUnused.cs", "GenericTypeParameterUnused.Partial.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); #if NET - [TestMethod] - public void GenericTypeParameterUnused_CSharp9() => - builder.AddPaths("GenericTypeParameterUnused.CSharp9.cs").WithTopLevelStatements().Verify(); + [TestMethod] + public void GenericTypeParameterUnused_CSharp9() => + builder.AddPaths("GenericTypeParameterUnused.CSharp9.cs").WithTopLevelStatements().Verify(); - [TestMethod] - public void GenericTypeParameterUnused_CSharp10() => - builder.AddPaths("GenericTypeParameterUnused.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void GenericTypeParameterUnused_CSharp10() => + builder.AddPaths("GenericTypeParameterUnused.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); - [TestMethod] - public void GenericTypeParameterUnused_CSharp11() => - builder.AddPaths("GenericTypeParameterUnused.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void GenericTypeParameterUnused_CSharp11() => + builder.AddPaths("GenericTypeParameterUnused.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); - [TestMethod] - public void GenericTypeParameterUnused_CSharp12() => - builder.AddPaths("GenericTypeParameterUnused.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + [TestMethod] + public void GenericTypeParameterUnused_CSharp12() => + builder.AddPaths("GenericTypeParameterUnused.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/GetHashCodeEqualsOverrideTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/GetHashCodeEqualsOverrideTest.cs index d39f4f7c629..5b572f76410 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/GetHashCodeEqualsOverrideTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/GetHashCodeEqualsOverrideTest.cs @@ -37,7 +37,7 @@ public class GetHashCodeEqualsOverrideTest public void GetHashCodeEqualsOverride_CSharp9() => builder.AddPaths("GetHashCodeEqualsOverride.CSharp9.cs") .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/GetTypeWithIsAssignableFromTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/GetTypeWithIsAssignableFromTest.cs index 215108e23f3..5ce7afb33dd 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/GetTypeWithIsAssignableFromTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/GetTypeWithIsAssignableFromTest.cs @@ -20,62 +20,61 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class GetTypeWithIsAssignableFromTest { - [TestClass] - public class GetTypeWithIsAssignableFromTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void GetTypeWithIsAssignableFrom() => - builder.AddPaths("GetTypeWithIsAssignableFrom.cs").Verify(); + [TestMethod] + public void GetTypeWithIsAssignableFrom() => + builder.AddPaths("GetTypeWithIsAssignableFrom.cs").Verify(); #if NET - [TestMethod] - public void GetTypeWithIsAssignableFrom_CSharp9() => - builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp9.cs") - .WithTopLevelStatements() - .Verify(); + [TestMethod] + public void GetTypeWithIsAssignableFrom_CSharp9() => + builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp9.cs") + .WithTopLevelStatements() + .Verify(); - [TestMethod] - public void GetTypeWithIsAssignableFrom_CSharp9_CodeFix() => - builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp9.cs") - .WithCodeFix() - .WithCodeFixedPaths("GetTypeWithIsAssignableFrom.CSharp9.Fixed.cs") - .WithTopLevelStatements() - .VerifyCodeFix(); + [TestMethod] + public void GetTypeWithIsAssignableFrom_CSharp9_CodeFix() => + builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp9.cs") + .WithCodeFix() + .WithCodeFixedPaths("GetTypeWithIsAssignableFrom.CSharp9.Fixed.cs") + .WithTopLevelStatements() + .VerifyCodeFix(); - [TestMethod] - public void GetTypeWithIsAssignableFrom_CSharp10() => - builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp10.cs") - .WithTopLevelStatements() - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + [TestMethod] + public void GetTypeWithIsAssignableFrom_CSharp10() => + builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp10.cs") + .WithTopLevelStatements() + .WithOptions(ParseOptionsHelper.FromCSharp10) + .Verify(); - [TestMethod] - public void GetTypeWithIsAssignableFrom_CSharp10_CodeFix() => - builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp10.cs") - .WithCodeFix() - .WithCodeFixedPaths("GetTypeWithIsAssignableFrom.CSharp10.Fixed.cs") - .WithTopLevelStatements() - .WithOptions(ParseOptionsHelper.FromCSharp10) - .VerifyCodeFix(); + [TestMethod] + public void GetTypeWithIsAssignableFrom_CSharp10_CodeFix() => + builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp10.cs") + .WithCodeFix() + .WithCodeFixedPaths("GetTypeWithIsAssignableFrom.CSharp10.Fixed.cs") + .WithTopLevelStatements() + .WithOptions(ParseOptionsHelper.FromCSharp10) + .VerifyCodeFix(); - [TestMethod] - public void GetTypeWithIsAssignableFrom_CSharp11() => - builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void GetTypeWithIsAssignableFrom_CSharp11() => + builder.AddPaths("GetTypeWithIsAssignableFrom.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .VerifyNoIssues(); #endif - [TestMethod] - public void GetTypeWithIsAssignableFrom_CodeFix() => - builder.AddPaths("GetTypeWithIsAssignableFrom.cs") - .WithCodeFix() - .WithCodeFixedPaths("GetTypeWithIsAssignableFrom.Fixed.cs", "GetTypeWithIsAssignableFrom.Fixed.Batch.cs") - .VerifyCodeFix(); - } + [TestMethod] + public void GetTypeWithIsAssignableFrom_CodeFix() => + builder.AddPaths("GetTypeWithIsAssignableFrom.cs") + .WithCodeFix() + .WithCodeFixedPaths("GetTypeWithIsAssignableFrom.Fixed.cs", "GetTypeWithIsAssignableFrom.Fixed.Batch.cs") + .VerifyCodeFix(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/CommandPathTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/CommandPathTest.cs index f90c4313f9e..bc47073bf05 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/CommandPathTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/CommandPathTest.cs @@ -55,7 +55,7 @@ public class CommandPathTest public void CommandPath_CSharp12() => builderCS.AddPaths("CommandPath.CSharp12.cs") .WithOptions(ParseOptionsHelper.FromCSharp12) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/CreatingHashAlgorithmsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/CreatingHashAlgorithmsTest.cs index 35fcfd20476..6334ffaf170 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/CreatingHashAlgorithmsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/CreatingHashAlgorithmsTest.cs @@ -21,57 +21,56 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class CreatingHashAlgorithmsTest { - [TestClass] - public class CreatingHashAlgorithmsTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder().WithBasePath("Hotspots") - .AddReferences(MetadataReferenceFacade.SystemSecurityCryptography) - .AddAnalyzer(() => new CS.CreatingHashAlgorithms(AnalyzerConfiguration.AlwaysEnabled)); - private readonly VerifierBuilder builderVB = new VerifierBuilder().WithBasePath("Hotspots") - .AddReferences(MetadataReferenceFacade.SystemSecurityCryptography) - .AddAnalyzer(() => new VB.CreatingHashAlgorithms(AnalyzerConfiguration.AlwaysEnabled)); - - [TestMethod] - public void CreatingHashAlgorithms_CSharp8() => - builderCS.AddPaths("CreatingHashAlgorithms.cs") - .WithOptions(ParseOptionsHelper.FromCSharp8) - .Verify(); + private readonly VerifierBuilder builderCS = new VerifierBuilder().WithBasePath("Hotspots") + .AddReferences(MetadataReferenceFacade.SystemSecurityCryptography) + .AddAnalyzer(() => new CS.CreatingHashAlgorithms(AnalyzerConfiguration.AlwaysEnabled)); + private readonly VerifierBuilder builderVB = new VerifierBuilder().WithBasePath("Hotspots") + .AddReferences(MetadataReferenceFacade.SystemSecurityCryptography) + .AddAnalyzer(() => new VB.CreatingHashAlgorithms(AnalyzerConfiguration.AlwaysEnabled)); + + [TestMethod] + public void CreatingHashAlgorithms_CSharp8() => + builderCS.AddPaths("CreatingHashAlgorithms.cs") + .WithOptions(ParseOptionsHelper.FromCSharp8) + .Verify(); #if NETFRAMEWORK // HMACRIPEMD160, MD5Cng, RIPEMD160Managed and RIPEMD160 are available only for .Net Framework - [TestMethod] - public void CreatingHashAlgorithms_CS_NetFx() => - builderCS.AddPaths("CreatingHashAlgorithms.NetFramework.cs") - .WithOptions(ParseOptionsHelper.FromCSharp8) - .Verify(); + [TestMethod] + public void CreatingHashAlgorithms_CS_NetFx() => + builderCS.AddPaths("CreatingHashAlgorithms.NetFramework.cs") + .WithOptions(ParseOptionsHelper.FromCSharp8) + .Verify(); #endif - [TestMethod] - public void CreatingHashAlgorithms_VB() => - builderVB.AddPaths("CreatingHashAlgorithms.vb").Verify(); + [TestMethod] + public void CreatingHashAlgorithms_VB() => + builderVB.AddPaths("CreatingHashAlgorithms.vb").Verify(); #if NETFRAMEWORK // HMACRIPEMD160, MD5Cng, RIPEMD160Managed and RIPEMD160 are available only for .Net Framework - [TestMethod] - public void CreatingHashAlgorithms_VB_NetFx() => - builderVB.AddPaths("CreatingHashAlgorithms.NetFramework.vb").Verify(); + [TestMethod] + public void CreatingHashAlgorithms_VB_NetFx() => + builderVB.AddPaths("CreatingHashAlgorithms.NetFramework.vb").Verify(); #endif #if NET - [TestMethod] - public void CreatingHashAlgorithms_CSharp11() => - builderCS.AddPaths("CreatingHashAlgorithms.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void CreatingHashAlgorithms_CSharp11() => + builderCS.AddPaths("CreatingHashAlgorithms.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); - [TestMethod] - public void CreatingHashAlgorithms_CSharp12() => - builderCS.AddPaths("CreatingHashAlgorithms.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + [TestMethod] + public void CreatingHashAlgorithms_CSharp12() => + builderCS.AddPaths("CreatingHashAlgorithms.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/DeliveringDebugFeaturesInProductionTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/DeliveringDebugFeaturesInProductionTest.cs index d99caaa5879..5cc402583a7 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/DeliveringDebugFeaturesInProductionTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/Hotspots/DeliveringDebugFeaturesInProductionTest.cs @@ -21,72 +21,69 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class DeliveringDebugFeaturesInProductionTest { - [TestClass] - public class DeliveringDebugFeaturesInProductionTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder().WithBasePath("Hotspots").AddAnalyzer(() => new CS.DeliveringDebugFeaturesInProduction(AnalyzerConfiguration.AlwaysEnabled)); - private readonly VerifierBuilder builderVB = new VerifierBuilder().WithBasePath("Hotspots").AddAnalyzer(() => new VB.DeliveringDebugFeaturesInProduction(AnalyzerConfiguration.AlwaysEnabled)); + private readonly VerifierBuilder builderCS = new VerifierBuilder().WithBasePath("Hotspots").AddAnalyzer(() => new CS.DeliveringDebugFeaturesInProduction(AnalyzerConfiguration.AlwaysEnabled)); + private readonly VerifierBuilder builderVB = new VerifierBuilder().WithBasePath("Hotspots").AddAnalyzer(() => new VB.DeliveringDebugFeaturesInProduction(AnalyzerConfiguration.AlwaysEnabled)); - [TestMethod] - public void DeliveringDebugFeaturesInProduction_NetCore2_CS() => - builderCS.AddPaths("DeliveringDebugFeaturesInProduction.NetCore2.cs") - .AddReferences(AdditionalReferencesForAspNetCore2) - .Verify(); + [TestMethod] + public void DeliveringDebugFeaturesInProduction_NetCore2_CS() => + builderCS.AddPaths("DeliveringDebugFeaturesInProduction.NetCore2.cs") + .AddReferences(AdditionalReferencesForAspNetCore2) + .Verify(); - [TestMethod] - public void DeliveringDebugFeaturesInProduction_NetCore2_VB() => - builderVB.AddPaths("DeliveringDebugFeaturesInProduction.NetCore2.vb") - .AddReferences(AdditionalReferencesForAspNetCore2) - .Verify(); + [TestMethod] + public void DeliveringDebugFeaturesInProduction_NetCore2_VB() => + builderVB.AddPaths("DeliveringDebugFeaturesInProduction.NetCore2.vb") + .AddReferences(AdditionalReferencesForAspNetCore2) + .Verify(); #if NET - [TestMethod] - public void DeliveringDebugFeaturesInProduction_NetCore3_CS() => - builderCS.AddPaths("DeliveringDebugFeaturesInProduction.NetCore3.cs") - .AddReferences(AdditionalReferencesForAspNetCore3AndLater) - .Verify(); - - [TestMethod] - public void DeliveringDebugFeaturesInProduction_NetCore3_VB() => - builderVB.AddPaths("DeliveringDebugFeaturesInProduction.NetCore3.vb") - .AddReferences(AdditionalReferencesForAspNetCore3AndLater) - .Verify(); + [TestMethod] + public void DeliveringDebugFeaturesInProduction_NetCore3_CS() => + builderCS.AddPaths("DeliveringDebugFeaturesInProduction.NetCore3.cs") + .AddReferences(AdditionalReferencesForAspNetCore3AndLater) + .Verify(); - [TestMethod] - public void DeliveringDebugFeaturesInProduction_Net7_CS() => - builderCS.AddPaths("DeliveringDebugFeaturesInProduction.Net7.cs") - .WithTopLevelStatements() - .AddReferences(new[] - { - AspNetCoreMetadataReference.MicrosoftAspNetCore, - AspNetCoreMetadataReference.MicrosoftAspNetCoreRouting, - AspNetCoreMetadataReference.MicrosoftAspNetCoreDiagnostics, - AspNetCoreMetadataReference.MicrosoftAspNetCoreHttpAbstractions, - AspNetCoreMetadataReference.MicrosoftAspNetCoreHostingAbstractions, - AspNetCoreMetadataReference.MicrosoftExtensionsHostingAbstractions, - }) - .Verify(); + [TestMethod] + public void DeliveringDebugFeaturesInProduction_NetCore3_VB() => + builderVB.AddPaths("DeliveringDebugFeaturesInProduction.NetCore3.vb") + .AddReferences(AdditionalReferencesForAspNetCore3AndLater) + .Verify(); - private static IEnumerable AdditionalReferencesForAspNetCore3AndLater => - new[] - { + [TestMethod] + public void DeliveringDebugFeaturesInProduction_Net7_CS() => + builderCS.AddPaths("DeliveringDebugFeaturesInProduction.Net7.cs") + .WithTopLevelStatements() + .AddReferences([ + AspNetCoreMetadataReference.MicrosoftAspNetCore, + AspNetCoreMetadataReference.MicrosoftAspNetCoreRouting, AspNetCoreMetadataReference.MicrosoftAspNetCoreDiagnostics, - AspNetCoreMetadataReference.MicrosoftAspNetCoreHostingAbstractions, AspNetCoreMetadataReference.MicrosoftAspNetCoreHttpAbstractions, - AspNetCoreMetadataReference.MicrosoftExtensionsHostingAbstractions - }; + AspNetCoreMetadataReference.MicrosoftAspNetCoreHostingAbstractions, + AspNetCoreMetadataReference.MicrosoftExtensionsHostingAbstractions]) + .VerifyNoIssues(); + + private static IEnumerable AdditionalReferencesForAspNetCore3AndLater => + new[] + { + AspNetCoreMetadataReference.MicrosoftAspNetCoreDiagnostics, + AspNetCoreMetadataReference.MicrosoftAspNetCoreHostingAbstractions, + AspNetCoreMetadataReference.MicrosoftAspNetCoreHttpAbstractions, + AspNetCoreMetadataReference.MicrosoftExtensionsHostingAbstractions + }; #endif - internal static IEnumerable AdditionalReferencesForAspNetCore2 => - Enumerable.Empty() - .Concat(MetadataReferenceFacade.NetStandard) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreDiagnostics(Constants.DotNetCore220Version)) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreDiagnosticsEntityFrameworkCore(Constants.DotNetCore220Version)) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreHttpAbstractions(Constants.DotNetCore220Version)) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreHostingAbstractions(Constants.DotNetCore220Version)); - } + internal static IEnumerable AdditionalReferencesForAspNetCore2 => + Enumerable.Empty() + .Concat(MetadataReferenceFacade.NetStandard) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreDiagnostics(Constants.DotNetCore220Version)) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreDiagnosticsEntityFrameworkCore(Constants.DotNetCore220Version)) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreHttpAbstractions(Constants.DotNetCore220Version)) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreHostingAbstractions(Constants.DotNetCore220Version)); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ImplementIDisposableCorrectlyTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ImplementIDisposableCorrectlyTest.cs index a61818768d4..b01e7ec989f 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ImplementIDisposableCorrectlyTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ImplementIDisposableCorrectlyTest.cs @@ -20,31 +20,30 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class ImplementIDisposableCorrectlyTest { - [TestClass] - public class ImplementIDisposableCorrectlyTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void ImplementIDisposableCorrectly() => - builder.AddPaths("ImplementIDisposableCorrectly.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + [TestMethod] + public void ImplementIDisposableCorrectly() => + builder.AddPaths("ImplementIDisposableCorrectly.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); #if NET - [TestMethod] - public void ImplementIDisposableCorrectly_FromCSharp9() => - builder.AddPaths("ImplementIDisposableCorrectly.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + [TestMethod] + public void ImplementIDisposableCorrectly_FromCSharp9() => + builder.AddPaths("ImplementIDisposableCorrectly.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); #endif - [TestMethod] - public void ImplementIDisposableCorrectly_AbstractClass() => - builder.AddPaths("ImplementIDisposableCorrectly.AbstractClass.cs").Verify(); + [TestMethod] + public void ImplementIDisposableCorrectly_AbstractClass() => + builder.AddPaths("ImplementIDisposableCorrectly.AbstractClass.cs").Verify(); - [TestMethod] - public void ImplementIDisposableCorrectly_PartialClassesInDifferentFiles() => - builder.AddPaths("ImplementIDisposableCorrectlyPartial1.cs", "ImplementIDisposableCorrectlyPartial2.cs").Verify(); - } + [TestMethod] + public void ImplementIDisposableCorrectly_PartialClassesInDifferentFiles() => + builder.AddPaths("ImplementIDisposableCorrectlyPartial1.cs", "ImplementIDisposableCorrectlyPartial2.cs").VerifyNoIssues(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ImplementSerializationMethodsCorrectlyTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ImplementSerializationMethodsCorrectlyTest.cs index 73b068b2600..b4aa1c50ff3 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ImplementSerializationMethodsCorrectlyTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ImplementSerializationMethodsCorrectlyTest.cs @@ -21,61 +21,60 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class ImplementSerializationMethodsCorrectlyTest { - [TestClass] - public class ImplementSerializationMethodsCorrectlyTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder(); - private readonly VerifierBuilder builderVB = new VerifierBuilder(); + private readonly VerifierBuilder builderCS = new VerifierBuilder(); + private readonly VerifierBuilder builderVB = new VerifierBuilder(); - [TestMethod] - public void ImplementSerializationMethodsCorrectly_CS() => - builderCS.AddPaths("ImplementSerializationMethodsCorrectly.cs").Verify(); + [TestMethod] + public void ImplementSerializationMethodsCorrectly_CS() => + builderCS.AddPaths("ImplementSerializationMethodsCorrectly.cs").Verify(); #if NET - [TestMethod] - public void ImplementSerializationMethodsCorrectly_CSharp8() => - builderCS.AddPaths("ImplementSerializationMethodsCorrectly.CSharp8.cs") - .WithOptions(ParseOptionsHelper.FromCSharp8) - .Verify(); + [TestMethod] + public void ImplementSerializationMethodsCorrectly_CSharp8() => + builderCS.AddPaths("ImplementSerializationMethodsCorrectly.CSharp8.cs") + .WithOptions(ParseOptionsHelper.FromCSharp8) + .VerifyNoIssues(); - [TestMethod] - public void ImplementSerializationMethodsCorrectly_CSharp9() => - builderCS.AddPaths("ImplementSerializationMethodsCorrectly.CSharp9.cs") - .WithTopLevelStatements() - .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); + [TestMethod] + public void ImplementSerializationMethodsCorrectly_CSharp9() => + builderCS.AddPaths("ImplementSerializationMethodsCorrectly.CSharp9.cs") + .WithTopLevelStatements() + .WithOptions(ParseOptionsHelper.FromCSharp9) + .Verify(); - [TestMethod] - public void ImplementSerializationMethodsCorrectly_CSharp10() => - builderCS.AddPaths("ImplementSerializationMethodsCorrectly.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + [TestMethod] + public void ImplementSerializationMethodsCorrectly_CSharp10() => + builderCS.AddPaths("ImplementSerializationMethodsCorrectly.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .Verify(); - [TestMethod] - public void ImplementSerializationMethodsCorrectly_CSharp11() => - builderCS.AddPaths("ImplementSerializationMethodsCorrectly.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void ImplementSerializationMethodsCorrectly_CSharp11() => + builderCS.AddPaths("ImplementSerializationMethodsCorrectly.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .Verify(); #endif - [TestMethod] - public void ImplementSerializationMethodsCorrectly_CS_InvalidCode() => - builderCS.AddSnippet(@" -[Serializable] -public class Foo -{ - [OnDeserializing] - public int { throw new NotImplementedException(); } -}") - .WithErrorBehavior(CompilationErrorBehavior.Ignore) - .Verify(); + [TestMethod] + public void ImplementSerializationMethodsCorrectly_CS_InvalidCode() => + builderCS.AddSnippet(""" + [Serializable] + public class Foo + { + [OnDeserializing] + public int { throw new NotImplementedException(); } + } + """) + .VerifyNoIssuesIgnoreErrors(); - [TestMethod] - public void ImplementSerializationMethodsCorrectly_VB() => - builderVB.AddPaths("ImplementSerializationMethodsCorrectly.vb").Verify(); - } + [TestMethod] + public void ImplementSerializationMethodsCorrectly_VB() => + builderVB.AddPaths("ImplementSerializationMethodsCorrectly.vb").Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/InfiniteRecursionTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/InfiniteRecursionTest.cs index cda3e3fa908..a067f4d1f22 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/InfiniteRecursionTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/InfiniteRecursionTest.cs @@ -21,53 +21,53 @@ using System.Text; using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class InfiniteRecursionTest { - [TestClass] - public class InfiniteRecursionTest - { - private readonly VerifierBuilder sonarCfg = new VerifierBuilder() - .AddAnalyzer(() => new InfiniteRecursion(AnalyzerConfiguration.AlwaysEnabledWithSonarCfg)) - .AddReferences(MetadataReferenceFacade.NetStandard21); + private readonly VerifierBuilder sonarCfg = new VerifierBuilder() + .AddAnalyzer(() => new InfiniteRecursion(AnalyzerConfiguration.AlwaysEnabledWithSonarCfg)) + .AddReferences(MetadataReferenceFacade.NetStandard21); - private readonly VerifierBuilder roslynCfg = new VerifierBuilder() - .AddReferences(MetadataReferenceFacade.NetStandard21); + private readonly VerifierBuilder roslynCfg = new VerifierBuilder() + .AddReferences(MetadataReferenceFacade.NetStandard21); - [TestMethod] - public void InfiniteRecursion_SonarCfg() => - sonarCfg.AddPaths("InfiniteRecursion.SonarCfg.cs") - .WithOptions(ParseOptionsHelper.OnlyCSharp7) - .Verify(); + [TestMethod] + public void InfiniteRecursion_SonarCfg() => + sonarCfg.AddPaths("InfiniteRecursion.SonarCfg.cs") + .WithOptions(ParseOptionsHelper.OnlyCSharp7) + .Verify(); - [TestMethod] - public void InfiniteRecursion_RoslynCfg() => - roslynCfg.AddPaths("InfiniteRecursion.RoslynCfg.cs") - .WithOptions(ParseOptionsHelper.FromCSharp8) - .Verify(); + [TestMethod] + public void InfiniteRecursion_RoslynCfg() => + roslynCfg.AddPaths("InfiniteRecursion.RoslynCfg.cs") + .WithOptions(ParseOptionsHelper.FromCSharp8) + .Verify(); #if NET - [TestMethod] - public void InfiniteRecursion_RoslynCfg_CSharp9() => - roslynCfg.AddPaths("InfiniteRecursion.RoslynCfg.CSharp9.cs") - .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); + [TestMethod] + public void InfiniteRecursion_RoslynCfg_CSharp9() => + roslynCfg.AddPaths("InfiniteRecursion.RoslynCfg.CSharp9.cs") + .WithOptions(ParseOptionsHelper.FromCSharp9) + .Verify(); - [TestMethod] - public void InfiniteRecursion_CSharp11() => - roslynCfg.AddPaths("InfiniteRecursion.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void InfiniteRecursion_CSharp11() => + roslynCfg.AddPaths("InfiniteRecursion.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .Verify(); #endif - // https://github.com/SonarSource/sonar-dotnet/issues/8977 - [TestMethod] - public void InfiniteRecursion_RoslynCfg_8977() - { - const int rows = 4_000; - var code = new StringBuilder(); - code.Append(""" + // https://github.com/SonarSource/sonar-dotnet/issues/8977 + [TestMethod] + public void InfiniteRecursion_RoslynCfg_8977() + { + const int rows = 4_000; + var code = new StringBuilder(); + code.Append(""" using UInt32Value = System.UInt32; using StringValue = System.String; @@ -127,34 +127,33 @@ void GenerateWorksheetPart1Content(WorksheetPart worksheetPart1) SheetData sheetData1 = new SheetData(); """); - for (var i = 1; i <= rows; i++) - { - code.Append($$""" - Row row{{i}} = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue() { InnerText = "1:1" }, DyDescent = 0.25D }; + for (var i = 1; i <= rows; i++) + { + code.Append($$""" + Row row{{i}} = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue() { InnerText = "1:1" }, DyDescent = 0.25D }; - Cell cell{{i}} = new Cell() { CellReference = "A{{i}}", StyleIndex = (UInt32Value)1U }; - CellValue cellValue{{i}} = new CellValue(); - cellValue{{i}}.Text = "{{i}}"; + Cell cell{{i}} = new Cell() { CellReference = "A{{i}}", StyleIndex = (UInt32Value)1U }; + CellValue cellValue{{i}} = new CellValue(); + cellValue{{i}}.Text = "{{i}}"; - cell{{i}}.Append(cellValue{{i}}); + cell{{i}}.Append(cellValue{{i}}); - row{{i}}.Append(cell{{i}}); - """); - } - for (var i = 1; i <= rows; i++) - { - code.AppendLine($$""" sheetData1.Append(row{{i}});"""); - } - code.Append("""" - worksheet1.Append(sheetData1); - worksheetPart1.Worksheet = worksheet1; - } + row{{i}}.Append(cell{{i}}); + """); + } + for (var i = 1; i <= rows; i++) + { + code.AppendLine($$""" sheetData1.Append(row{{i}});"""); + } + code.Append("""" + worksheet1.Append(sheetData1); + worksheetPart1.Worksheet = worksheet1; } - """"); - - roslynCfg.AddSnippet(code.ToString()) - .WithOptions(ParseOptionsHelper.FromCSharp8) - .Verify(); } + """"); + + roslynCfg.AddSnippet(code.ToString()) + .WithOptions(ParseOptionsHelper.FromCSharp8) + .VerifyNoIssues(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/InsteadOfAnyTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/InsteadOfAnyTest.cs index 1365b1f23bd..dae987e2e10 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/InsteadOfAnyTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/InsteadOfAnyTest.cs @@ -56,7 +56,7 @@ public class InsteadOfAnyTest public void InsteadOfAny_EntityFramework_Framework() => builderCS.AddPaths("InsteadOfAny.EntityFramework.Framework.cs") .AddReferences(GetReferencesEntityFrameworkNetFramework()) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/JSInvokableMethodsShouldBePublicTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/JSInvokableMethodsShouldBePublicTest.cs index c4e418b1b4d..42ced08a763 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/JSInvokableMethodsShouldBePublicTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/JSInvokableMethodsShouldBePublicTest.cs @@ -54,7 +54,7 @@ public class JSInvokableMethodsShouldBePublicTest public void JSInvokableMethodsShouldBePublic_CSharp9() => builder.AddPaths("JSInvokableMethodsShouldBePublic.CSharp9.cs") .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); + .VerifyNoIssues(); } #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/LiteralSuffixUpperCaseTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/LiteralSuffixUpperCaseTest.cs index 6af997dedfa..82590d42eb5 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/LiteralSuffixUpperCaseTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/LiteralSuffixUpperCaseTest.cs @@ -50,7 +50,7 @@ public class LiteralSuffixUpperCaseTest public void LiteralSuffixUpperCase_CSharp11() => builder.AddPaths("LiteralSuffixUpperCase.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/LoggerMembersNamesShouldComplyTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/LoggerMembersNamesShouldComplyTest.cs index 9a8fae74aab..122ea83e0a9 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/LoggerMembersNamesShouldComplyTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/LoggerMembersNamesShouldComplyTest.cs @@ -53,7 +53,7 @@ public class Two } """) .AddReferences(NuGetMetadataReference.MicrosoftExtensionsLoggingAbstractions()) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void LoggerMembersNamesShouldComply_MicrosoftExtensionsLogging_CS() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/LoggersShouldBeNamedForEnclosingTypeTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/LoggersShouldBeNamedForEnclosingTypeTest.cs index 5f5b4dc3f97..f3da0922852 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/LoggersShouldBeNamedForEnclosingTypeTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/LoggersShouldBeNamedForEnclosingTypeTest.cs @@ -50,7 +50,7 @@ class RandomType { } """) .AddReferences(NuGetMetadataReference.MicrosoftExtensionsLoggingAbstractions()) .WithTopLevelStatements() - .Verify(); + .VerifyNoIssues(); [TestMethod] public void LoggersShouldBeNamedForEnclosingType_NLog_CS() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/LoggingTemplatePlaceHoldersShouldBeInOrderTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/LoggingTemplatePlaceHoldersShouldBeInOrderTest.cs index 0f351ca30f4..d802c12cbca 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/LoggingTemplatePlaceHoldersShouldBeInOrderTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/LoggingTemplatePlaceHoldersShouldBeInOrderTest.cs @@ -1,22 +1,22 @@ /* -* SonarAnalyzer for .NET -* Copyright (C) 2015-2024 SonarSource SA -* mailto: contact AT sonarsource DOT com -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU Lesser General Public -* License as published by the Free Software Foundation; either -* version 3 of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* Lesser General Public License for more details. -* -* You should have received a copy of the GNU Lesser General Public License -* along with this program; if not, write to the Free Software Foundation, -* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -*/ + * SonarAnalyzer for .NET + * Copyright (C) 2015-2024 SonarSource SA + * mailto: contact AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ using SonarAnalyzer.Rules.CSharp; using SonarAnalyzer.Rules.MessageTemplates; @@ -133,5 +133,5 @@ public interface ILogger { void Info(string message, params object[] args); } - """).Verify(); + """).VerifyNoIssues(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithAssemblyVersionAttributeTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithAssemblyVersionAttributeTest.cs index cacffbcf5d3..9d7d8ff7e3c 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithAssemblyVersionAttributeTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithAssemblyVersionAttributeTest.cs @@ -21,83 +21,82 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class MarkAssemblyWithAssemblyVersionAttributeTest { - [TestClass] - public class MarkAssemblyWithAssemblyVersionAttributeTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder(); - private readonly VerifierBuilder builderVB = new VerifierBuilder(); + private readonly VerifierBuilder builderCS = new VerifierBuilder(); + private readonly VerifierBuilder builderVB = new VerifierBuilder(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttribute_CS() => - builderCS.AddPaths("MarkAssemblyWithAssemblyVersionAttribute.cs").WithConcurrentAnalysis(false).Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttribute_CS() => + builderCS.AddPaths("MarkAssemblyWithAssemblyVersionAttribute.cs").WithConcurrentAnalysis(false).VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttributeRazor_CS() => - builderCS - .AddPaths("MarkAssemblyWithAssemblyVersionAttributeRazor.cs") - .WithConcurrentAnalysis(false) - .AddReferences(GetAspNetCoreRazorReferences()) - .Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttributeRazor_CS() => + builderCS + .AddPaths("MarkAssemblyWithAssemblyVersionAttributeRazor.cs") + .WithConcurrentAnalysis(false) + .AddReferences(GetAspNetCoreRazorReferences()) + .VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttribute_CS_Concurrent() => - builderCS - .AddPaths("MarkAssemblyWithAssemblyVersionAttribute.cs", "MarkAssemblyWithAssemblyVersionAttributeRazor.cs") - .AddReferences(GetAspNetCoreRazorReferences()) - .WithAutogenerateConcurrentFiles(false) - .Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttribute_CS_Concurrent() => + builderCS + .AddPaths("MarkAssemblyWithAssemblyVersionAttribute.cs", "MarkAssemblyWithAssemblyVersionAttributeRazor.cs") + .AddReferences(GetAspNetCoreRazorReferences()) + .WithAutogenerateConcurrentFiles(false) + .VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttributeNoncompliant_CS() => - builderCS.AddPaths("MarkAssemblyWithAssemblyVersionAttributeNoncompliant.cs") - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttributeNoncompliant_CS() => + builderCS.AddPaths("MarkAssemblyWithAssemblyVersionAttributeNoncompliant.cs") + .WithConcurrentAnalysis(false) + .Verify(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttributeNoncompliant_NoTargets_ShouldNotRaise_CS() => - // False positive. No assembly gets generated when Microsoft.Build.NoTargets is referenced. - builderCS.AddSnippet("// Noncompliant ^1#0 {{Provide an 'AssemblyVersion' attribute for assembly 'project0'.}}") - .AddReferences(NuGetMetadataReference.MicrosoftBuildNoTargets()) - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttributeNoncompliant_NoTargets_ShouldNotRaise_CS() => + // False positive. No assembly gets generated when Microsoft.Build.NoTargets is referenced. + builderCS.AddSnippet("// Noncompliant ^1#0 {{Provide an 'AssemblyVersion' attribute for assembly 'project0'.}}") + .AddReferences(NuGetMetadataReference.MicrosoftBuildNoTargets()) + .WithConcurrentAnalysis(false) + .Verify(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttribute_VB() => - builderVB.AddPaths("MarkAssemblyWithAssemblyVersionAttribute.vb").WithConcurrentAnalysis(false).Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttribute_VB() => + builderVB.AddPaths("MarkAssemblyWithAssemblyVersionAttribute.vb").WithConcurrentAnalysis(false).VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttributeRazor_VB() => - builderVB - .AddPaths("MarkAssemblyWithAssemblyVersionAttributeRazor.vb") - .WithConcurrentAnalysis(false) - .AddReferences(GetAspNetCoreRazorReferences()) - .Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttributeRazor_VB() => + builderVB + .AddPaths("MarkAssemblyWithAssemblyVersionAttributeRazor.vb") + .WithConcurrentAnalysis(false) + .AddReferences(GetAspNetCoreRazorReferences()) + .VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttribute_VB_Concurrent() => - builderVB - .AddPaths("MarkAssemblyWithAssemblyVersionAttribute.vb", "MarkAssemblyWithAssemblyVersionAttributeRazor.vb") - .AddReferences(GetAspNetCoreRazorReferences()) - .WithAutogenerateConcurrentFiles(false) - .Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttribute_VB_Concurrent() => + builderVB + .AddPaths("MarkAssemblyWithAssemblyVersionAttribute.vb", "MarkAssemblyWithAssemblyVersionAttributeRazor.vb") + .AddReferences(GetAspNetCoreRazorReferences()) + .WithAutogenerateConcurrentFiles(false) + .VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttributeNoncompliant_VB() => - builderVB.AddPaths("MarkAssemblyWithAssemblyVersionAttributeNoncompliant.vb") - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttributeNoncompliant_VB() => + builderVB.AddPaths("MarkAssemblyWithAssemblyVersionAttributeNoncompliant.vb") + .WithConcurrentAnalysis(false) + .Verify(); - [TestMethod] - public void MarkAssemblyWithAssemblyVersionAttributeNoncompliant_NoTargets_ShouldNotRaise_VB() => - // False positive. No assembly gets generated when Microsoft.Build.NoTargets is referenced. - builderVB.AddSnippet("' Noncompliant ^1#0 {{Provide an 'AssemblyVersion' attribute for assembly 'project0'.}}") - .AddReferences(NuGetMetadataReference.MicrosoftBuildNoTargets()) - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void MarkAssemblyWithAssemblyVersionAttributeNoncompliant_NoTargets_ShouldNotRaise_VB() => + // False positive. No assembly gets generated when Microsoft.Build.NoTargets is referenced. + builderVB.AddSnippet("' Noncompliant ^1#0 {{Provide an 'AssemblyVersion' attribute for assembly 'project0'.}}") + .AddReferences(NuGetMetadataReference.MicrosoftBuildNoTargets()) + .WithConcurrentAnalysis(false) + .Verify(); - private static IEnumerable GetAspNetCoreRazorReferences() => - NuGetMetadataReference.MicrosoftAspNetCoreMvcRazorRuntime(Constants.NuGetLatestVersion); - } + private static IEnumerable GetAspNetCoreRazorReferences() => + NuGetMetadataReference.MicrosoftAspNetCoreMvcRazorRuntime(Constants.NuGetLatestVersion); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithClsCompliantAttributeTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithClsCompliantAttributeTest.cs index 244bd3cc08e..ac5cc78dade 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithClsCompliantAttributeTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithClsCompliantAttributeTest.cs @@ -21,28 +21,27 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class MarkAssemblyWithClsCompliantAttributeTest { - [TestClass] - public class MarkAssemblyWithClsCompliantAttributeTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder().WithConcurrentAnalysis(false); - private readonly VerifierBuilder builderVB = new VerifierBuilder().WithConcurrentAnalysis(false); + private readonly VerifierBuilder builderCS = new VerifierBuilder().WithConcurrentAnalysis(false); + private readonly VerifierBuilder builderVB = new VerifierBuilder().WithConcurrentAnalysis(false); - [TestMethod] - public void MarkAssemblyWithClsCompliantAttribute_CS() => - builderCS.AddPaths(@"MarkAssemblyWithClsCompliantAttribute.cs").Verify(); + [TestMethod] + public void MarkAssemblyWithClsCompliantAttribute_CS() => + builderCS.AddPaths(@"MarkAssemblyWithClsCompliantAttribute.cs").VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithClsCompliantAttribute_VB() => - builderVB.AddPaths(@"MarkAssemblyWithClsCompliantAttribute.vb").Verify(); + [TestMethod] + public void MarkAssemblyWithClsCompliantAttribute_VB() => + builderVB.AddPaths(@"MarkAssemblyWithClsCompliantAttribute.vb").VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithClsCompliantAttributeNoncompliant_CS() => - builderCS.AddPaths(@"MarkAssemblyWithClsCompliantAttributeNoncompliant.cs").Verify(); + [TestMethod] + public void MarkAssemblyWithClsCompliantAttributeNoncompliant_CS() => + builderCS.AddPaths(@"MarkAssemblyWithClsCompliantAttributeNoncompliant.cs").Verify(); - [TestMethod] - public void MarkAssemblyWithClsCompliantAttributeNoncompliant_VB() => - builderVB.AddPaths(@"MarkAssemblyWithClsCompliantAttributeNoncompliant.vb").Verify(); - } + [TestMethod] + public void MarkAssemblyWithClsCompliantAttributeNoncompliant_VB() => + builderVB.AddPaths(@"MarkAssemblyWithClsCompliantAttributeNoncompliant.vb").Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithComVisibleAttributeTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithComVisibleAttributeTest.cs index b03ac22db68..7f16bd0c8ef 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithComVisibleAttributeTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithComVisibleAttributeTest.cs @@ -21,28 +21,27 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class MarkAssemblyWithComVisibleAttributeTest { - [TestClass] - public class MarkAssemblyWithComVisibleAttributeTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder().WithConcurrentAnalysis(false); - private readonly VerifierBuilder builderVB = new VerifierBuilder().WithConcurrentAnalysis(false); + private readonly VerifierBuilder builderCS = new VerifierBuilder().WithConcurrentAnalysis(false); + private readonly VerifierBuilder builderVB = new VerifierBuilder().WithConcurrentAnalysis(false); - [TestMethod] - public void MarkAssemblyWithComVisibleAttribute_CS() => - builderCS.AddPaths(@"MarkAssemblyWithComVisibleAttribute.cs").Verify(); + [TestMethod] + public void MarkAssemblyWithComVisibleAttribute_CS() => + builderCS.AddPaths(@"MarkAssemblyWithComVisibleAttribute.cs").VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithComVisibleAttribute_VB() => - builderVB.AddPaths(@"MarkAssemblyWithComVisibleAttribute.vb").Verify(); + [TestMethod] + public void MarkAssemblyWithComVisibleAttribute_VB() => + builderVB.AddPaths(@"MarkAssemblyWithComVisibleAttribute.vb").VerifyNoIssues(); - [TestMethod] - public void MarkAssemblyWithComVisibleAttributeNoncompliant_CS() => - builderCS.AddPaths(@"MarkAssemblyWithComVisibleAttributeNoncompliant.cs").Verify(); + [TestMethod] + public void MarkAssemblyWithComVisibleAttributeNoncompliant_CS() => + builderCS.AddPaths(@"MarkAssemblyWithComVisibleAttributeNoncompliant.cs").Verify(); - [TestMethod] - public void MarkAssemblyWithComVisibleAttributeNoncompliant_VB() => - builderVB.AddPaths(@"MarkAssemblyWithComVisibleAttributeNoncompliant.vb").Verify(); - } + [TestMethod] + public void MarkAssemblyWithComVisibleAttributeNoncompliant_VB() => + builderVB.AddPaths(@"MarkAssemblyWithComVisibleAttributeNoncompliant.vb").Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithNeutralResourcesLanguageAttributeTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithNeutralResourcesLanguageAttributeTest.cs index 3c7242ed52c..6fd46049fc4 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithNeutralResourcesLanguageAttributeTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkAssemblyWithNeutralResourcesLanguageAttributeTest.cs @@ -29,11 +29,11 @@ public class MarkAssemblyWithNeutralResourcesLanguageAttributeTest [TestMethod] public void MarkAssemblyWithNeutralResourcesLanguageAttribute_HasResx_HasAttribute_Compliant() => - builder.AddPaths("MarkAssemblyWithNeutralResourcesLanguageAttribute.cs", @"Resources\SomeResources.Designer.cs", @"Resources\AnotherResources.Designer.cs").Verify(); + builder.AddPaths("MarkAssemblyWithNeutralResourcesLanguageAttribute.cs", @"Resources\SomeResources.Designer.cs", @"Resources\AnotherResources.Designer.cs").VerifyNoIssues(); [TestMethod] public void MarkAssemblyWithNeutralResourcesLanguageAttribute_NoResx_HasAttribute_Compliant() => - builder.AddPaths("MarkAssemblyWithNeutralResourcesLanguageAttribute.cs").Verify(); + builder.AddPaths("MarkAssemblyWithNeutralResourcesLanguageAttribute.cs").VerifyNoIssues(); [TestMethod] public void MarkAssemblyWithNeutralResourcesLanguageAttribute_HasResx_HasInvalidAttribute_Noncompliant() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkWindowsFormsMainWithStaThreadTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkWindowsFormsMainWithStaThreadTest.cs index 6d5f7e7c310..1050c4d4c46 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MarkWindowsFormsMainWithStaThreadTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MarkWindowsFormsMainWithStaThreadTest.cs @@ -73,8 +73,7 @@ public class MarkWindowsFormsMainWithStaThreadTest public void MarkWindowsFormsMainWithStaThread_VB_NoWindowsForms() => builderVB .AddPaths("MarkWindowsFormsMainWithStaThread_NoWindowsForms.vb") - .WithErrorBehavior(CompilationErrorBehavior.Ignore) .WithOutputKind(OutputKind.WindowsApplication) - .Verify(); + .VerifyNoIssuesIgnoreErrors(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MemberInitializedToDefaultTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MemberInitializedToDefaultTest.cs index 45dc9970437..7975c9b9937 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MemberInitializedToDefaultTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MemberInitializedToDefaultTest.cs @@ -20,53 +20,52 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class MemberInitializedToDefaultTest { - [TestClass] - public class MemberInitializedToDefaultTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void MemberInitializedToDefault() => - builder.AddPaths("MemberInitializedToDefault.cs").Verify(); + [TestMethod] + public void MemberInitializedToDefault() => + builder.AddPaths("MemberInitializedToDefault.cs").Verify(); - [TestMethod] - public void MemberInitializedToDefault_CodeFix() => - builder - .WithCodeFix() - .AddPaths("MemberInitializedToDefault.cs") - .WithCodeFixedPaths("MemberInitializedToDefault.Fixed.cs") - .VerifyCodeFix(); + [TestMethod] + public void MemberInitializedToDefault_CodeFix() => + builder + .WithCodeFix() + .AddPaths("MemberInitializedToDefault.cs") + .WithCodeFixedPaths("MemberInitializedToDefault.Fixed.cs") + .VerifyCodeFix(); #if NET - [TestMethod] - public void MemberInitializedToDefault_CSharp8() => - builder.AddPaths("MemberInitializedToDefault.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + [TestMethod] + public void MemberInitializedToDefault_CSharp8() => + builder.AddPaths("MemberInitializedToDefault.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).VerifyNoIssues(); - [TestMethod] - public void MemberInitializedToDefault_CSharp9() => - builder.AddPaths("MemberInitializedToDefault.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + [TestMethod] + public void MemberInitializedToDefault_CSharp9() => + builder.AddPaths("MemberInitializedToDefault.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); - [TestMethod] - public void MemberInitializedToDefault_CSharp10() => - builder.AddPaths("MemberInitializedToDefault.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void MemberInitializedToDefault_CSharp10() => + builder.AddPaths("MemberInitializedToDefault.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); - [TestMethod] - public void MemberInitializedToDefault_CSharp11() => - builder.AddPaths("MemberInitializedToDefault.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void MemberInitializedToDefault_CSharp11() => + builder.AddPaths("MemberInitializedToDefault.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); - [TestMethod] - public void MemberInitializedToDefault_CSharp11_CodeFix() => - builder - .WithCodeFix() - .AddPaths("MemberInitializedToDefault.CSharp11.cs") - .WithCodeFixedPaths("MemberInitializedToDefault.CSharp11.Fixed.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .VerifyCodeFix(); + [TestMethod] + public void MemberInitializedToDefault_CSharp11_CodeFix() => + builder + .WithCodeFix() + .AddPaths("MemberInitializedToDefault.CSharp11.cs") + .WithCodeFixedPaths("MemberInitializedToDefault.CSharp11.Fixed.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .VerifyCodeFix(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MemberOverrideCallsBaseMemberTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MemberOverrideCallsBaseMemberTest.cs index 4901e5a8f65..649d6c7fe04 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MemberOverrideCallsBaseMemberTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MemberOverrideCallsBaseMemberTest.cs @@ -67,7 +67,12 @@ class Test {{ {toString} }} - ").Verify(); + ") +#if NET + .Verify(); +#elif NETFRAMEWORK + .VerifyNoIssues(); +#endif } } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MemberShouldBeStaticTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MemberShouldBeStaticTest.cs index d0d8c52771b..3a96402cef8 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MemberShouldBeStaticTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MemberShouldBeStaticTest.cs @@ -20,73 +20,74 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class MemberShouldBeStaticTest { - [TestClass] - public class MemberShouldBeStaticTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [DataTestMethod] - [DataRow("1.0.0", "3.0.20105.1")] - [DataRow(Constants.NuGetLatestVersion, Constants.NuGetLatestVersion)] - public void MemberShouldBeStatic(string aspnetCoreVersion, string aspnetVersion) => - builder.AddPaths("MemberShouldBeStatic.cs") - .AddReferences(NuGetMetadataReference.MicrosoftAspNetCoreMvcWebApiCompatShim(aspnetCoreVersion) - .Concat(NuGetMetadataReference.MicrosoftAspNetMvc(aspnetVersion)) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreMvcCore(aspnetCoreVersion)) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreMvcViewFeatures(aspnetCoreVersion)) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreRoutingAbstractions(aspnetCoreVersion))) - .Verify(); + [DataTestMethod] + [DataRow("1.0.0", "3.0.20105.1")] + [DataRow(Constants.NuGetLatestVersion, Constants.NuGetLatestVersion)] + public void MemberShouldBeStatic(string aspnetCoreVersion, string aspnetVersion) => + builder.AddPaths("MemberShouldBeStatic.cs") + .AddReferences(NuGetMetadataReference.MicrosoftAspNetCoreMvcWebApiCompatShim(aspnetCoreVersion) + .Concat(NuGetMetadataReference.MicrosoftAspNetMvc(aspnetVersion)) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreMvcCore(aspnetCoreVersion)) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreMvcViewFeatures(aspnetCoreVersion)) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreRoutingAbstractions(aspnetCoreVersion))) + .Verify(); - [TestMethod] - public void MemberShouldBeStatic_WinForms() => - builder.AddPaths("MemberShouldBeStatic.WinForms.cs") - .AddReferences(MetadataReferenceFacade.SystemWindowsForms) - .Verify(); + [TestMethod] + public void MemberShouldBeStatic_WinForms() => + builder.AddPaths("MemberShouldBeStatic.WinForms.cs") + .AddReferences(MetadataReferenceFacade.SystemWindowsForms) + .Verify(); #if NET - [TestMethod] - public void MemberShouldBeStatic_CSharp9() => - builder.AddPaths("MemberShouldBeStatic.CSharp9.cs").WithTopLevelStatements().Verify(); + [TestMethod] + public void MemberShouldBeStatic_CSharp9() => + builder.AddPaths("MemberShouldBeStatic.CSharp9.cs").WithTopLevelStatements().Verify(); - [TestMethod] - public void MemberShouldBeStatic_CSharp12() => - builder.AddPaths("MemberShouldBeStatic.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + [TestMethod] + public void MemberShouldBeStatic_CSharp12() => + builder.AddPaths("MemberShouldBeStatic.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); #endif - [TestMethod] - public void MemberShouldBeStatic_CSharp8() => - builder.AddPaths("MemberShouldBeStatic.CSharp8.cs") - .WithOptions(ParseOptionsHelper.FromCSharp8) - .AddReferences(MetadataReferenceFacade.NetStandard21) - .Verify(); + [TestMethod] + public void MemberShouldBeStatic_CSharp8() => + builder.AddPaths("MemberShouldBeStatic.CSharp8.cs") + .WithOptions(ParseOptionsHelper.FromCSharp8) + .AddReferences(MetadataReferenceFacade.NetStandard21) + .Verify(); #if NETFRAMEWORK // HttpApplication is available only on .Net Framework - [TestMethod] - public void MemberShouldBeStatic_HttpApplication() => - builder.AddSnippet(@" + [TestMethod] + public void MemberShouldBeStatic_HttpApplication() => + builder.AddSnippet(@" public class HttpApplication1 : System.Web.HttpApplication { - public int Foo() => 0; +public int Foo() => 0; - protected int FooFoo() => 0; // Noncompliant +protected int FooFoo() => 0; // Noncompliant }").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); #endif - [TestMethod] - public void MemberShouldBeStatic_InvalidCode() => + [TestMethod] + public void MemberShouldBeStatic_InvalidCode() => // Handle invalid code causing NullReferenceException: https://github.com/SonarSource/sonar-dotnet/issues/819 - builder.AddSnippet(@" -public class Class7 -{ - public async Task Function(Func>> f) - { - Result result; - result = await f(); - return result; - } -}").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); - } + builder.AddSnippet(""" + + public class Class7 + { + public async Task Function(Func>> f) + { + Result result; + result = await f(); + return result; + } + } + """).VerifyNoIssuesIgnoreErrors(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodOverrideNoParamsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodOverrideNoParamsTest.cs index 28185b50d4e..99188c5f7b1 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodOverrideNoParamsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodOverrideNoParamsTest.cs @@ -39,7 +39,7 @@ public class MethodOverrideNoParamsTest [TestMethod] public void MethodOverrideNoParams_CSharp11() => - builder.AddPaths("MethodOverrideNoParams.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + builder.AddPaths("MethodOverrideNoParams.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodShouldBeNamedAccordingToSynchronicityTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodShouldBeNamedAccordingToSynchronicityTest.cs index c484308ccd6..78a6ad93d32 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodShouldBeNamedAccordingToSynchronicityTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodShouldBeNamedAccordingToSynchronicityTest.cs @@ -20,70 +20,69 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class MethodShouldBeNamedAccordingToSynchronicityTest { - [TestClass] - public class MethodShouldBeNamedAccordingToSynchronicityTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - [DataRow("4.0.0")] - [DataRow(Constants.NuGetLatestVersion)] - public void MethodShouldBeNamedAccordingToSynchronicity(string tasksVersion) => - builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.cs") - .AddReferences(MetadataReferenceFacade.SystemThreadingTasksExtensions(tasksVersion) - .Union(NuGetMetadataReference.MicrosoftAspNetSignalRCore()) - .Union(MetadataReferenceFacade.SystemComponentModelPrimitives)) - .Verify(); + [TestMethod] + [DataRow("4.0.0")] + [DataRow(Constants.NuGetLatestVersion)] + public void MethodShouldBeNamedAccordingToSynchronicity(string tasksVersion) => + builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.cs") + .AddReferences(MetadataReferenceFacade.SystemThreadingTasksExtensions(tasksVersion) + .Union(NuGetMetadataReference.MicrosoftAspNetSignalRCore()) + .Union(MetadataReferenceFacade.SystemComponentModelPrimitives)) + .Verify(); - [TestMethod] - [DataRow("3.0.20105.1")] - [DataRow(Constants.NuGetLatestVersion)] - public void MethodShouldBeNamedAccordingToSynchronicity_MVC(string mvcVersion) => - builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.MVC.cs").AddReferences(NuGetMetadataReference.MicrosoftAspNetMvc(mvcVersion)).Verify(); + [TestMethod] + [DataRow("3.0.20105.1")] + [DataRow(Constants.NuGetLatestVersion)] + public void MethodShouldBeNamedAccordingToSynchronicity_MVC(string mvcVersion) => + builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.MVC.cs").AddReferences(NuGetMetadataReference.MicrosoftAspNetMvc(mvcVersion)).VerifyNoIssues(); - [TestMethod] - [DataRow("2.0.4", "2.0.3")] - [DataRow(Constants.NuGetLatestVersion, Constants.NuGetLatestVersion)] - public void MethodShouldBeNamedAccordingToSynchronicity_MVC_Core(string aspNetCoreMvcVersion, string aspNetCoreRoutingVersion) => - builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.MVC.Core.cs") - .AddReferences(NuGetMetadataReference.MicrosoftAspNetCoreMvcCore(aspNetCoreMvcVersion) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreMvcViewFeatures(aspNetCoreMvcVersion)) - .Concat(NuGetMetadataReference.MicrosoftAspNetCoreRoutingAbstractions(aspNetCoreRoutingVersion))) - .Verify(); + [TestMethod] + [DataRow("2.0.4", "2.0.3")] + [DataRow(Constants.NuGetLatestVersion, Constants.NuGetLatestVersion)] + public void MethodShouldBeNamedAccordingToSynchronicity_MVC_Core(string aspNetCoreMvcVersion, string aspNetCoreRoutingVersion) => + builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.MVC.Core.cs") + .AddReferences(NuGetMetadataReference.MicrosoftAspNetCoreMvcCore(aspNetCoreMvcVersion) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreMvcViewFeatures(aspNetCoreMvcVersion)) + .Concat(NuGetMetadataReference.MicrosoftAspNetCoreRoutingAbstractions(aspNetCoreRoutingVersion))) + .Verify(); - [DataTestMethod] - [DataRow("1.1.11")] - [DataRow(Constants.NuGetLatestVersion)] - public void MethodShouldBeNamedAccordingToSynchronicity_MsTest(string testFwkVersion) => - builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.MsTest.cs").AddReferences(NuGetMetadataReference.MSTestTestFramework(testFwkVersion)).Verify(); + [DataTestMethod] + [DataRow("1.1.11")] + [DataRow(Constants.NuGetLatestVersion)] + public void MethodShouldBeNamedAccordingToSynchronicity_MsTest(string testFwkVersion) => + builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.MsTest.cs").AddReferences(NuGetMetadataReference.MSTestTestFramework(testFwkVersion)).VerifyNoIssues(); - [DataTestMethod] - [DataRow("2.5.7.10213")] - [DataRow(Constants.NuGetLatestVersion)] - public void MethodShouldBeNamedAccordingToSynchronicity_NUnit(string testFwkVersion) => - builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.NUnit.cs").AddReferences(NuGetMetadataReference.NUnit(testFwkVersion)).Verify(); + [DataTestMethod] + [DataRow("2.5.7.10213")] + [DataRow(Constants.NuGetLatestVersion)] + public void MethodShouldBeNamedAccordingToSynchronicity_NUnit(string testFwkVersion) => + builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.NUnit.cs").AddReferences(NuGetMetadataReference.NUnit(testFwkVersion)).VerifyNoIssues(); - [DataTestMethod] - [DataRow("2.0.0")] - [DataRow(Constants.NuGetLatestVersion)] - public void MethodShouldBeNamedAccordingToSynchronicity_Xunit(string testFwkVersion) => - builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.Xunit.cs").AddReferences(NuGetMetadataReference.XunitFramework(testFwkVersion)).Verify(); + [DataTestMethod] + [DataRow("2.0.0")] + [DataRow(Constants.NuGetLatestVersion)] + public void MethodShouldBeNamedAccordingToSynchronicity_Xunit(string testFwkVersion) => + builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.Xunit.cs").AddReferences(NuGetMetadataReference.XunitFramework(testFwkVersion)).VerifyNoIssues(); - [TestMethod] - public void MethodShouldBeNamedAccordingToSynchronicity_CSharp8() => - builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).AddReferences(MetadataReferenceFacade.NetStandard21).Verify(); + [TestMethod] + public void MethodShouldBeNamedAccordingToSynchronicity_CSharp8() => + builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).AddReferences(MetadataReferenceFacade.NetStandard21).Verify(); #if NET - [TestMethod] - public void MethodShouldBeNamedAccordingToSynchronicity_CSharp11() => - builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .AddReferences(NuGetMetadataReference.MicrosoftAspNetSignalRCore()) - .Verify(); + [TestMethod] + public void MethodShouldBeNamedAccordingToSynchronicity_CSharp11() => + builder.AddPaths("MethodShouldBeNamedAccordingToSynchronicity.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .AddReferences(NuGetMetadataReference.MicrosoftAspNetSignalRCore()) + .Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodShouldNotOnlyReturnConstantTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodShouldNotOnlyReturnConstantTest.cs index 190db33da42..158e823a342 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodShouldNotOnlyReturnConstantTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodShouldNotOnlyReturnConstantTest.cs @@ -20,28 +20,27 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class MethodShouldNotOnlyReturnConstantTest { - [TestClass] - public class MethodShouldNotOnlyReturnConstantTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void MethodShouldNotOnlyReturnConstant() => - builder.AddPaths("MethodShouldNotOnlyReturnConstant.cs").Verify(); + [TestMethod] + public void MethodShouldNotOnlyReturnConstant() => + builder.AddPaths("MethodShouldNotOnlyReturnConstant.cs").Verify(); #if NET - [TestMethod] - public void MethodShouldNotOnlyReturnConstant_CSharp8() => - builder.AddPaths("MethodShouldNotOnlyReturnConstant.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + [TestMethod] + public void MethodShouldNotOnlyReturnConstant_CSharp8() => + builder.AddPaths("MethodShouldNotOnlyReturnConstant.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).VerifyNoIssues(); - [TestMethod] - public void MethodShouldNotOnlyReturnConstant_CSharp11() => - builder.AddPaths("MethodShouldNotOnlyReturnConstant.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void MethodShouldNotOnlyReturnConstant_CSharp11() => + builder.AddPaths("MethodShouldNotOnlyReturnConstant.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodsShouldNotHaveTooManyLinesTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodsShouldNotHaveTooManyLinesTest.cs index db5ec6b45a6..1b75c43e7ec 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodsShouldNotHaveTooManyLinesTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodsShouldNotHaveTooManyLinesTest.cs @@ -69,14 +69,16 @@ public class MethodsShouldNotHaveTooManyLinesTest [TestMethod] public void MethodsShouldNotHaveTooManyLines_CSharp9_Valid() => - CreateCSBuilder(4).AddSnippet(@" -int i = 1; i++; -i++; -i++; -i++;") - .WithOptions(ParseOptionsHelper.FromCSharp9) - .WithOutputKind(OutputKind.ConsoleApplication) - .Verify(); + CreateCSBuilder(4) + .AddSnippet(""" + int i = 1; i++; + i++; + i++; + i++; + """) + .WithOptions(ParseOptionsHelper.FromCSharp9) + .WithOutputKind(OutputKind.ConsoleApplication) + .VerifyNoIssues(); #endif [TestMethod] @@ -87,16 +89,17 @@ public class MethodsShouldNotHaveTooManyLinesTest [TestMethod] public void MethodsShouldNotHaveTooManyLines_InvalidSyntax_CS() => - CreateCSBuilder(2).AddSnippet(@" -public class Foo -{ - public string () - { - return ""f""; - } -}") - .WithErrorBehavior(CompilationErrorBehavior.Ignore) - .Verify(); + CreateCSBuilder(2) + .AddSnippet(""" + public class Foo + { + public string () + { + return "f"; + } + } + """) + .VerifyNoIssuesIgnoreErrors(); [DataTestMethod] [DataRow(1)] diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodsShouldUseBaseTypesTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodsShouldUseBaseTypesTest.cs index 83b921523ae..f2c1f111551 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/MethodsShouldUseBaseTypesTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/MethodsShouldUseBaseTypesTest.cs @@ -85,24 +85,25 @@ public void MethodOne(Foo foo) [TestMethod] public void MethodsShouldUseBaseTypes_InvalidCode() => - builder.AddSnippet(@" -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; + builder.AddSnippet(""" + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; -public class Foo -{ - private void FooBar(IList , IList) - { - a.ToList(); - } + public class Foo + { + private void FooBar(IList , IList) + { + a.ToList(); + } - // New test case - code doesn't compile but was making analyzer crash - private void Foo(IList a, IList a) - { - a.ToList(); - } -}").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); + // New test case - code doesn't compile but was making analyzer crash + private void Foo(IList a, IList a) + { + a.ToList(); + } + } + """).VerifyNoIssuesIgnoreErrors(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/NativeMethodsShouldBeWrappedTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/NativeMethodsShouldBeWrappedTest.cs index c89cea111cb..b4b744df6e2 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/NativeMethodsShouldBeWrappedTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/NativeMethodsShouldBeWrappedTest.cs @@ -21,64 +21,59 @@ using Microsoft.CodeAnalysis.CSharp; using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class NativeMethodsShouldBeWrappedTest { - [TestClass] - public class NativeMethodsShouldBeWrappedTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void NativeMethodsShouldBeWrapped() => - builder.AddPaths("NativeMethodsShouldBeWrapped.cs").Verify(); + [TestMethod] + public void NativeMethodsShouldBeWrapped() => + builder.AddPaths("NativeMethodsShouldBeWrapped.cs").Verify(); #if NET - [TestMethod] - public void NativeMethodsShouldBeWrapped_CSharp9() => - builder.AddPaths("NativeMethodsShouldBeWrapped.CSharp9.cs").WithTopLevelStatements().Verify(); - - [TestMethod] - public void NativeMethodsShouldBeWrapped_CSharp10() => - builder.AddPaths("NativeMethodsShouldBeWrapped.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void NativeMethodsShouldBeWrapped_CSharp9() => + builder.AddPaths("NativeMethodsShouldBeWrapped.CSharp9.cs").WithTopLevelStatements().Verify(); - // NativeMethodsShouldBeWrapped.CSharp11.SourceGenerator.cs contains the code as generated by the SourceGenerator. To regenerate it: - // * Take the code from NativeMethodsShouldBeWrapped.CSharp11.cs - // * Copy it to a new .Net 7 project - // * Press F12 on any of the partial methods - // * Copy the result to NativeMethodsShouldBeWrapped.CSharp11.SourceGenerator.cs - [TestMethod] - public void NativeMethodsShouldBeWrapped_CSharp11() => - builder - .AddPaths("NativeMethodsShouldBeWrapped.CSharp11.cs") - .AddPaths("NativeMethodsShouldBeWrapped.CSharp11.SourceGenerator.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .WithConcurrentAnalysis(false) - .Verify(); + // NativeMethodsShouldBeWrapped.CSharp11.SourceGenerator.cs contains the code as generated by the SourceGenerator. To regenerate it: + // * Take the code from NativeMethodsShouldBeWrapped.CSharp11.cs + // * Copy it to a new .Net 7 project + // * Press F12 on any of the partial methods + // * Copy the result to NativeMethodsShouldBeWrapped.CSharp11.SourceGenerator.cs + [TestMethod] + public void NativeMethodsShouldBeWrapped_CSharp11() => + builder + .AddPaths("NativeMethodsShouldBeWrapped.CSharp11.cs") + .AddPaths("NativeMethodsShouldBeWrapped.CSharp11.SourceGenerator.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .WithConcurrentAnalysis(false) + .Verify(); #endif - [TestMethod] - public void NativeMethodsShouldBeWrapped_InvalidCode() => - builder.AddSnippet(""" - public class InvalidSyntax + [TestMethod] + public void NativeMethodsShouldBeWrapped_InvalidCode() => + builder.AddSnippet(""" + public class InvalidSyntax + { + extern public void Extern1 // Error [CS0670, CS0106, CS1002] + extern public void Extern2; // Error [CS0670, CS0106] + extern private void Extern3(int x); + public void Wrapper // Error [CS0547, CS0548] + { + Extern3(x); // Error [CS1014, CS1513, CS8124, CS1519] + } + public void Wrapper( // Error [CS0106, CS8107, CS8803, CS8805, CS8112, CS1001] + { + Extern3(x); // Error [CS0246, CS1003, CS0246, CS8124, CS1001, CS1026, CS1001] + } // Error [CS1022] + public void Wrapper() // Error [CS0106, CS0128] { - extern public void Extern1 // Error [CS0670, CS0106, CS1002] - extern public void Extern2; // Error [CS0670, CS0106] - extern private void Extern3(int x); - public void Wrapper // Error [CS0547, CS0548] - { - Extern3(x); // Error [CS1014, CS1513, CS8124, CS1519] - } - public void Wrapper( // Error [CS0106, CS8107, CS8803, CS8805, CS8112, CS1001] - { - Extern3(x); // Error [CS0246, CS1003, CS0246, CS8124, CS1001, CS1026, CS1001] - } // Error [CS1022] - public void Wrapper() // Error [CS0106, CS0128] - { - Extern3(x); // Error [CS0103, CS0103] - } - } // Error [CS1022] - """).WithLanguageVersion(LanguageVersion.CSharp7).Verify(); - } + Extern3(x); // Error [CS0103, CS0103] + } + } // Error [CS1022] + """).WithLanguageVersion(LanguageVersion.CSharp7).Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/OperatorsShouldBeOverloadedConsistentlyTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/OperatorsShouldBeOverloadedConsistentlyTest.cs index 32a1b42bcb4..a3785aa9b33 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/OperatorsShouldBeOverloadedConsistentlyTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/OperatorsShouldBeOverloadedConsistentlyTest.cs @@ -20,28 +20,27 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class OperatorsShouldBeOverloadedConsistentlyTest { - [TestClass] - public class OperatorsShouldBeOverloadedConsistentlyTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void OperatorsShouldBeOverloadedConsistently() => - builder.AddPaths("OperatorsShouldBeOverloadedConsistently.cs").Verify(); + [TestMethod] + public void OperatorsShouldBeOverloadedConsistently() => + builder.AddPaths("OperatorsShouldBeOverloadedConsistently.cs").Verify(); #if NET - [TestMethod] - public void OperatorsShouldBeOverloadedConsistently_CSharp9() => - builder.AddPaths("OperatorsShouldBeOverloadedConsistently.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + [TestMethod] + public void OperatorsShouldBeOverloadedConsistently_CSharp9() => + builder.AddPaths("OperatorsShouldBeOverloadedConsistently.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).VerifyNoIssues(); - [TestMethod] - public void OperatorsShouldBeOverloadedConsistently_CSharp11() => - builder.AddPaths("OperatorsShouldBeOverloadedConsistently.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void OperatorsShouldBeOverloadedConsistently_CSharp11() => + builder.AddPaths("OperatorsShouldBeOverloadedConsistently.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/OptionExplicitOnTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/OptionExplicitOnTest.cs index 6997b67035b..f17cc250575 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/OptionExplicitOnTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/OptionExplicitOnTest.cs @@ -20,47 +20,45 @@ using Microsoft.CodeAnalysis.VisualBasic; using SonarAnalyzer.Rules.VisualBasic; -using SonarAnalyzer.Test.Helpers; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class OptionExplicitOnTest { - [TestClass] - public class OptionExplicitOnTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void OptionExplicitOn_IsOffForProject() - { - var project = SolutionBuilder.Create().AddProject(AnalyzerLanguage.VisualBasic).AddSnippet("' Noncompliant ^1#0 {{Configure 'Option Explicit On' for assembly 'project0'.}}"); - var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionExplicit: false); // optionExplicit is true by default => tested in other tests - var compilation = project.GetCompilation(null, options); - DiagnosticVerifier.Verify(compilation, new OptionExplicitOn()); - } + [TestMethod] + public void OptionExplicitOn_IsOffForProject() + { + var project = SolutionBuilder.Create().AddProject(AnalyzerLanguage.VisualBasic).AddSnippet("' Noncompliant ^1#0 {{Configure 'Option Explicit On' for assembly 'project0'.}}"); + var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionExplicit: false); // optionExplicit is true by default => tested in other tests + var compilation = project.GetCompilation(null, options); + DiagnosticVerifier.Verify(compilation, new OptionExplicitOn()); + } - [TestMethod] - public void OptionExplicitOn_IsOff() => - builder.AddSnippet("Option Explicit Off ' Noncompliant ^1#19 {{Change this to 'Option Explicit On'.}}").Verify(); + [TestMethod] + public void OptionExplicitOn_IsOff() => + builder.AddSnippet("Option Explicit Off ' Noncompliant ^1#19 {{Change this to 'Option Explicit On'.}}").Verify(); - [TestMethod] - public void OptionExplicitOn_IsOn() => - builder.AddSnippet("Option Explicit On").Verify(); + [TestMethod] + public void OptionExplicitOn_IsOn() => + builder.AddSnippet("Option Explicit On").VerifyNoIssues(); - [TestMethod] - public void OptionExplicitOn_IsMissing() => - builder.AddSnippet("Option Strict Off").Verify(); + [TestMethod] + public void OptionExplicitOn_IsMissing() => + builder.AddSnippet("Option Strict Off").VerifyNoIssues(); - [TestMethod] - public void OptionExplicitOn_Concurrent() - { - using var scope = new EnvironmentVariableScope { EnableConcurrentAnalysis = true}; - var project = SolutionBuilder.Create() - .AddProject(AnalyzerLanguage.VisualBasic) - .AddSnippet("' Noncompliant ^1#0 {{Configure 'Option Explicit On' for assembly 'project0'.}}") - .AddSnippet("Option Explicit Off ' Noncompliant ^1#19 {{Change this to 'Option Explicit On'.}}"); - var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionExplicit: false); // optionExplicit is true by default => tested in other tests - var compilation = project.GetCompilation(null, options); - DiagnosticVerifier.Verify(compilation, new OptionExplicitOn()); - } + [TestMethod] + public void OptionExplicitOn_Concurrent() + { + using var scope = new EnvironmentVariableScope { EnableConcurrentAnalysis = true}; + var project = SolutionBuilder.Create() + .AddProject(AnalyzerLanguage.VisualBasic) + .AddSnippet("' Noncompliant ^1#0 {{Configure 'Option Explicit On' for assembly 'project0'.}}") + .AddSnippet("Option Explicit Off ' Noncompliant ^1#19 {{Change this to 'Option Explicit On'.}}"); + var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionExplicit: false); // optionExplicit is true by default => tested in other tests + var compilation = project.GetCompilation(null, options); + DiagnosticVerifier.Verify(compilation, new OptionExplicitOn()); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/OptionalParameterTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/OptionalParameterTest.cs index 298a58905d4..0812df933be 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/OptionalParameterTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/OptionalParameterTest.cs @@ -21,33 +21,32 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class OptionalParameterTest { - [TestClass] - public class OptionalParameterTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder(); - private readonly VerifierBuilder builderVB = new VerifierBuilder(); + private readonly VerifierBuilder builderCS = new VerifierBuilder(); + private readonly VerifierBuilder builderVB = new VerifierBuilder(); - [TestMethod] - public void OptionalParameter_CS() => - builderCS.AddPaths("OptionalParameter.cs").Verify(); + [TestMethod] + public void OptionalParameter_CS() => + builderCS.AddPaths("OptionalParameter.cs").Verify(); - [TestMethod] - public void OptionalParameter_VB() => - builderVB.AddPaths("OptionalParameter.vb").Verify(); + [TestMethod] + public void OptionalParameter_VB() => + builderVB.AddPaths("OptionalParameter.vb").Verify(); #if NET - [TestMethod] - public void OptionalParameter_CSharp10() => - builderCS.AddPaths("OptionalParameter.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void OptionalParameter_CSharp10() => + builderCS.AddPaths("OptionalParameter.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).VerifyNoIssues(); - [TestMethod] - public void OptionalParameter_CSharp11() => - builderCS.AddPaths("OptionalParameter.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void OptionalParameter_CSharp11() => + builderCS.AddPaths("OptionalParameter.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/OverrideGetHashCodeOnOverridingEqualsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/OverrideGetHashCodeOnOverridingEqualsTest.cs index a6135a1f9e7..c5517d34cff 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/OverrideGetHashCodeOnOverridingEqualsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/OverrideGetHashCodeOnOverridingEqualsTest.cs @@ -20,24 +20,23 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class OverrideGetHashCodeOnOverridingEqualsTest { - [TestClass] - public class OverrideGetHashCodeOnOverridingEqualsTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void OverrideGetHashCodeOnOverridingEquals() => - builder.AddPaths("OverrideGetHashCodeOnOverridingEquals.cs").Verify(); + [TestMethod] + public void OverrideGetHashCodeOnOverridingEquals() => + builder.AddPaths("OverrideGetHashCodeOnOverridingEquals.cs").Verify(); #if NET - [TestMethod] - public void OverrideGetHashCodeOnOverridingEquals_CSharp9() => - builder.AddPaths("OverrideGetHashCodeOnOverridingEquals.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + [TestMethod] + public void OverrideGetHashCodeOnOverridingEquals_CSharp9() => + builder.AddPaths("OverrideGetHashCodeOnOverridingEquals.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ParametersCorrectOrderTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ParametersCorrectOrderTest.cs index 1f9b583219c..fe5b66b02ba 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ParametersCorrectOrderTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ParametersCorrectOrderTest.cs @@ -21,55 +21,56 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class ParametersCorrectOrderTest { - [TestClass] - public class ParametersCorrectOrderTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder(); - private readonly VerifierBuilder builderVB = new VerifierBuilder(); + private readonly VerifierBuilder builderCS = new VerifierBuilder(); + private readonly VerifierBuilder builderVB = new VerifierBuilder(); - [TestMethod] - public void ParametersCorrectOrder_CSharp8() => - builderCS.AddPaths("ParametersCorrectOrder.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + [TestMethod] + public void ParametersCorrectOrder_CSharp8() => + builderCS.AddPaths("ParametersCorrectOrder.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); #if NET - [TestMethod] - public void ParametersCorrectOrder_CSharp11() => - builderCS.AddPaths("ParametersCorrectOrder.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void ParametersCorrectOrder_CSharp11() => + builderCS.AddPaths("ParametersCorrectOrder.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); - [TestMethod] - public void ParametersCorrectOrder_CSharp12() => - builderCS.AddPaths("ParametersCorrectOrder.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + [TestMethod] + public void ParametersCorrectOrder_CSharp12() => + builderCS.AddPaths("ParametersCorrectOrder.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); #endif - [TestMethod] - public void ParametersCorrectOrder_InvalidCode_CS() => - builderCS.AddSnippet(@" -public class Foo -{ - public void Bar() - { - new Foo - new () - new System. () - } -}").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); + [TestMethod] + public void ParametersCorrectOrder_InvalidCode_CS() => + builderCS.AddSnippet(""" + public class Foo + { + public void Bar() + { + new Foo + new () + new System. () + } + } + """).VerifyNoIssuesIgnoreErrors(); - [TestMethod] - public void ParametersCorrectOrder_VB() => - builderVB.AddPaths("ParametersCorrectOrder.vb").Verify(); + [TestMethod] + public void ParametersCorrectOrder_VB() => + builderVB.AddPaths("ParametersCorrectOrder.vb").Verify(); - [TestMethod] - public void ParametersCorrectOrder_InvalidCode_VB() => - builderVB.AddSnippet(@" -Public Class Foo - Public Sub Bar() - Dim x = New () - Dim y = New System. () - End Sub -End Class").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); - } + [TestMethod] + public void ParametersCorrectOrder_InvalidCode_VB() => + builderVB.AddSnippet(""" + Public Class Foo + Public Sub Bar() + Dim x = New () + Dim y = New System. () + End Sub + End Class + """).VerifyNoIssuesIgnoreErrors(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/PropertiesAccessCorrectFieldTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/PropertiesAccessCorrectFieldTest.cs index 196529270c8..7a910bc8517 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/PropertiesAccessCorrectFieldTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/PropertiesAccessCorrectFieldTest.cs @@ -21,51 +21,50 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class PropertiesAccessCorrectFieldTest { - [TestClass] - public class PropertiesAccessCorrectFieldTest - { - private readonly VerifierBuilder builderCS = new VerifierBuilder(); - private readonly VerifierBuilder builderVB = new VerifierBuilder(); + private readonly VerifierBuilder builderCS = new VerifierBuilder(); + private readonly VerifierBuilder builderVB = new VerifierBuilder(); + + private static IEnumerable AdditionalReferences => + NuGetMetadataReference.MvvmLightLibs("5.4.1.1") + .Concat(MetadataReferenceFacade.WindowsBase) + .Concat(MetadataReferenceFacade.PresentationFramework); - [TestMethod] - public void PropertiesAccessCorrectField_CS() => - builderCS.AddPaths("PropertiesAccessCorrectField.cs").AddReferences(AdditionalReferences).Verify(); + [TestMethod] + public void PropertiesAccessCorrectField_CS() => + builderCS.AddPaths("PropertiesAccessCorrectField.cs").AddReferences(AdditionalReferences).Verify(); - [TestMethod] - public void PropertiesAccessCorrectField_CSharp8() => - builderCS.AddPaths("PropertiesAccessCorrectField.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + [TestMethod] + public void PropertiesAccessCorrectField_CSharp8() => + builderCS.AddPaths("PropertiesAccessCorrectField.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); #if NET - [TestMethod] - public void PropertiesAccessCorrectField_CSharp9() => - builderCS.AddPaths("PropertiesAccessCorrectField.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + [TestMethod] + public void PropertiesAccessCorrectField_CSharp9() => + builderCS.AddPaths("PropertiesAccessCorrectField.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); - [TestMethod] - public void PropertiesAccessCorrectField_CSharp12() => - builderCS.AddPaths("PropertiesAccessCorrectField.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + [TestMethod] + public void PropertiesAccessCorrectField_CSharp12() => + builderCS.AddPaths("PropertiesAccessCorrectField.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).VerifyNoIssues(); #else - [TestMethod] - public void PropertiesAccessCorrectField_CS_NetFramework() => - builderCS.AddPaths("PropertiesAccessCorrectField.NetFramework.cs").AddReferences(AdditionalReferences).Verify(); + [TestMethod] + public void PropertiesAccessCorrectField_CS_NetFramework() => + builderCS.AddPaths("PropertiesAccessCorrectField.NetFramework.cs").AddReferences(AdditionalReferences).VerifyNoIssues(); - [TestMethod] - public void PropertiesAccessCorrectField_VB_NetFramework() => - builderVB.AddPaths("PropertiesAccessCorrectField.NetFramework.vb").AddReferences(AdditionalReferences).Verify(); + [TestMethod] + public void PropertiesAccessCorrectField_VB_NetFramework() => + builderVB.AddPaths("PropertiesAccessCorrectField.NetFramework.vb").AddReferences(AdditionalReferences).VerifyNoIssues(); #endif - [TestMethod] - public void PropertiesAccessCorrectField_VB() => - builderVB.AddPaths("PropertiesAccessCorrectField.vb").AddReferences(AdditionalReferences).WithOptions(ParseOptionsHelper.FromVisualBasic14).Verify(); - - private static IEnumerable AdditionalReferences => - NuGetMetadataReference.MvvmLightLibs("5.4.1.1") - .Concat(MetadataReferenceFacade.WindowsBase) - .Concat(MetadataReferenceFacade.PresentationFramework); - } + [TestMethod] + public void PropertiesAccessCorrectField_VB() => + builderVB.AddPaths("PropertiesAccessCorrectField.vb").AddReferences(AdditionalReferences).WithOptions(ParseOptionsHelper.FromVisualBasic14).Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/PropertyNamesShouldNotMatchGetMethodsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/PropertyNamesShouldNotMatchGetMethodsTest.cs index a6535d778b4..3c6d51bc6e2 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/PropertyNamesShouldNotMatchGetMethodsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/PropertyNamesShouldNotMatchGetMethodsTest.cs @@ -20,38 +20,38 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules -{ - [TestClass] - public class PropertyNamesShouldNotMatchGetMethodsTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); - - [TestMethod] - public void PropertyNamesShouldNotMatchGetMethods() => - builder.AddPaths("PropertyNamesShouldNotMatchGetMethods.cs").Verify(); - - [TestMethod] - public void PropertyNamesShouldNotMatchGetMethods_InvalidCode() => - builder.AddSnippet(@" -public class Sample +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class PropertyNamesShouldNotMatchGetMethodsTest { - // Missing identifier on purpose - public int { get; } - public int () { return 42; } -}").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); + private readonly VerifierBuilder builder = new VerifierBuilder(); + + [TestMethod] + public void PropertyNamesShouldNotMatchGetMethods() => + builder.AddPaths("PropertyNamesShouldNotMatchGetMethods.cs").Verify(); + + [TestMethod] + public void PropertyNamesShouldNotMatchGetMethods_InvalidCode() => + builder.AddSnippet(""" + public class Sample + { + // Missing identifier on purpose + public int { get; } + public int () { return 42; } + } + """).VerifyNoIssuesIgnoreErrors(); #if NET - [TestMethod] - public void PropertyNamesShouldNotMatchGetMethods_CSharp9() => - builder.AddPaths("PropertyNamesShouldNotMatchGetMethods.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + [TestMethod] + public void PropertyNamesShouldNotMatchGetMethods_CSharp9() => + builder.AddPaths("PropertyNamesShouldNotMatchGetMethods.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); - [TestMethod] - public void PropertyNamesShouldNotMatchGetMethods_CSharp10() => - builder.AddPaths("PropertyNamesShouldNotMatchGetMethods.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void PropertyNamesShouldNotMatchGetMethods_CSharp10() => + builder.AddPaths("PropertyNamesShouldNotMatchGetMethods.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantCastTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantCastTest.cs index 697fb33bb2c..d1e9c38bc5d 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantCastTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantCastTest.cs @@ -28,6 +28,32 @@ public class RedundantCastTest { private readonly VerifierBuilder builder = new VerifierBuilder(); + private static IEnumerable<(string Snippet, bool CompliantWithFlowState, bool CompliantWithoutFlowState)> NullableTestData => new[] + { + ("""_ = (string)"Test";""", false, false), + ("""_ = (string?)"Test";""", true, false), + ("""_ = (string)null;""", true, true), + ("""_ = (string?)null;""", true, true), + ("""_ = (string)nullable;""", true, false), + ("""_ = (string?)nullable;""", false, false), + ("""_ = (string)nonNullable;""", false, false), + ("""_ = (string?)nonNullable;""", true, false), + ("""_ = nullable as string;""", true, false), + ("""_ = nonNullable as string;""", false, false), + ("""if (nullable != null) _ = (string)nullable;""", false, false), + ("""if (nullable != null) _ = (string?)nullable;""", true, false), + ("""if (nullable != null) _ = nullable as string;""", false, false), + ("""if (nonNullable == null) _ = (string)nonNullable;""", true, false), + ("""if (nonNullable == null) _ = (string?)nonNullable;""", false, false), + ("""if (nonNullable == null) _ = nonNullable as string;""", true, false), + }; + + private static IEnumerable NullableTestDataWithFlowState => + NullableTestData.Select(x => new object[] { x.Snippet, x.CompliantWithFlowState }); + + private static IEnumerable NullableTestDataWithoutFlowState => + NullableTestData.Select(x => new object[] { x.Snippet, x.CompliantWithoutFlowState }); + [TestMethod] public void RedundantCast() => builder.AddPaths("RedundantCast.cs").Verify(); @@ -61,27 +87,27 @@ public static void RunAction(Action action) public static T RunFunc(Func func, T returnValue = default) => returnValue; } - """).WithLanguageVersion(LanguageVersion.CSharp7_1).Verify(); + """).WithLanguageVersion(LanguageVersion.CSharp7_1).VerifyNoIssues(); [TestMethod] [DynamicData(nameof(NullableTestDataWithFlowState))] - public void RedundantCast_NullableEnabled(string snippet, bool compliant) - => VerifyNullableTests(snippet, "enable", compliant); + public void RedundantCast_NullableEnabled(string snippet, bool compliant) => + VerifyNullableTests(snippet, "enable", compliant); [TestMethod] [DynamicData(nameof(NullableTestDataWithFlowState))] - public void RedundantCast_NullableWarnings(string snippet, bool compliant) - => VerifyNullableTests(snippet, "enable warnings", compliant); + public void RedundantCast_NullableWarnings(string snippet, bool compliant) => + VerifyNullableTests(snippet, "enable warnings", compliant); [TestMethod] [DynamicData(nameof(NullableTestDataWithoutFlowState))] - public void RedundantCast_NullableDisabled(string snippet, bool compliant) - => VerifyNullableTests(snippet, "disable", compliant); + public void RedundantCast_NullableDisabled(string snippet, bool compliant) => + VerifyNullableTests(snippet, "disable", compliant); [TestMethod] [DynamicData(nameof(NullableTestDataWithoutFlowState))] - public void RedundantCast_NullableAnnotations(string snippet, bool compliant) - => VerifyNullableTests(snippet, "enable annotations", compliant); + public void RedundantCast_NullableAnnotations(string snippet, bool compliant) => + VerifyNullableTests(snippet, "enable annotations", compliant); private void VerifyNullableTests(string snippet, string nullableContext, bool compliant) { @@ -92,32 +118,14 @@ void Test(string nonNullable, string? nullable) {{snippet}} // {{compliant switch { true => "Compliant", false => "Noncompliant" }}} } """; - builder.AddSnippet(code).WithTopLevelStatements().Verify(); + var snippetVerifier = builder.AddSnippet(code).WithTopLevelStatements(); + if (compliant) + { + snippetVerifier.VerifyNoIssues(); + } + else + { + snippetVerifier.Verify(); + } } - - private static IEnumerable<(string Snippet, bool CompliantWithFlowState, bool CompliantWithoutFlowState)> NullableTestData => new[] - { - ("""_ = (string)"Test";""", false, false), - ("""_ = (string?)"Test";""", true, false), - ("""_ = (string)null;""", true, true), - ("""_ = (string?)null;""", true, true), - ("""_ = (string)nullable;""", true, false), - ("""_ = (string?)nullable;""", false, false), - ("""_ = (string)nonNullable;""", false, false), - ("""_ = (string?)nonNullable;""", true, false), - ("""_ = nullable as string;""", true, false), - ("""_ = nonNullable as string;""", false, false), - ("""if (nullable != null) _ = (string)nullable;""", false, false), - ("""if (nullable != null) _ = (string?)nullable;""", true, false), - ("""if (nullable != null) _ = nullable as string;""", false, false), - ("""if (nonNullable == null) _ = (string)nonNullable;""", true, false), - ("""if (nonNullable == null) _ = (string?)nonNullable;""", false, false), - ("""if (nonNullable == null) _ = nonNullable as string;""", true, false), - }; - - private static IEnumerable NullableTestDataWithFlowState => - NullableTestData.Select(x => new object[] { x.Snippet, x.CompliantWithFlowState }); - - private static IEnumerable NullableTestDataWithoutFlowState => - NullableTestData.Select(x => new object[] { x.Snippet, x.CompliantWithoutFlowState }); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantConditionalAroundAssignmentTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantConditionalAroundAssignmentTest.cs index 1be56223ffb..4f7827bc00a 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantConditionalAroundAssignmentTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantConditionalAroundAssignmentTest.cs @@ -66,7 +66,7 @@ public class RedundantConditionalAroundAssignmentTest public void RedundantConditionalAroundAssignment_CSharp11() => builder.AddPaths("RedundantConditionalAroundAssignment.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantDeclarationTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantDeclarationTest.cs index 640d9309941..18f3671716c 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantDeclarationTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantDeclarationTest.cs @@ -20,130 +20,129 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class RedundantDeclarationTest { - [TestClass] - public class RedundantDeclarationTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); - private readonly VerifierBuilder codeFixBuilder = new VerifierBuilder().WithCodeFix(); - - [TestMethod] - public void RedundantDeclaration() => - builder.AddPaths("RedundantDeclaration.cs") - .WithOptions(ParseOptionsHelper.BeforeCSharp10) - .Verify(); - - [TestMethod] - public void RedundantDeclaration_UnusedLambdaParameters_BeforeCSharp9() => - builder.AddSnippet(@"using System; public class C { public void M() { Action a = (p1, p2) => { }; /* Compliant - Lambda discard parameters have been introduced in C# 9 */ } }") - .WithOptions(ParseOptionsHelper.BeforeCSharp9) - .Verify(); + private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder codeFixBuilder = new VerifierBuilder().WithCodeFix(); + + [TestMethod] + public void RedundantDeclaration() => + builder.AddPaths("RedundantDeclaration.cs") + .WithOptions(ParseOptionsHelper.BeforeCSharp10) + .Verify(); + + [TestMethod] + public void RedundantDeclaration_UnusedLambdaParameters_BeforeCSharp9() => + builder.AddSnippet(@"using System; public class C { public void M() { Action a = (p1, p2) => { }; /* Compliant - Lambda discard parameters have been introduced in C# 9 */ } }") + .WithOptions(ParseOptionsHelper.BeforeCSharp9) + .VerifyNoIssues(); #if NET - [TestMethod] - public void RedundantDeclaration_CSharp9() => - builder.AddPaths("RedundantDeclaration.CSharp9.cs") - .WithTopLevelStatements() - .Verify(); - - [TestMethod] - public void RedundantDeclaration_CSharp9_CodeFix_TitleRedundantParameterName() => - codeFixBuilder.AddPaths("RedundantDeclaration.CSharp9.cs") - .WithCodeFixedPaths("RedundantDeclaration.CSharp9.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantParameterName) - .WithOptions(ParseOptionsHelper.FromCSharp9) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CSharp10() => - builder.AddPaths("RedundantDeclaration.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); - - [TestMethod] - public void RedundantDeclaration_CSharp10_CodeFix_ExplicitDelegate() => - codeFixBuilder.AddPaths("RedundantDeclaration.CSharp10.cs") - .WithCodeFixedPaths("RedundantDeclaration.CSharp10.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantExplicitDelegate) - .WithOptions(ParseOptionsHelper.FromCSharp10) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CSharp12() => - builder.AddPaths("RedundantDeclaration.CSharp12.cs") - .WithOptions(ParseOptionsHelper.FromCSharp12) - .Verify(); - - [TestMethod] - public void RedundantDeclaration_CSharp12_CodeFix_ArraySize() => - codeFixBuilder.AddPaths("RedundantDeclaration.CSharp12.cs") - .WithCodeFix() - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantArraySize) - .WithCodeFixedPaths("RedundantDeclaration.CSharp12.ArraySize.Fixed.cs") - .WithOptions(ParseOptionsHelper.FromCSharp12) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CSharp12_CodeFix_LambdaParameterType() => - codeFixBuilder.AddPaths("RedundantDeclaration.CSharp12.cs") - .WithCodeFix() - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantLambdaParameterType) - .WithCodeFixedPaths("RedundantDeclaration.CSharp12.LambdaParameterType.Fixed.cs") - .WithOptions(ParseOptionsHelper.FromCSharp12) - .VerifyCodeFix(); + [TestMethod] + public void RedundantDeclaration_CSharp9() => + builder.AddPaths("RedundantDeclaration.CSharp9.cs") + .WithTopLevelStatements() + .Verify(); + + [TestMethod] + public void RedundantDeclaration_CSharp9_CodeFix_TitleRedundantParameterName() => + codeFixBuilder.AddPaths("RedundantDeclaration.CSharp9.cs") + .WithCodeFixedPaths("RedundantDeclaration.CSharp9.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantParameterName) + .WithOptions(ParseOptionsHelper.FromCSharp9) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CSharp10() => + builder.AddPaths("RedundantDeclaration.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .Verify(); + + [TestMethod] + public void RedundantDeclaration_CSharp10_CodeFix_ExplicitDelegate() => + codeFixBuilder.AddPaths("RedundantDeclaration.CSharp10.cs") + .WithCodeFixedPaths("RedundantDeclaration.CSharp10.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantExplicitDelegate) + .WithOptions(ParseOptionsHelper.FromCSharp10) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CSharp12() => + builder.AddPaths("RedundantDeclaration.CSharp12.cs") + .WithOptions(ParseOptionsHelper.FromCSharp12) + .Verify(); + + [TestMethod] + public void RedundantDeclaration_CSharp12_CodeFix_ArraySize() => + codeFixBuilder.AddPaths("RedundantDeclaration.CSharp12.cs") + .WithCodeFix() + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantArraySize) + .WithCodeFixedPaths("RedundantDeclaration.CSharp12.ArraySize.Fixed.cs") + .WithOptions(ParseOptionsHelper.FromCSharp12) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CSharp12_CodeFix_LambdaParameterType() => + codeFixBuilder.AddPaths("RedundantDeclaration.CSharp12.cs") + .WithCodeFix() + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantLambdaParameterType) + .WithCodeFixedPaths("RedundantDeclaration.CSharp12.LambdaParameterType.Fixed.cs") + .WithOptions(ParseOptionsHelper.FromCSharp12) + .VerifyCodeFix(); #endif - [TestMethod] - public void RedundantDeclaration_CodeFix_ArraySize() => - codeFixBuilder.AddPaths("RedundantDeclaration.cs") - .WithCodeFixedPaths("RedundantDeclaration.ArraySize.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantArraySize) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CodeFix_ArrayType() => - codeFixBuilder.AddPaths("RedundantDeclaration.cs") - .WithCodeFixedPaths("RedundantDeclaration.ArrayType.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantArrayType) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CodeFix_DelegateParameterList() => - codeFixBuilder.AddPaths("RedundantDeclaration.cs") - .WithCodeFixedPaths("RedundantDeclaration.DelegateParameterList.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantDelegateParameterList) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CodeFix_ExplicitDelegate() => - codeFixBuilder.AddPaths("RedundantDeclaration.cs") - .WithCodeFixedPaths("RedundantDeclaration.ExplicitDelegate.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantExplicitDelegate) - .WithOptions(ParseOptionsHelper.BeforeCSharp10) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CodeFix_ExplicitNullable() => - codeFixBuilder.AddPaths("RedundantDeclaration.cs") - .WithCodeFixedPaths("RedundantDeclaration.ExplicitNullable.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantExplicitNullable) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CodeFix_LambdaParameterType() => - codeFixBuilder.AddPaths("RedundantDeclaration.cs") - .WithCodeFixedPaths("RedundantDeclaration.LambdaParameterType.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantLambdaParameterType) - .VerifyCodeFix(); - - [TestMethod] - public void RedundantDeclaration_CodeFix_ObjectInitializer() => - codeFixBuilder.AddPaths("RedundantDeclaration.cs") - .WithCodeFixedPaths("RedundantDeclaration.ObjectInitializer.Fixed.cs") - .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantObjectInitializer) - .VerifyCodeFix(); - } + [TestMethod] + public void RedundantDeclaration_CodeFix_ArraySize() => + codeFixBuilder.AddPaths("RedundantDeclaration.cs") + .WithCodeFixedPaths("RedundantDeclaration.ArraySize.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantArraySize) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CodeFix_ArrayType() => + codeFixBuilder.AddPaths("RedundantDeclaration.cs") + .WithCodeFixedPaths("RedundantDeclaration.ArrayType.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantArrayType) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CodeFix_DelegateParameterList() => + codeFixBuilder.AddPaths("RedundantDeclaration.cs") + .WithCodeFixedPaths("RedundantDeclaration.DelegateParameterList.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantDelegateParameterList) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CodeFix_ExplicitDelegate() => + codeFixBuilder.AddPaths("RedundantDeclaration.cs") + .WithCodeFixedPaths("RedundantDeclaration.ExplicitDelegate.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantExplicitDelegate) + .WithOptions(ParseOptionsHelper.BeforeCSharp10) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CodeFix_ExplicitNullable() => + codeFixBuilder.AddPaths("RedundantDeclaration.cs") + .WithCodeFixedPaths("RedundantDeclaration.ExplicitNullable.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantExplicitNullable) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CodeFix_LambdaParameterType() => + codeFixBuilder.AddPaths("RedundantDeclaration.cs") + .WithCodeFixedPaths("RedundantDeclaration.LambdaParameterType.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantLambdaParameterType) + .VerifyCodeFix(); + + [TestMethod] + public void RedundantDeclaration_CodeFix_ObjectInitializer() => + codeFixBuilder.AddPaths("RedundantDeclaration.cs") + .WithCodeFixedPaths("RedundantDeclaration.ObjectInitializer.Fixed.cs") + .WithCodeFixTitle(RedundantDeclarationCodeFix.TitleRedundantObjectInitializer) + .VerifyCodeFix(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantNullCheckTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantNullCheckTest.cs index 6223807c640..abb2b6949d4 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantNullCheckTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/RedundantNullCheckTest.cs @@ -58,7 +58,7 @@ public class RedundantNullCheckTest public void RedundantNullCheck_CSharp11() => builderCS.AddPaths("RedundantNullCheck.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void RedundantNullCheck_CSharp9_CodeFix() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SerializationConstructorsShouldBeSecuredTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SerializationConstructorsShouldBeSecuredTest.cs index 751f97cba8a..46f409ad804 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SerializationConstructorsShouldBeSecuredTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SerializationConstructorsShouldBeSecuredTest.cs @@ -20,46 +20,46 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class SerializationConstructorsShouldBeSecuredTest { - [TestClass] - public class SerializationConstructorsShouldBeSecuredTest - { - private readonly VerifierBuilder builder = new VerifierBuilder().AddReferences(MetadataReferenceFacade.SystemSecurityPermissions); + private readonly VerifierBuilder builder = new VerifierBuilder().AddReferences(MetadataReferenceFacade.SystemSecurityPermissions); - [TestMethod] - public void SerializationConstructorsShouldBeSecured() => - builder.AddPaths("SerializationConstructorsShouldBeSecured.cs").WithConcurrentAnalysis(false).Verify(); + [TestMethod] + public void SerializationConstructorsShouldBeSecured() => + builder.AddPaths("SerializationConstructorsShouldBeSecured.cs").WithConcurrentAnalysis(false).Verify(); #if NET - [TestMethod] - public void SerializationConstructorsShouldBeSecured_CSharp9() => - builder.AddPaths("SerializationConstructorsShouldBeSecured.CSharp9.cs").WithConcurrentAnalysis(false).WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + [TestMethod] + public void SerializationConstructorsShouldBeSecured_CSharp9() => + builder.AddPaths("SerializationConstructorsShouldBeSecured.CSharp9.cs").WithConcurrentAnalysis(false).WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); #endif - [TestMethod] - public void SerializationConstructorsShouldBeSecured_InvalidCode() => - builder.AddSnippet(@" -[Serializable] - public partial class InvalidCode : ISerializable - { - [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)] - [ZoneIdentityPermission(SecurityAction.Demand, Unrestricted = true)] - public InvalidCode() { } + [TestMethod] + public void SerializationConstructorsShouldBeSecured_InvalidCode() => + builder.AddSnippet(""" + [Serializable] + public partial class InvalidCode : ISerializable + { + [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)] + [ZoneIdentityPermission(SecurityAction.Demand, Unrestricted = true)] + public InvalidCode() { } - protected (SerializationInfo info, StreamingContext context) { } + protected (SerializationInfo info, StreamingContext context) { } - public void GetObjectData(SerializationInfo info, StreamingContext context) { } - }").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); + public void GetObjectData(SerializationInfo info, StreamingContext context) { } + } + """).VerifyNoIssuesIgnoreErrors(); - [TestMethod] - public void SerializationConstructorsShouldBeSecured_NoAssemblyAttribute() => - builder.AddPaths("SerializationConstructorsShouldBeSecured_NoAssemblyAttribute.cs").Verify(); + [TestMethod] + public void SerializationConstructorsShouldBeSecured_NoAssemblyAttribute() => + builder.AddPaths("SerializationConstructorsShouldBeSecured_NoAssemblyAttribute.cs").VerifyNoIssues(); - [TestMethod] - public void SerializationConstructorsShouldBeSecured_PartialClasses() => - builder.AddPaths("SerializationConstructorsShouldBeSecured_Part1.cs", "SerializationConstructorsShouldBeSecured_Part2.cs").WithConcurrentAnalysis(false).Verify(); - } + [TestMethod] + public void SerializationConstructorsShouldBeSecured_PartialClasses() => + builder.AddPaths("SerializationConstructorsShouldBeSecured_Part1.cs", "SerializationConstructorsShouldBeSecured_Part2.cs").WithConcurrentAnalysis(false).Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SqlKeywordsDelimitedBySpaceTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SqlKeywordsDelimitedBySpaceTest.cs index 453e7498159..df78247a959 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SqlKeywordsDelimitedBySpaceTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SqlKeywordsDelimitedBySpaceTest.cs @@ -20,94 +20,94 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class SqlKeywordsDelimitedBySpaceTest { - [TestClass] - public class SqlKeywordsDelimitedBySpaceTest - { - private static readonly VerifierBuilder Builder = new VerifierBuilder() - .AddReferences(NuGetMetadataReference.SystemDataSqlClient()); + private static readonly VerifierBuilder Builder = new VerifierBuilder() + .AddReferences(NuGetMetadataReference.SystemDataSqlClient()); - [TestMethod] - public void SqlKeywordsDelimitedBySpace_Csharp8() => - Builder.AddPaths("SqlKeywordsDelimitedBySpace.cs") - .WithOptions(ParseOptionsHelper.FromCSharp8) - .Verify(); + [TestMethod] + public void SqlKeywordsDelimitedBySpace_Csharp8() => + Builder.AddPaths("SqlKeywordsDelimitedBySpace.cs") + .WithOptions(ParseOptionsHelper.FromCSharp8) + .Verify(); - [TestMethod] - public void SqlKeywordsDelimitedBySpace_UsingInsideNamespace() => - Builder.AddPaths("SqlKeywordsDelimitedBySpace_InsideNamespace.cs") - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void SqlKeywordsDelimitedBySpace_UsingInsideNamespace() => + Builder.AddPaths("SqlKeywordsDelimitedBySpace_InsideNamespace.cs") + .WithConcurrentAnalysis(false) + .Verify(); - [TestMethod] - public void SqlKeywordsDelimitedBySpace_DefaultNamespace() => - Builder.AddPaths("SqlKeywordsDelimitedBySpace_DefaultNamespace.cs") - .AddTestReference() - .VerifyNoIssues(); + [TestMethod] + public void SqlKeywordsDelimitedBySpace_DefaultNamespace() => + Builder.AddPaths("SqlKeywordsDelimitedBySpace_DefaultNamespace.cs") + .AddTestReference() + .VerifyNoIssues(); #if NET - [TestMethod] - public void SqlKeywordsDelimitedBySpace_CSharp10_GlobalUsings() => - Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp10.GlobalUsing.cs", "SqlKeywordsDelimitedBySpace.CSharp10.GlobalUsingConsumer.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void SqlKeywordsDelimitedBySpace_CSharp10_GlobalUsings() => + Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp10.GlobalUsing.cs", "SqlKeywordsDelimitedBySpace.CSharp10.GlobalUsingConsumer.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .WithConcurrentAnalysis(false) + .VerifyNoIssues(); - [TestMethod] - public void SqlKeywordsDelimitedBySpace_CSharp10_FileScopesNamespace() => - Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp10.FileScopedNamespaceDeclaration.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void SqlKeywordsDelimitedBySpace_CSharp10_FileScopesNamespace() => + Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp10.FileScopedNamespaceDeclaration.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .WithConcurrentAnalysis(false) + .Verify(); - [TestMethod] - public void SqlKeywordsDelimitedBySpace_CSharp10() => - Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + [TestMethod] + public void SqlKeywordsDelimitedBySpace_CSharp10() => + Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .Verify(); - [TestMethod] - public void SqlKeywordsDelimitedBySpace_CSharp11() => - Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void SqlKeywordsDelimitedBySpace_CSharp11() => + Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .Verify(); - [TestMethod] - public void SqlKeywordsDelimitedBySpace_CSharp12() => - Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp12.cs") - .WithOptions(ParseOptionsHelper.FromCSharp12) - .WithConcurrentAnalysis(false) - .Verify(); + [TestMethod] + public void SqlKeywordsDelimitedBySpace_CSharp12() => + Builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp12.cs") + .WithOptions(ParseOptionsHelper.FromCSharp12) + .WithConcurrentAnalysis(false) + .Verify(); #endif - [DataRow("System.Data")] - [DataRow("System.Data.SqlClient")] - [DataRow("System.Data.SQLite")] - [DataRow("System.Data.SqlServerCe")] - [DataRow("System.Data.Entity")] - [DataRow("System.Data.Odbc")] - [DataRow("Dapper")] - [DataRow("Microsoft.Data.SqlClient")] - [DataRow("Microsoft.Data.Sqlite")] - [DataRow("NHibernate")] - [DataRow("PetaPoco")] - [DataTestMethod] - public void SqlKeywordsDelimitedBySpace_DotnetFramework(string sqlNamespace) => - Builder - .AddReferences(MetadataReferenceFacade.SystemData) - .AddReferences(NuGetMetadataReference.Dapper()) - .AddReferences(NuGetMetadataReference.EntityFramework()) - .AddReferences(NuGetMetadataReference.MicrosoftDataSqlClient()) - .AddReferences(NuGetMetadataReference.MicrosoftDataSqliteCore()) - .AddReferences(NuGetMetadataReference.MicrosoftSqlServerCompact()) - .AddReferences(NuGetMetadataReference.NHibernate()) - .AddReferences(NuGetMetadataReference.PetaPocoCompiled()) - .AddReferences(NuGetMetadataReference.SystemDataOdbc()) - .AddReferences(NuGetMetadataReference.SystemDataSQLiteCore()) - .AddSnippet($@" + [DataRow("System.Data")] + [DataRow("System.Data.SqlClient")] + [DataRow("System.Data.SQLite")] + [DataRow("System.Data.SqlServerCe")] + [DataRow("System.Data.Entity")] + [DataRow("System.Data.Odbc")] + [DataRow("Dapper")] + [DataRow("Microsoft.Data.SqlClient")] + [DataRow("Microsoft.Data.Sqlite")] + [DataRow("NHibernate")] + [DataRow("PetaPoco")] + [DataTestMethod] + public void SqlKeywordsDelimitedBySpace_DotnetFramework(string sqlNamespace) => + Builder + .AddReferences(MetadataReferenceFacade.SystemData) + .AddReferences(NuGetMetadataReference.Dapper()) + .AddReferences(NuGetMetadataReference.EntityFramework()) + .AddReferences(NuGetMetadataReference.MicrosoftDataSqlClient()) + .AddReferences(NuGetMetadataReference.MicrosoftDataSqliteCore()) + .AddReferences(NuGetMetadataReference.MicrosoftSqlServerCompact()) + .AddReferences(NuGetMetadataReference.NHibernate()) + .AddReferences(NuGetMetadataReference.PetaPocoCompiled()) + .AddReferences(NuGetMetadataReference.SystemDataOdbc()) + .AddReferences(NuGetMetadataReference.SystemDataSQLiteCore()) + .AddSnippet($@" using {sqlNamespace}; namespace TestNamespace {{ @@ -119,18 +119,18 @@ public class Test }} }}").Verify(); - [DataRow("System.Data.SqlClient")] - [DataRow("System.Data.OracleClient")] - [DataRow("Microsoft.EntityFrameworkCore")] - [DataRow("ServiceStack.OrmLite")] - [DataTestMethod] - public void SqlKeywordsDelimitedBySpace_DotnetCore(string sqlNamespace) => - Builder - .AddReferences(MetadataReferenceFacade.SystemData) - .AddReferences(NuGetMetadataReference.MicrosoftEntityFrameworkCore("2.2.0")) - .AddReferences(NuGetMetadataReference.ServiceStackOrmLite()) - .AddReferences(NuGetMetadataReference.SystemDataOracleClient()) - .AddSnippet($@" + [DataRow("System.Data.SqlClient")] + [DataRow("System.Data.OracleClient")] + [DataRow("Microsoft.EntityFrameworkCore")] + [DataRow("ServiceStack.OrmLite")] + [DataTestMethod] + public void SqlKeywordsDelimitedBySpace_DotnetCore(string sqlNamespace) => + Builder + .AddReferences(MetadataReferenceFacade.SystemData) + .AddReferences(NuGetMetadataReference.MicrosoftEntityFrameworkCore("2.2.0")) + .AddReferences(NuGetMetadataReference.ServiceStackOrmLite()) + .AddReferences(NuGetMetadataReference.SystemDataOracleClient()) + .AddSnippet($@" using {sqlNamespace}; namespace TestNamespace {{ @@ -141,5 +141,4 @@ public class Test ""val""; }} }}").Verify(); - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/StreamReadStatementTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/StreamReadStatementTest.cs index 8c43112471e..7a993ff4f4f 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/StreamReadStatementTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/StreamReadStatementTest.cs @@ -20,28 +20,27 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class StreamReadStatementTest { - [TestClass] - public class StreamReadStatementTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void StreamReadStatement() => - builder.AddPaths("StreamReadStatement.cs").Verify(); + [TestMethod] + public void StreamReadStatement() => + builder.AddPaths("StreamReadStatement.cs").Verify(); #if NET - [TestMethod] - public void StreamReadStatement_CSharp10() => - builder.AddPaths("StreamReadStatement.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void StreamReadStatement_CSharp10() => + builder.AddPaths("StreamReadStatement.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).VerifyNoIssues(); - [TestMethod] - public void StreamReadStatement_CSharp11() => - builder.AddPaths("StreamReadStatement.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void StreamReadStatement_CSharp11() => + builder.AddPaths("StreamReadStatement.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/StringOperationWithoutCultureTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/StringOperationWithoutCultureTest.cs index adf7e17961a..f535aa47973 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/StringOperationWithoutCultureTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/StringOperationWithoutCultureTest.cs @@ -20,32 +20,31 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class StringOperationWithoutCultureTest { - [TestClass] - public class StringOperationWithoutCultureTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void StringOperationWithoutCulture() => - builder.AddPaths("StringOperationWithoutCulture.cs").Verify(); + [TestMethod] + public void StringOperationWithoutCulture() => + builder.AddPaths("StringOperationWithoutCulture.cs").Verify(); #if NET - [TestMethod] - public void StringOperationWithoutCulture_CSharp10() => - builder.AddPaths("StringOperationWithoutCulture.CSharp10.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + [TestMethod] + public void StringOperationWithoutCulture_CSharp10() => + builder.AddPaths("StringOperationWithoutCulture.CSharp10.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .VerifyNoIssues(); - [TestMethod] - public void StringOperationWithoutCulture_CSharp11() => - builder.AddPaths("StringOperationWithoutCulture.CSharp11.cs") - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void StringOperationWithoutCulture_CSharp11() => + builder.AddPaths("StringOperationWithoutCulture.CSharp11.cs") + .WithOptions(ParseOptionsHelper.FromCSharp11) + .Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SwaggerActionReturnTypeTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SwaggerActionReturnTypeTest.cs index 1f732923eb4..6e15c72cb0f 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SwaggerActionReturnTypeTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SwaggerActionReturnTypeTest.cs @@ -102,7 +102,7 @@ public class Foo : Controller public class Bar {} """) - .Verify(); + .VerifyNoIssues(); [DataTestMethod] [DataRow("""Results.Ok(bar)""")] @@ -162,7 +162,7 @@ public class Foo : Controller public class Bar {} """) - .Verify(); + .VerifyNoIssues(); } #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/ConditionEvaluatesToConstantTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/ConditionEvaluatesToConstantTest.cs index 07bbb62c71f..b6421466a8c 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/ConditionEvaluatesToConstantTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/ConditionEvaluatesToConstantTest.cs @@ -116,7 +116,7 @@ public class ConditionEvaluatesToConstantTest public void ConditionEvaluatesToConstant_Sonar_CSharp9_TopLevelStatements() => sonar.AddPaths("ConditionEvaluatesToConstant.CSharp9.TopLevelStatements.cs") .WithTopLevelStatements() - .Verify(); + .VerifyNoIssues(); [TestMethod] public void ConditionEvaluatesToConstant_Roslyn_CSharp9_TopLevelStatements() => @@ -129,7 +129,7 @@ public class ConditionEvaluatesToConstantTest sonar.AddPaths("ConditionEvaluatesToConstant.CSharp10.cs") .WithOptions(ParseOptionsHelper.FromCSharp10) .WithConcurrentAnalysis(false) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void ConditionEvaluatesToConstant_Roslyn_CSharp10() => @@ -142,13 +142,13 @@ public class ConditionEvaluatesToConstantTest public void ConditionEvaluatesToConstant_Sonar_CSharp11() => sonar.AddPaths("ConditionEvaluatesToConstant.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void ConditionEvaluatesToConstant_Roslyn_CSharp11() => roslynCS.AddPaths("ConditionEvaluatesToConstant.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void ConditionEvaluatesToConstant_Roslyn_CSharp12() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/EmptyCollectionsShouldNotBeEnumeratedTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/EmptyCollectionsShouldNotBeEnumeratedTest.cs index 1f251e367b1..f04c2dd2b66 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/EmptyCollectionsShouldNotBeEnumeratedTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/EmptyCollectionsShouldNotBeEnumeratedTest.cs @@ -88,7 +88,7 @@ public class EmptyCollectionsShouldNotBeEnumeratedTest [TestMethod] public void EmptyCollectionsShouldNotBeEnumerated_Sonar_CSharp10() => - sonar.AddPaths("EmptyCollectionsShouldNotBeEnumerated.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + sonar.AddPaths("EmptyCollectionsShouldNotBeEnumerated.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).VerifyNoIssues(); [TestMethod] public void EmptyCollectionsShouldNotBeEnumerated_Roslyn_CSharp10() => @@ -96,15 +96,15 @@ public class EmptyCollectionsShouldNotBeEnumeratedTest [TestMethod] public void EmptyCollectionsShouldNotBeEnumerated_Sonar_CSharp11() => - sonar.AddPaths("EmptyCollectionsShouldNotBeEnumerated.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + sonar.AddPaths("EmptyCollectionsShouldNotBeEnumerated.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).VerifyNoIssues(); [TestMethod] public void EmptyCollectionsShouldNotBeEnumerated_Roslyn_CSharp11() => - roslynCS.AddPaths("EmptyCollectionsShouldNotBeEnumerated.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + roslynCS.AddPaths("EmptyCollectionsShouldNotBeEnumerated.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).VerifyNoIssues(); [TestMethod] public void EmptyCollectionsShouldNotBeEnumerated_Roslyn_CSharp12() => - roslynCS.AddPaths("EmptyCollectionsShouldNotBeEnumerated.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + roslynCS.AddPaths("EmptyCollectionsShouldNotBeEnumerated.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/HashesShouldHaveUnpredictableSaltTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/HashesShouldHaveUnpredictableSaltTest.cs index 2a2cf14e276..0a12aa2f95e 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/HashesShouldHaveUnpredictableSaltTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/HashesShouldHaveUnpredictableSaltTest.cs @@ -107,7 +107,7 @@ public class HashesShouldHaveUnpredictableSaltTest public void HashesShouldHaveUnpredictableSalt_Sonar_CSharp10() => sonar.AddPaths("HashesShouldHaveUnpredictableSalt.CSharp10.cs") .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void HashesShouldHaveUnpredictableSalt_Roslyn_CSharp10() => @@ -119,13 +119,13 @@ public class HashesShouldHaveUnpredictableSaltTest public void HashesShouldHaveUnpredictableSalt_Sonar_CSharp11() => sonar.AddPaths("HashesShouldHaveUnpredictableSalt.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void HashesShouldHaveUnpredictableSalt_Roslyn_CSharp11() => roslynCS.AddPaths("HashesShouldHaveUnpredictableSalt.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/InitializationVectorShouldBeRandomTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/InitializationVectorShouldBeRandomTest.cs index 96a3349e958..86ae53feb6a 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/InitializationVectorShouldBeRandomTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/InitializationVectorShouldBeRandomTest.cs @@ -98,7 +98,7 @@ public class InitializationVectorShouldBeRandomTest public void InitializationVectorShouldBeRandom_Sonar_CSharp10() => sonar.AddPaths("InitializationVectorShouldBeRandom.CSharp10.cs") .WithOptions(ParseOptionsHelper.FromCSharp10) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void InitializationVectorShouldBeRandom_Roslyn_CSharp10() => @@ -110,13 +110,13 @@ public class InitializationVectorShouldBeRandomTest public void InitializationVectorShouldBeRandom_Sonar_CSharp11() => sonar.AddPaths("InitializationVectorShouldBeRandom.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void InitializationVectorShouldBeRandom_Roslyn_CSharp11() => roslynCS.AddPaths("InitializationVectorShouldBeRandom.CSharp11.cs") .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/NullPointerDereferenceTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/NullPointerDereferenceTest.cs index 01390616014..7bab8dcc671 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/NullPointerDereferenceTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/NullPointerDereferenceTest.cs @@ -23,110 +23,109 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class NullPointerDereferenceTest { - [TestClass] - public class NullPointerDereferenceTest - { - private readonly VerifierBuilder sonar = new VerifierBuilder() - .AddAnalyzer(() => new CS.SymbolicExecutionRunner(AnalyzerConfiguration.AlwaysEnabledWithSonarCfg)) - .WithBasePath(@"SymbolicExecution\Sonar") - .WithOnlyDiagnostics(ChecksCS.NullPointerDereference.S2259); - - private readonly VerifierBuilder roslynCS = new VerifierBuilder() - .AddAnalyzer(() => new CS.SymbolicExecutionRunner(AnalyzerConfiguration.AlwaysEnabled)) - .WithBasePath(@"SymbolicExecution\Roslyn") - .WithOnlyDiagnostics(ChecksCS.NullPointerDereference.S2259); - - private readonly VerifierBuilder roslynVB = new VerifierBuilder() - .WithBasePath(@"SymbolicExecution\Roslyn") - .WithOnlyDiagnostics(ChecksVB.NullPointerDereference.S2259); - - [TestMethod] - public void NullPointerDereference_Sonar_CS() => - sonar.AddPaths("NullPointerDereference.cs").WithConcurrentAnalysis(false).Verify(); - - [TestMethod] - public void NullPointerDereference_Roslyn_CS() => - roslynCS.AddPaths("NullPointerDereference.cs").WithConcurrentAnalysis(false).Verify(); - - [TestMethod] - public void NullPointerDereference_VB() => - roslynVB.AddPaths("NullPointerDereference.vb").Verify(); - - [TestMethod] - public void NullPointerDereference_Sonar_DoesNotRaiseIssuesForTestProject() => - sonar.AddTestReference().AddPaths("NullPointerDereference.cs").WithConcurrentAnalysis(false).VerifyNoIssues(); - - [TestMethod] - public void NullPointerDereference_Roslyn_DoesNotRaiseIssuesForTestProject() => - roslynCS.AddTestReference().AddPaths("NullPointerDereference.cs").WithConcurrentAnalysis(false).VerifyNoIssues(); - - [TestMethod] - public void NullPointerDereference_Sonar_CSharp6() => - sonar.AddPaths("NullPointerDereference.CSharp6.cs").WithOptions(ParseOptionsHelper.FromCSharp6).Verify(); - - [TestMethod] - public void NullPointerDereference_Roslyn_CSharp6() => - roslynCS.AddPaths("NullPointerDereference.CSharp6.cs").WithOptions(ParseOptionsHelper.FromCSharp6).Verify(); - - [TestMethod] - public void NullPointerDereference_Sonar_CSharp7() => - sonar.AddPaths("NullPointerDereference.CSharp7.cs").WithOptions(ParseOptionsHelper.FromCSharp7).Verify(); - - [TestMethod] - public void NullPointerDereference_Roslyn_CSharp7() => - roslynCS.AddPaths("NullPointerDereference.CSharp7.cs").WithOptions(ParseOptionsHelper.FromCSharp7).Verify(); - - [TestMethod] - public void NullPointerDereference_Sonar_CSharp8() => - sonar.AddPaths("NullPointerDereference.CSharp8.cs").AddReferences(MetadataReferenceFacade.NetStandard21).WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); - - [TestMethod] - public void NullPointerDereference_Roslyn_CSharp8() => - roslynCS.AddPaths("NullPointerDereference.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + private readonly VerifierBuilder sonar = new VerifierBuilder() + .AddAnalyzer(() => new CS.SymbolicExecutionRunner(AnalyzerConfiguration.AlwaysEnabledWithSonarCfg)) + .WithBasePath(@"SymbolicExecution\Sonar") + .WithOnlyDiagnostics(ChecksCS.NullPointerDereference.S2259); + + private readonly VerifierBuilder roslynCS = new VerifierBuilder() + .AddAnalyzer(() => new CS.SymbolicExecutionRunner(AnalyzerConfiguration.AlwaysEnabled)) + .WithBasePath(@"SymbolicExecution\Roslyn") + .WithOnlyDiagnostics(ChecksCS.NullPointerDereference.S2259); + + private readonly VerifierBuilder roslynVB = new VerifierBuilder() + .WithBasePath(@"SymbolicExecution\Roslyn") + .WithOnlyDiagnostics(ChecksVB.NullPointerDereference.S2259); + + [TestMethod] + public void NullPointerDereference_Sonar_CS() => + sonar.AddPaths("NullPointerDereference.cs").WithConcurrentAnalysis(false).Verify(); + + [TestMethod] + public void NullPointerDereference_Roslyn_CS() => + roslynCS.AddPaths("NullPointerDereference.cs").WithConcurrentAnalysis(false).Verify(); + + [TestMethod] + public void NullPointerDereference_VB() => + roslynVB.AddPaths("NullPointerDereference.vb").Verify(); + + [TestMethod] + public void NullPointerDereference_Sonar_DoesNotRaiseIssuesForTestProject() => + sonar.AddTestReference().AddPaths("NullPointerDereference.cs").WithConcurrentAnalysis(false).VerifyNoIssues(); + + [TestMethod] + public void NullPointerDereference_Roslyn_DoesNotRaiseIssuesForTestProject() => + roslynCS.AddTestReference().AddPaths("NullPointerDereference.cs").WithConcurrentAnalysis(false).VerifyNoIssues(); + + [TestMethod] + public void NullPointerDereference_Sonar_CSharp6() => + sonar.AddPaths("NullPointerDereference.CSharp6.cs").WithOptions(ParseOptionsHelper.FromCSharp6).Verify(); + + [TestMethod] + public void NullPointerDereference_Roslyn_CSharp6() => + roslynCS.AddPaths("NullPointerDereference.CSharp6.cs").WithOptions(ParseOptionsHelper.FromCSharp6).Verify(); + + [TestMethod] + public void NullPointerDereference_Sonar_CSharp7() => + sonar.AddPaths("NullPointerDereference.CSharp7.cs").WithOptions(ParseOptionsHelper.FromCSharp7).Verify(); + + [TestMethod] + public void NullPointerDereference_Roslyn_CSharp7() => + roslynCS.AddPaths("NullPointerDereference.CSharp7.cs").WithOptions(ParseOptionsHelper.FromCSharp7).Verify(); + + [TestMethod] + public void NullPointerDereference_Sonar_CSharp8() => + sonar.AddPaths("NullPointerDereference.CSharp8.cs").AddReferences(MetadataReferenceFacade.NetStandard21).WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + + [TestMethod] + public void NullPointerDereference_Roslyn_CSharp8() => + roslynCS.AddPaths("NullPointerDereference.CSharp8.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); #if NET - [TestMethod] - public void NullPointerDereference_Roslyn_CSharp8_Nullable() => - roslynCS.AddPaths("NullPointerDereference.CSharp8.Nullable.cs").WithOptions(ParseOptionsHelper.FromCSharp8).WithConcurrentAnalysis(false).Verify(); + [TestMethod] + public void NullPointerDereference_Roslyn_CSharp8_Nullable() => + roslynCS.AddPaths("NullPointerDereference.CSharp8.Nullable.cs").WithOptions(ParseOptionsHelper.FromCSharp8).WithConcurrentAnalysis(false).Verify(); - [TestMethod] - public void NullPointerDereference_Sonar_CSharp9() => - sonar.AddPaths("NullPointerDereference.CSharp9.cs").WithTopLevelStatements().Verify(); + [TestMethod] + public void NullPointerDereference_Sonar_CSharp9() => + sonar.AddPaths("NullPointerDereference.CSharp9.cs").WithTopLevelStatements().Verify(); - [TestMethod] - public void NullPointerDereference_Roslyn_CSharp9() => - roslynCS.AddPaths("NullPointerDereference.CSharp9.cs").WithTopLevelStatements().Verify(); + [TestMethod] + public void NullPointerDereference_Roslyn_CSharp9() => + roslynCS.AddPaths("NullPointerDereference.CSharp9.cs").WithTopLevelStatements().Verify(); - [TestMethod] - public void NullPointerDereference_Sonar_CSharp10() => - sonar.AddPaths("NullPointerDereference.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void NullPointerDereference_Sonar_CSharp10() => + sonar.AddPaths("NullPointerDereference.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).VerifyNoIssues(); - [TestMethod] - public void NullPointerDereference_Roslyn_CSharp10() => - roslynCS.AddPaths("NullPointerDereference.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void NullPointerDereference_Roslyn_CSharp10() => + roslynCS.AddPaths("NullPointerDereference.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); - [TestMethod] - public void NullPointerDereference_Roslyn_CS_NetCore() => - roslynCS.AddPaths("NullPointerDereference.NetCore.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); + [TestMethod] + public void NullPointerDereference_Roslyn_CS_NetCore() => + roslynCS.AddPaths("NullPointerDereference.NetCore.cs").WithOptions(ParseOptionsHelper.FromCSharp8).Verify(); - [TestMethod] - public void NullPointerDereference_Sonar_CSharp11() => - sonar.AddPaths("NullPointerDereference.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void NullPointerDereference_Sonar_CSharp11() => + sonar.AddPaths("NullPointerDereference.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); - [TestMethod] - public void NullPointerDereference_Roslyn_CSharp11() => - roslynCS.AddPaths("NullPointerDereference.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void NullPointerDereference_Roslyn_CSharp11() => + roslynCS.AddPaths("NullPointerDereference.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); #else - [TestMethod] - public void NullPointerDereference_Roslyn_CS_NetFx() => - roslynCS.AddPaths("NullPointerDereference.NetFx.cs").Verify(); + [TestMethod] + public void NullPointerDereference_Roslyn_CS_NetFx() => + roslynCS.AddPaths("NullPointerDereference.NetFx.cs").VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/SymbolicExecutionRunnerTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/SymbolicExecutionRunnerTest.cs index 898120975fa..7d11db516aa 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/SymbolicExecutionRunnerTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/SymbolicExecution/SymbolicExecutionRunnerTest.cs @@ -403,22 +403,31 @@ public void Method() [TestMethod] public void Analyze_Severity_ExecutesWhenMore() => - Verify(@"string s = null; // Noncompliant {{Message for SAll}} - // Noncompliant@-1 {{Message for SMain}} - s.ToString(); // Compliant, should not raise S2259", + Verify(""" + string s = null; // Noncompliant {{Message for SAll}} + // Noncompliant@-1 {{Message for SMain}} + s.ToString(); // Compliant, should not raise S2259 + """, + expectingIssues: true, AllScopeAssignmentRuleCheck.SAll, MainScopeAssignmentRuleCheck.SMain); [TestMethod] public void Analyze_Severity_ExecutesWhenOne() => - Verify(@"string s = null; // Noncompliant {{Message for SMain}} - s.ToString(); // Compliant, should not raise S2259", + Verify(""" + string s = null; // Noncompliant {{Message for SMain}} + s.ToString(); // Compliant, should not raise S2259 + """, + expectingIssues: true, MainScopeAssignmentRuleCheck.SMain); [TestMethod] public void Analyze_Severity_DoesNotExecutesWhenNone() => - Verify(@"string s = null; // Compliant, SMain and SAll are suppressed by test framework, because only 'SAnother' is active - s.ToString(); // Compliant, should not raise S2259", + Verify(""" + string s = null; // Compliant, SMain and SAll are suppressed by test framework, because only 'SAnother' is active + s.ToString(); // Compliant, should not raise S2259 + """, + expectingIssues: false, AnalysisScaffolding.CreateDescriptorMain("SAnother")); [TestMethod] @@ -427,23 +436,25 @@ public void Analyze_ShouldExecute_ExcludesCheckFromExecution() var sut = new ConfigurableSERunnerCS(); sut.RegisterRule(InvocationAssignmentRuleCheck.SInvocation); var builder = new VerifierBuilder().AddAnalyzer(() => sut); - builder.AddSnippet(@" -public class Sample -{ - public void Method() - { - string s = null; // Nothing is raised because InvocationAssignmentRuleCheck.ShouldExecute returns false - } -}").Verify(); - builder.AddSnippet(@" -public class Sample -{ - public void Method() - { - string s = null; // Noncompliant {{Message for SInvocation}} - because invocation is present in the method body - Method(); - } -}").Verify(); + builder.AddSnippet(""" + public class Sample + { + public void Method() + { + string s = null; // Nothing is raised because InvocationAssignmentRuleCheck.ShouldExecute returns false + } + } + """).VerifyNoIssues(); + builder.AddSnippet(""" + public class Sample + { + public void Method() + { + string s = null; // Noncompliant {{Message for SInvocation}} - because invocation is present in the method body + Method(); + } + } + """).Verify(); } [TestMethod] @@ -511,34 +522,36 @@ public class Sample diagnostic.Descriptor.IsEnabledByDefault.Should().BeFalse("we're explicitly activating non-SonarWay rule that is not active by default"); } - private static void Verify(string body, params DiagnosticDescriptor[] onlyRules) => - Verify(body, ProjectType.Product, null, onlyRules); + private static void Verify(string body, bool expectingIssues = true, params DiagnosticDescriptor[] onlyRules) => + Verify(body, ProjectType.Product, null, expectingIssues, onlyRules); - private static void Verify(string body, ProjectType projectType, string sonarProjectConfigPath, params DiagnosticDescriptor[] onlyRules) + private static void Verify(string body, ProjectType projectType, string sonarProjectConfigPath, bool expectingIssues = true, params DiagnosticDescriptor[] onlyRules) { - var code = $@" -using System; -using System.Threading; -public class Sample -{{ - public void Main(bool condition) - {{ - {body} - }} -}}"; - VerifyCode(code, projectType, ParseOptionsHelper.FromCSharp9, sonarProjectConfigPath, OutputKind.DynamicallyLinkedLibrary, onlyRules); + var code = $$""" + using System; + using System.Threading; + public class Sample + { + public void Main(bool condition) + { + {{body}} + } + } + """; + VerifyCode(code, projectType, ParseOptionsHelper.FromCSharp9, sonarProjectConfigPath, OutputKind.DynamicallyLinkedLibrary, expectingIssues, onlyRules); } private static void VerifyClassMainCS(string members) { - var code = -$@"using System; -using System.Linq; -public class Sample -{{ - {members} -}}"; - VerifyCode(code, ProjectType.Product, ParseOptionsHelper.FromCSharp9, null, OutputKind.DynamicallyLinkedLibrary, MainScopeAssignmentRuleCheck.SMain, BinaryRuleCheck.SBinary); + var code = $$""" + using System; + using System.Linq; + public class Sample + { + {{members}} + } + """; + VerifyCode(code, ProjectType.Product, ParseOptionsHelper.FromCSharp9, null, OutputKind.DynamicallyLinkedLibrary, true, MainScopeAssignmentRuleCheck.SMain, BinaryRuleCheck.SBinary); } private static void VerifyTopLevelStatements(string members) @@ -547,16 +560,17 @@ private static void VerifyTopLevelStatements(string members) using System; {members} """; - VerifyCode(code, ProjectType.Product, ParseOptionsHelper.FromCSharp9, null, OutputKind.ConsoleApplication, MainScopeAssignmentRuleCheck.SMain, BinaryRuleCheck.SBinary); + VerifyCode(code, ProjectType.Product, ParseOptionsHelper.FromCSharp9, null, OutputKind.ConsoleApplication, true, MainScopeAssignmentRuleCheck.SMain, BinaryRuleCheck.SBinary); } private static void VerifyClassMainVB(string members) { - var code = -$@"Public Class Sample - {members} -End Class"; - VerifyCode(code, ProjectType.Product, ImmutableArray.Empty, null, OutputKind.DynamicallyLinkedLibrary, MainScopeAssignmentRuleCheck.SMain, BinaryRuleCheck.SBinary); + var code = $""" + Public Class Sample + {members} + End Class + """; + VerifyCode(code, ProjectType.Product, [], null, OutputKind.DynamicallyLinkedLibrary, true, MainScopeAssignmentRuleCheck.SMain, BinaryRuleCheck.SBinary); } private static void VerifyCode(string code, @@ -564,16 +578,26 @@ private static void VerifyClassMainVB(string members) ImmutableArray parseOptions, string sonarProjectConfigPath, OutputKind kind, - params DiagnosticDescriptor[] onlyRules) where TRunner : SymbolicExecutionRunnerBase, new() => - new VerifierBuilder() + bool expectingIssues, + params DiagnosticDescriptor[] onlyRules) where TRunner : SymbolicExecutionRunnerBase, new() + { + var builder = new VerifierBuilder() .AddReferences(TestHelper.ProjectTypeReference(projectType)) .AddSnippet(code) .WithAdditionalFilePath(sonarProjectConfigPath) .WithOptions(parseOptions) .WithOnlyDiagnostics(onlyRules) .WithConcurrentAnalysis(false) - .WithOutputKind(kind) - .Verify(); + .WithOutputKind(kind); + if (expectingIssues) + { + builder.Verify(); + } + else + { + builder.VerifyNoIssues(); + } + } private class TestSERunnerCS : CS.SymbolicExecutionRunner { diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/TaskConfigureAwaitTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/TaskConfigureAwaitTest.cs index 59950340b28..33560924324 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/TaskConfigureAwaitTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/TaskConfigureAwaitTest.cs @@ -21,43 +21,42 @@ using Microsoft.CodeAnalysis.CSharp; using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class TaskConfigureAwaitTest { - [TestClass] - public class TaskConfigureAwaitTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); #if NETFRAMEWORK - [TestMethod] - public void TaskConfigureAwait_NetFx() => - builder.AddPaths("TaskConfigureAwait.NetFx.cs").Verify(); + [TestMethod] + public void TaskConfigureAwait_NetFx() => + builder.AddPaths("TaskConfigureAwait.NetFx.cs").Verify(); #else - [TestMethod] - public void TaskConfigureAwait_NetCore() => - builder.AddPaths("TaskConfigureAwait.NetCore.cs").Verify(); + [TestMethod] + public void TaskConfigureAwait_NetCore() => + builder.AddPaths("TaskConfigureAwait.NetCore.cs").VerifyNoIssues(); #endif - [TestMethod] - public void TaskConfigureAwait_ConsoleApp() - { - const string code = @" + [TestMethod] + public void TaskConfigureAwait_ConsoleApp() + { + const string code = @" using System.Threading.Tasks; public static class EntryPoint { public async static Task Main() => await Task.Delay(1000); // Compliant }"; - var projectBuilder = SolutionBuilder.Create().AddProject(AnalyzerLanguage.CSharp).AddSnippet(code); - var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication); - var analyzer = new TaskConfigureAwait(); - var compilation = projectBuilder.GetCompilation(null, compilationOptions); + var projectBuilder = SolutionBuilder.Create().AddProject(AnalyzerLanguage.CSharp).AddSnippet(code); + var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication); + var analyzer = new TaskConfigureAwait(); + var compilation = projectBuilder.GetCompilation(null, compilationOptions); - DiagnosticVerifier.Verify(compilation, analyzer); - } + DiagnosticVerifier.Verify(compilation, analyzer); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/TestMethodShouldContainAssertionTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/TestMethodShouldContainAssertionTest.cs index f250933113e..1f5c0596460 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/TestMethodShouldContainAssertionTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/TestMethodShouldContainAssertionTest.cs @@ -21,105 +21,86 @@ using SonarAnalyzer.Rules.CSharp; using SonarAnalyzer.Test.Common; -namespace SonarAnalyzer.Test.Rules -{ - [TestClass] - public class TestMethodShouldContainAssertionTest - { - private const string Latest = Constants.NuGetLatestVersion; // Rename only - - private static class FluentAssertionVersions - { - public const string Ver1 = "1.6.0"; - public const string Ver4 = "4.19.4"; - public const string Ver5 = "5.9.0"; - } - - private static class MsTestVersions - { - public const string Ver1 = "1.1.11"; - } - - private static class NUnitVersions - { - public const string Ver3 = "3.11.0"; - public const string Ver3Latest = "3.14.0"; - public const string Ver25 = "2.5.7.10213"; - public const string Ver27 = "2.7.0"; - } - - private readonly VerifierBuilder builder = new VerifierBuilder(); - - [DataTestMethod] - [DataRow(MsTestVersions.Ver1)] - [DataRow(Latest)] - public void TestMethodShouldContainAssertion_MSTest(string testFwkVersion) => - WithTestReferences(NuGetMetadataReference.MSTestTestFramework(testFwkVersion)) - .AddPaths("TestMethodShouldContainAssertion.MsTest.cs", "TestMethodShouldContainAssertion.MsTest.AnotherFile.cs") - .Verify(); - - [DataTestMethod] - [DataRow(NUnitVersions.Ver3, Latest, Latest)] - [DataRow(NUnitVersions.Ver3Latest, FluentAssertionVersions.Ver5, Latest)] // Breaking changes in NUnit 4.0 would fail the test https://github.com/SonarSource/sonar-dotnet/issues/8409 - [DataRow(NUnitVersions.Ver3Latest, Latest, Latest)] // Breaking changes in NUnit 4.0 would fail the test https://github.com/SonarSource/sonar-dotnet/issues/8409 - public void TestMethodShouldContainAssertion_NUnit(string testFwkVersion, string fluentVersion, string nSubstituteVersion) => - WithTestReferences(NuGetMetadataReference.NUnit(testFwkVersion), fluentVersion, nSubstituteVersion).AddPaths("TestMethodShouldContainAssertion.NUnit.cs").Verify(); - - [DataTestMethod] - [DataRow(NUnitVersions.Ver25)] - [DataRow(NUnitVersions.Ver27)] - public void TestMethodShouldContainAssertion_NUnit_V2Specific(string testFwkVersion) => - WithTestReferences(NuGetMetadataReference.NUnit(testFwkVersion)).AddSnippet(@" -using System; -using NUnit.Framework; +namespace SonarAnalyzer.Test.Rules; -[TestFixture] -public class Foo +[TestClass] +public class TestMethodShouldContainAssertionTest { - [TestCase] - [ExpectedException(typeof(Exception))] - public void TestCase4() - { - var x = System.IO.File.Open("""", System.IO.FileMode.Open); - } - - [Theory] - [ExpectedException(typeof(Exception))] - public void Theory4() - { - var x = System.IO.File.Open("""", System.IO.FileMode.Open); - } - - [TestCaseSource(""Foo"")] - [ExpectedException(typeof(Exception))] - public void TestCaseSource4() - { - var x = System.IO.File.Open("""", System.IO.FileMode.Open); - } - - [Test] - [ExpectedException(typeof(Exception))] - public void Test4() - { - var x = System.IO.File.Open("""", System.IO.FileMode.Open); - } -}").Verify(); - - [DataTestMethod] - [DataRow(XUnitVersions.Ver2, Latest, Latest)] - [DataRow(XUnitVersions.Ver253, Latest, Latest)] - public void TestMethodShouldContainAssertion_Xunit(string testFwkVersion, string fluentVersion, string nSubstituteVersion) => - WithTestReferences(NuGetMetadataReference.XunitFramework(testFwkVersion), fluentVersion, nSubstituteVersion).AddPaths("TestMethodShouldContainAssertion.Xunit.cs").Verify(); - - [TestMethod] - public void TestMethodShouldContainAssertion_Xunit_Legacy() => - WithTestReferences(NuGetMetadataReference.XunitFrameworkV1).AddPaths("TestMethodShouldContainAssertion.Xunit.Legacy.cs").Verify(); - - [DataTestMethod] - [DataRow(NUnitVersions.Ver25, FluentAssertionVersions.Ver1)] - [DataRow(NUnitVersions.Ver25, FluentAssertionVersions.Ver4)] - public void TestMethodShouldContainAssertion_NUnit_FluentAssertionsLegacy(string testFwkVersion, string fluentVersion) => - WithTestReferences(NuGetMetadataReference.NUnit(testFwkVersion), fluentVersion).AddSnippet(@" + private const string Latest = Constants.NuGetLatestVersion; // Rename only + + private readonly VerifierBuilder builder = new VerifierBuilder(); + + [DataTestMethod] + [DataRow(MsTestVersions.Ver1)] + [DataRow(Latest)] + public void TestMethodShouldContainAssertion_MSTest(string testFwkVersion) => + WithTestReferences(NuGetMetadataReference.MSTestTestFramework(testFwkVersion)) + .AddPaths("TestMethodShouldContainAssertion.MsTest.cs", "TestMethodShouldContainAssertion.MsTest.AnotherFile.cs") + .Verify(); + + [DataTestMethod] + [DataRow(NUnitVersions.Ver3, Latest, Latest)] + [DataRow(NUnitVersions.Ver3Latest, FluentAssertionVersions.Ver5, Latest)] // Breaking changes in NUnit 4.0 would fail the test https://github.com/SonarSource/sonar-dotnet/issues/8409 + [DataRow(NUnitVersions.Ver3Latest, Latest, Latest)] // Breaking changes in NUnit 4.0 would fail the test https://github.com/SonarSource/sonar-dotnet/issues/8409 + public void TestMethodShouldContainAssertion_NUnit(string testFwkVersion, string fluentVersion, string nSubstituteVersion) => + WithTestReferences(NuGetMetadataReference.NUnit(testFwkVersion), fluentVersion, nSubstituteVersion).AddPaths("TestMethodShouldContainAssertion.NUnit.cs").Verify(); + + [DataTestMethod] + [DataRow(NUnitVersions.Ver25)] + [DataRow(NUnitVersions.Ver27)] + public void TestMethodShouldContainAssertion_NUnit_V2Specific(string testFwkVersion) => + WithTestReferences(NuGetMetadataReference.NUnit(testFwkVersion)).AddSnippet(""" + using System; + using NUnit.Framework; + + [TestFixture] + public class Foo + { + [TestCase] + [ExpectedException(typeof(Exception))] + public void TestCase4() + { + var x = System.IO.File.Open("", System.IO.FileMode.Open); + } + + [Theory] + [ExpectedException(typeof(Exception))] + public void Theory4() + { + var x = System.IO.File.Open("", System.IO.FileMode.Open); + } + + [TestCaseSource("Foo")] + [ExpectedException(typeof(Exception))] + public void TestCaseSource4() + { + var x = System.IO.File.Open("", System.IO.FileMode.Open); + } + + [Test] + [ExpectedException(typeof(Exception))] + public void Test4() + { + var x = System.IO.File.Open("", System.IO.FileMode.Open); + } + } + """).VerifyNoIssues(); + + [DataTestMethod] + [DataRow(XUnitVersions.Ver2, Latest, Latest)] + [DataRow(XUnitVersions.Ver253, Latest, Latest)] + public void TestMethodShouldContainAssertion_Xunit(string testFwkVersion, string fluentVersion, string nSubstituteVersion) => + WithTestReferences(NuGetMetadataReference.XunitFramework(testFwkVersion), fluentVersion, nSubstituteVersion).AddPaths("TestMethodShouldContainAssertion.Xunit.cs").Verify(); + + [TestMethod] + public void TestMethodShouldContainAssertion_Xunit_Legacy() => + WithTestReferences(NuGetMetadataReference.XunitFrameworkV1).AddPaths("TestMethodShouldContainAssertion.Xunit.Legacy.cs").Verify(); + + [DataTestMethod] + [DataRow(NUnitVersions.Ver25, FluentAssertionVersions.Ver1)] + [DataRow(NUnitVersions.Ver25, FluentAssertionVersions.Ver4)] + public void TestMethodShouldContainAssertion_NUnit_FluentAssertionsLegacy(string testFwkVersion, string fluentVersion) => + WithTestReferences(NuGetMetadataReference.NUnit(testFwkVersion), fluentVersion).AddSnippet(@" using System; using FluentAssertions; using NUnit.Framework; @@ -148,62 +129,82 @@ public void ShouldNotThrowTest() } }").Verify(); - [TestMethod] - public void TestMethodShouldContainAssertion_NUnit_NFluentLegacy() => - WithTestReferences(NuGetMetadataReference.NUnit(NUnitVersions.Ver25), nFluentVersion: "1.3.1").AddSnippet(@" -using System; -using NFluent; -using NUnit.Framework; - -[TestFixture] -public class Foo -{ - [Test] - public void Test1() - { - throw new NFluent.FluentCheckException(""You failed me!""); - } -}").Verify(); - - [TestMethod] - public void TestMethodShouldContainAssertion_CustomAssertionMethod() => - builder.AddPaths("TestMethodShouldContainAssertion.Custom.cs").AddReferences(NuGetMetadataReference.MSTestTestFramework(Latest)).Verify(); + [TestMethod] + public void TestMethodShouldContainAssertion_NUnit_NFluentLegacy() => + WithTestReferences(NuGetMetadataReference.NUnit(NUnitVersions.Ver25), nFluentVersion: "1.3.1").AddSnippet(""" + using System; + using NFluent; + using NUnit.Framework; + + [TestFixture] + public class Foo + { + [Test] + public void Test1() + { + throw new NFluent.FluentCheckException("You failed me!"); + } + } + """).VerifyNoIssues(); + + [TestMethod] + public void TestMethodShouldContainAssertion_CustomAssertionMethod() => + builder.AddPaths("TestMethodShouldContainAssertion.Custom.cs").AddReferences(NuGetMetadataReference.MSTestTestFramework(Latest)).Verify(); #if NET - [TestMethod] - public void TestMethodShouldContainAssertion_CSharp9() => - builder.AddPaths("TestMethodShouldContainAssertion.CSharp9.cs") - .AddReferences(NuGetMetadataReference.MSTestTestFrameworkV1) - .AddReferences(NuGetMetadataReference.XunitFramework(Latest)) - .AddReferences(NuGetMetadataReference.NUnit(Latest)) - .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); - - [TestMethod] - public void TestMethodShouldContainAssertion_CSharp11() => - builder.AddPaths("TestMethodShouldContainAssertion.CSharp11.cs") - .AddReferences(NuGetMetadataReference.MSTestTestFrameworkV1) - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void TestMethodShouldContainAssertion_CSharp9() => + builder.AddPaths("TestMethodShouldContainAssertion.CSharp9.cs") + .AddReferences(NuGetMetadataReference.MSTestTestFrameworkV1) + .AddReferences(NuGetMetadataReference.XunitFramework(Latest)) + .AddReferences(NuGetMetadataReference.NUnit(Latest)) + .WithOptions(ParseOptionsHelper.FromCSharp9) + .Verify(); + + [TestMethod] + public void TestMethodShouldContainAssertion_CSharp11() => + builder.AddPaths("TestMethodShouldContainAssertion.CSharp11.cs") + .AddReferences(NuGetMetadataReference.MSTestTestFrameworkV1) + .WithOptions(ParseOptionsHelper.FromCSharp11) + .Verify(); #endif - internal static VerifierBuilder WithTestReferences(IEnumerable testFrameworkReference, - string fluentVersion = Latest, - string nSubstituteVersion = Latest, - string nFluentVersion = Latest, - string shouldlyVersion = Latest) => - new VerifierBuilder() - .AddReferences(testFrameworkReference) - .AddReferences(NuGetMetadataReference.FluentAssertions(fluentVersion)) - .AddReferences(NuGetMetadataReference.NSubstitute(nSubstituteVersion)) - .AddReferences(NuGetMetadataReference.NFluent(nFluentVersion)) - .AddReferences(NuGetMetadataReference.Shouldly(shouldlyVersion)) - .AddReferences(MetadataReferenceFacade.SystemData) - .AddReferences(MetadataReferenceFacade.SystemNetHttp) - .AddReferences(MetadataReferenceFacade.SystemXml) - .AddReferences(MetadataReferenceFacade.SystemXmlLinq) - .AddReferences(MetadataReferenceFacade.SystemThreadingTasks); + internal static VerifierBuilder WithTestReferences(IEnumerable testFrameworkReference, + string fluentVersion = Latest, + string nSubstituteVersion = Latest, + string nFluentVersion = Latest, + string shouldlyVersion = Latest) => + new VerifierBuilder() + .AddReferences(testFrameworkReference) + .AddReferences(NuGetMetadataReference.FluentAssertions(fluentVersion)) + .AddReferences(NuGetMetadataReference.NSubstitute(nSubstituteVersion)) + .AddReferences(NuGetMetadataReference.NFluent(nFluentVersion)) + .AddReferences(NuGetMetadataReference.Shouldly(shouldlyVersion)) + .AddReferences(MetadataReferenceFacade.SystemData) + .AddReferences(MetadataReferenceFacade.SystemNetHttp) + .AddReferences(MetadataReferenceFacade.SystemXml) + .AddReferences(MetadataReferenceFacade.SystemXmlLinq) + .AddReferences(MetadataReferenceFacade.SystemThreadingTasks); + + private static class FluentAssertionVersions + { + public const string Ver1 = "1.6.0"; + public const string Ver4 = "4.19.4"; + public const string Ver5 = "5.9.0"; + } + + private static class MsTestVersions + { + public const string Ver1 = "1.1.11"; + } + + private static class NUnitVersions + { + public const string Ver3 = "3.11.0"; + public const string Ver3Latest = "3.14.0"; + public const string Ver25 = "2.5.7.10213"; + public const string Ver27 = "2.7.0"; } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/TestMethodShouldNotBeIgnoredTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/TestMethodShouldNotBeIgnoredTest.cs index 4af3c9fc044..16f9917e669 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/TestMethodShouldNotBeIgnoredTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/TestMethodShouldNotBeIgnoredTest.cs @@ -20,86 +20,84 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class TestMethodShouldNotBeIgnoredTest { - [TestClass] - public class TestMethodShouldNotBeIgnoredTest - { - private readonly VerifierBuilder builder = new VerifierBuilder().AddReferences(NuGetMetadataReference.MSTestTestFrameworkV1); - - [TestMethod] - public void TestMethodShouldNotBeIgnored_MsTest_Legacy() => - builder.AddPaths("TestMethodShouldNotBeIgnored.MsTest.cs") - .WithErrorBehavior(CompilationErrorBehavior.Ignore) // IgnoreAttribute doesn't contain any reason param - .Verify(); - - [DataTestMethod] - [DataRow("1.2.0")] - [DataRow(Constants.NuGetLatestVersion)] - public void TestMethodShouldNotBeIgnored_MsTest(string testFwkVersion) => - new VerifierBuilder() - .AddPaths("TestMethodShouldNotBeIgnored.MsTest.cs") - .AddReferences(NuGetMetadataReference.MSTestTestFramework(testFwkVersion)).Verify(); - - [TestMethod] - public void TestMethodShouldNotBeIgnored_MsTest_InvalidCases() => - builder.AddSnippet(""" - using Microsoft.VisualStudio.TestTools.UnitTesting; - namespace Tests.Diagnostics.TestMethods - { - [ThisDoesNotExist] - public class MsTestClass3 - { - } + private readonly VerifierBuilder builder = new VerifierBuilder().AddReferences(NuGetMetadataReference.MSTestTestFrameworkV1); + + [TestMethod] + public void TestMethodShouldNotBeIgnored_MsTest_Legacy() => + builder.AddPaths("TestMethodShouldNotBeIgnored.MsTest.cs") + .WithErrorBehavior(CompilationErrorBehavior.Ignore) // IgnoreAttribute doesn't contain any reason param + .Verify(); - [Ignore] + [DataTestMethod] + [DataRow("1.2.0")] + [DataRow(Constants.NuGetLatestVersion)] + public void TestMethodShouldNotBeIgnored_MsTest(string testFwkVersion) => + new VerifierBuilder() + .AddPaths("TestMethodShouldNotBeIgnored.MsTest.cs") + .AddReferences(NuGetMetadataReference.MSTestTestFramework(testFwkVersion)).Verify(); + + [TestMethod] + public void TestMethodShouldNotBeIgnored_MsTest_InvalidCases() => + builder.AddSnippet(""" + using Microsoft.VisualStudio.TestTools.UnitTesting; + namespace Tests.Diagnostics.TestMethods + { + [ThisDoesNotExist] + public class MsTestClass3 + { } - """) - .WithErrorBehavior(CompilationErrorBehavior.Ignore) // IgnoreAttribute doesn't contain any reason param - .Verify(); - - [DataTestMethod] - [DataRow("2.5.7.10213")] - [DataRow("2.7.0")] - public void TestMethodShouldNotBeIgnored_NUnit_V2(string testFwkVersion) => - builder.AddPaths("TestMethodShouldNotBeIgnored.NUnit.V2.cs") - .AddReferences(NuGetMetadataReference.NUnit(testFwkVersion)) - .Verify(); - - [DataTestMethod] - [DataRow("3.0.0")] // Ignore without reason no longer exist - [DataRow(Constants.NuGetLatestVersion)] - public void TestMethodShouldNotBeIgnored_NUnit(string testFwkVersion) => - builder.AddPaths("TestMethodShouldNotBeIgnored.NUnit.cs").AddReferences(NuGetMetadataReference.NUnit(testFwkVersion)).Verify(); - - [DataTestMethod] - [DataRow("2.0.0")] - [DataRow(Constants.NuGetLatestVersion)] - public void TestMethodShouldNotBeIgnored_Xunit(string testFwkVersion) => - builder.AddPaths("TestMethodShouldNotBeIgnored.Xunit.cs").AddReferences(NuGetMetadataReference.XunitFramework(testFwkVersion)).Verify(); - - [TestMethod] - public void TestMethodShouldNotBeIgnored_Xunit_v1() => - builder.AddPaths("TestMethodShouldNotBeIgnored.Xunit.v1.cs").AddReferences(NuGetMetadataReference.XunitFrameworkV1).Verify(); + + [Ignore] + } + """) + .VerifyNoIssuesIgnoreErrors(); + + [DataTestMethod] + [DataRow("2.5.7.10213")] + [DataRow("2.7.0")] + public void TestMethodShouldNotBeIgnored_NUnit_V2(string testFwkVersion) => + builder.AddPaths("TestMethodShouldNotBeIgnored.NUnit.V2.cs") + .AddReferences(NuGetMetadataReference.NUnit(testFwkVersion)) + .Verify(); + + [DataTestMethod] + [DataRow("3.0.0")] // Ignore without reason no longer exist + [DataRow(Constants.NuGetLatestVersion)] + public void TestMethodShouldNotBeIgnored_NUnit(string testFwkVersion) => + builder.AddPaths("TestMethodShouldNotBeIgnored.NUnit.cs").AddReferences(NuGetMetadataReference.NUnit(testFwkVersion)).Verify(); + + [DataTestMethod] + [DataRow("2.0.0")] + [DataRow(Constants.NuGetLatestVersion)] + public void TestMethodShouldNotBeIgnored_Xunit(string testFwkVersion) => + builder.AddPaths("TestMethodShouldNotBeIgnored.Xunit.cs").AddReferences(NuGetMetadataReference.XunitFramework(testFwkVersion)).VerifyNoIssues(); + + [TestMethod] + public void TestMethodShouldNotBeIgnored_Xunit_v1() => + builder.AddPaths("TestMethodShouldNotBeIgnored.Xunit.v1.cs").AddReferences(NuGetMetadataReference.XunitFrameworkV1).VerifyNoIssues(); #if NET - [TestMethod] - public void TestMethodShouldNotBeIgnored_CSharp9() => - builder.AddPaths("TestMethodShouldNotBeIgnored.CSharp9.cs") - .AddReferences(NuGetMetadataReference.XunitFrameworkV1) - .AddReferences(NuGetMetadataReference.NUnit(Constants.NuGetLatestVersion)) - .WithOptions(ParseOptionsHelper.FromCSharp9) - .Verify(); - - [TestMethod] - public void TestMethodShouldNotBeIgnored_CSharp11() => - builder.AddPaths("TestMethodShouldNotBeIgnored.CSharp11.cs") - .AddReferences(NuGetMetadataReference.MSTestTestFramework(Constants.NuGetLatestVersion)) - .WithOptions(ParseOptionsHelper.FromCSharp11) - .Verify(); + [TestMethod] + public void TestMethodShouldNotBeIgnored_CSharp9() => + builder.AddPaths("TestMethodShouldNotBeIgnored.CSharp9.cs") + .AddReferences(NuGetMetadataReference.XunitFrameworkV1) + .AddReferences(NuGetMetadataReference.NUnit(Constants.NuGetLatestVersion)) + .WithOptions(ParseOptionsHelper.FromCSharp9) + .Verify(); + + [TestMethod] + public void TestMethodShouldNotBeIgnored_CSharp11() => + builder.AddPaths("TestMethodShouldNotBeIgnored.CSharp11.cs") + .AddReferences(NuGetMetadataReference.MSTestTestFramework(Constants.NuGetLatestVersion)) + .WithOptions(ParseOptionsHelper.FromCSharp11) + .Verify(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ToStringShouldNotReturnNullTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ToStringShouldNotReturnNullTest.cs index 1ab124d430f..1cb8c11e4fe 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ToStringShouldNotReturnNullTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ToStringShouldNotReturnNullTest.cs @@ -48,7 +48,7 @@ public class ToStringShouldNotReturnNullTest builderCS .WithOptions(ParseOptionsHelper.FromCSharp11) .AddPaths("ToStringShouldNotReturnNull.CSharp11.cs") - .Verify(); + .VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/TypeMemberVisibilityTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/TypeMemberVisibilityTest.cs index 36b232520bc..35661b846ad 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/TypeMemberVisibilityTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/TypeMemberVisibilityTest.cs @@ -20,32 +20,31 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class TypeMemberVisibilityTest { - [TestClass] - public class TypeMemberVisibilityTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void TypeMemberVisibility_CS() => - builder.AddPaths("TypeMemberVisibility.cs").Verify(); + [TestMethod] + public void TypeMemberVisibility_CS() => + builder.AddPaths("TypeMemberVisibility.cs").Verify(); #if NET - [TestMethod] - public void TypeMemberVisibility_CSharp9() => - builder.AddPaths("TypeMemberVisibility.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + [TestMethod] + public void TypeMemberVisibility_CSharp9() => + builder.AddPaths("TypeMemberVisibility.CSharp9.cs").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); - [TestMethod] - public void TypeMemberVisibility_CSharp10() => - builder.AddPaths("TypeMemberVisibility.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + [TestMethod] + public void TypeMemberVisibility_CSharp10() => + builder.AddPaths("TypeMemberVisibility.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); - [TestMethod] - public void TypeMemberVisibility_CSharp11() => - builder.AddPaths("TypeMemberVisibility.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).Verify(); + [TestMethod] + public void TypeMemberVisibility_CSharp11() => + builder.AddPaths("TypeMemberVisibility.CSharp11.cs").WithOptions(ParseOptionsHelper.FromCSharp11).VerifyNoIssues(); #endif - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UnchangedLocalVariablesShouldBeConstTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UnchangedLocalVariablesShouldBeConstTest.cs index 58f93bb7364..d5f92369c27 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UnchangedLocalVariablesShouldBeConstTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UnchangedLocalVariablesShouldBeConstTest.cs @@ -57,18 +57,19 @@ public class UnchangedLocalVariablesShouldBeConstTest [TestMethod] public void UnchangedLocalVariablesShouldBeConst_InvalidCode() => - verifier.AddSnippet(@" -// invalid code -public void Test_TypeThatCannotBeConst(int arg) -{ - System.Random random = 1; -} + verifier.AddSnippet(""" + // invalid code + public void Test_TypeThatCannotBeConst(int arg) + { + System.Random random = 1; + } -// invalid code -public void (int arg) -{ - int intVar = 1; -}").WithErrorBehavior(CompilationErrorBehavior.Ignore).Verify(); + // invalid code + public void (int arg) + { + int intVar = 1; + } + """).VerifyNoIssuesIgnoreErrors(); [TestMethod] public void UnchangedLocalVariablesShouldBeConst_Fix() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UnnecessaryUsingsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UnnecessaryUsingsTest.cs index 35b4812188f..52b6157a309 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UnnecessaryUsingsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UnnecessaryUsingsTest.cs @@ -21,147 +21,146 @@ using Microsoft.CodeAnalysis.CSharp; using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class UnnecessaryUsingsTest { - [TestClass] - public class UnnecessaryUsingsTest - { - private readonly VerifierBuilder builder = new VerifierBuilder() - .AddReferences(MetadataReferenceFacade.MicrosoftWin32Primitives) - .AddReferences(MetadataReferenceFacade.SystemSecurityCryptography); + private readonly VerifierBuilder builder = new VerifierBuilder() + .AddReferences(MetadataReferenceFacade.MicrosoftWin32Primitives) + .AddReferences(MetadataReferenceFacade.SystemSecurityCryptography); - public TestContext TestContext { get; set; } + public TestContext TestContext { get; set; } - [TestMethod] - public void UnnecessaryUsings() => - builder.AddPaths("UnnecessaryUsings.cs", "UnnecessaryUsings2.cs", "UnnecessaryUsingsFNRepro.cs").WithAutogenerateConcurrentFiles(false).Verify(); + [TestMethod] + public void UnnecessaryUsings() => + builder.AddPaths("UnnecessaryUsings.cs", "UnnecessaryUsings2.cs", "UnnecessaryUsingsFNRepro.cs").WithAutogenerateConcurrentFiles(false).Verify(); - [TestMethod] - public void UnnecessaryUsings_InheritedProperty() => - builder.AddPaths("UnnecessaryUsings.InheritedPropertyBase.cs", "UnnecessaryUsings.InheritedPropertyChild.cs", "UnnecessaryUsings.InheritedPropertyUsage.cs") - .WithAutogenerateConcurrentFiles(false) - .Verify(); + [TestMethod] + public void UnnecessaryUsings_InheritedProperty() => + builder.AddPaths("UnnecessaryUsings.InheritedPropertyBase.cs", "UnnecessaryUsings.InheritedPropertyChild.cs", "UnnecessaryUsings.InheritedPropertyUsage.cs") + .WithAutogenerateConcurrentFiles(false) + .VerifyNoIssues(); #if NET - [TestMethod] - public void UnnecessaryUsings_CSharp10_GlobalUsings() => - builder.AddPaths("UnnecessaryUsings.CSharp10.Global.cs", "UnnecessaryUsings.CSharp10.Consumer.cs").WithTopLevelStatements().WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); - - [DataTestMethod] - [DataRow("_ViewImports.cshtml")] - [DataRow("_viewimports.cshtml")] - [DataRow("_viEwiMpoRts.cshtml")] - public void UnnecessaryUsings_RazorViewImportsCshtmlFile_NoIssueReported(string fileName) => - builder - .AddSnippet(@"@using System.Text.Json;", fileName) - .AddReferences(NuGetMetadataReference.SystemTextJson("7.0.4")) - .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) - .VerifyNoIssues(); - - [DataTestMethod] - [DataRow("_Imports.razor")] - [DataRow("_imports.razor")] - [DataRow("_iMpoRts.razor")] - public void UnnecessaryUsings_RazorImportsRazorFile_NoIssueReported(string fileName) => - builder - .AddSnippet(@"@using System.Text.Json;", fileName) - .AddReferences(NuGetMetadataReference.SystemTextJson("7.0.4")) - .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) - .VerifyNoIssues(); - - [DataTestMethod] - [DataRow("RandomFile_ViewImports.cshtml")] - [DataRow("RandomFile_Imports.cshtml")] - [DataRow("_Imports.cshtml")] - public void UnnecessaryUsings_RazorViewImportsSimilarCshtmlFile_IssuesReported(string fileName) => - builder - .AddSnippet("@using System.Linq;", "_ViewImports.cshtml") - .AddSnippet(@"@using System.Text.Json; @* Noncompliant *@", fileName) - .AddReferences(NuGetMetadataReference.SystemTextJson("7.0.4")) - .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) - .Verify(); - - [DataTestMethod] - [DataRow("RandomFile_ViewImports.razor")] - [DataRow("RandomFile_Imports.razor")] - [DataRow("_ViewImports.razor")] - public void UnnecessaryUsings_RazorViewImportsSimilarRazorFile_IssuesReported(string fileName) => - builder - .AddSnippet("@using System.Linq;", "_Imports.razor") - .AddSnippet(@"@using System.Text.Json; @* Noncompliant *@", fileName) - .AddReferences(NuGetMetadataReference.SystemTextJson("7.0.4")) - .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) - .Verify(); - - [DataTestMethod] - [DataRow("_ViewImports.cs")] - [DataRow("_Imports.cs")] - public void UnnecessaryUsings_RazorViewImportsSimilarCSFile_IssuesReported(string fileName) => - builder.AddSnippet(@"using System.Text; // Noncompliant", fileName).Verify(); - - [TestMethod] - public void UnnecessaryUsings_CSharp10_FileScopedNamespace() => - builder.AddPaths("UnnecessaryUsings.CSharp10.FileScopedNamespace.cs").WithOptions(ParseOptionsHelper.FromCSharp10).WithConcurrentAnalysis(false).Verify(); - - [TestMethod] - public void UnnecessaryUsings_CodeFix_CSharp10_FileScopedNamespace() => - builder.AddPaths("UnnecessaryUsings.CSharp10.FileScopedNamespace.cs") - .WithOptions(ParseOptionsHelper.FromCSharp10) - .WithCodeFix() - .WithCodeFixedPaths("UnnecessaryUsings.CSharp10.FileScopedNamespace.Fixed.cs") - .VerifyCodeFix(); - - [TestMethod] - public void UnnecessaryUsings_CSharp9() => - builder.AddPaths("UnnecessaryUsings.CSharp9.cs").WithTopLevelStatements().Verify(); - - [TestMethod] - public void UnnecessaryUsings_TupleDeconstruct_NetCore() => - builder.AddPaths("UnnecessaryUsings.TupleDeconstruct.NetCore.cs").Verify(); - - [TestMethod] - public void UnnecessaryUsings_CSharp12() => - builder.AddPaths("UnnecessaryUsings.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + [TestMethod] + public void UnnecessaryUsings_CSharp10_GlobalUsings() => + builder.AddPaths("UnnecessaryUsings.CSharp10.Global.cs", "UnnecessaryUsings.CSharp10.Consumer.cs").WithTopLevelStatements().WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + + [DataTestMethod] + [DataRow("_ViewImports.cshtml")] + [DataRow("_viewimports.cshtml")] + [DataRow("_viEwiMpoRts.cshtml")] + public void UnnecessaryUsings_RazorViewImportsCshtmlFile_NoIssueReported(string fileName) => + builder + .AddSnippet(@"@using System.Text.Json;", fileName) + .AddReferences(NuGetMetadataReference.SystemTextJson("7.0.4")) + .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) + .VerifyNoIssues(); + + [DataTestMethod] + [DataRow("_Imports.razor")] + [DataRow("_imports.razor")] + [DataRow("_iMpoRts.razor")] + public void UnnecessaryUsings_RazorImportsRazorFile_NoIssueReported(string fileName) => + builder + .AddSnippet(@"@using System.Text.Json;", fileName) + .AddReferences(NuGetMetadataReference.SystemTextJson("7.0.4")) + .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) + .VerifyNoIssues(); + + [DataTestMethod] + [DataRow("RandomFile_ViewImports.cshtml")] + [DataRow("RandomFile_Imports.cshtml")] + [DataRow("_Imports.cshtml")] + public void UnnecessaryUsings_RazorViewImportsSimilarCshtmlFile_IssuesReported(string fileName) => + builder + .AddSnippet("@using System.Linq;", "_ViewImports.cshtml") + .AddSnippet(@"@using System.Text.Json; @* Noncompliant *@", fileName) + .AddReferences(NuGetMetadataReference.SystemTextJson("7.0.4")) + .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) + .Verify(); + + [DataTestMethod] + [DataRow("RandomFile_ViewImports.razor")] + [DataRow("RandomFile_Imports.razor")] + [DataRow("_ViewImports.razor")] + public void UnnecessaryUsings_RazorViewImportsSimilarRazorFile_IssuesReported(string fileName) => + builder + .AddSnippet("@using System.Linq;", "_Imports.razor") + .AddSnippet(@"@using System.Text.Json; @* Noncompliant *@", fileName) + .AddReferences(NuGetMetadataReference.SystemTextJson("7.0.4")) + .WithAdditionalFilePath(AnalysisScaffolding.CreateSonarProjectConfig(TestContext, ProjectType.Product)) + .Verify(); + + [DataTestMethod] + [DataRow("_ViewImports.cs")] + [DataRow("_Imports.cs")] + public void UnnecessaryUsings_RazorViewImportsSimilarCSFile_IssuesReported(string fileName) => + builder.AddSnippet(@"using System.Text; // Noncompliant", fileName).Verify(); + + [TestMethod] + public void UnnecessaryUsings_CSharp10_FileScopedNamespace() => + builder.AddPaths("UnnecessaryUsings.CSharp10.FileScopedNamespace.cs").WithOptions(ParseOptionsHelper.FromCSharp10).WithConcurrentAnalysis(false).Verify(); + + [TestMethod] + public void UnnecessaryUsings_CodeFix_CSharp10_FileScopedNamespace() => + builder.AddPaths("UnnecessaryUsings.CSharp10.FileScopedNamespace.cs") + .WithOptions(ParseOptionsHelper.FromCSharp10) + .WithCodeFix() + .WithCodeFixedPaths("UnnecessaryUsings.CSharp10.FileScopedNamespace.Fixed.cs") + .VerifyCodeFix(); + + [TestMethod] + public void UnnecessaryUsings_CSharp9() => + builder.AddPaths("UnnecessaryUsings.CSharp9.cs").WithTopLevelStatements().Verify(); + + [TestMethod] + public void UnnecessaryUsings_TupleDeconstruct_NetCore() => + builder.AddPaths("UnnecessaryUsings.TupleDeconstruct.NetCore.cs").Verify(); + + [TestMethod] + public void UnnecessaryUsings_CSharp12() => + builder.AddPaths("UnnecessaryUsings.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).VerifyNoIssues(); #elif NETFRAMEWORK - [TestMethod] - public void UnnecessaryUsings_TupleDeconstruct_NetFx() => - builder.AddPaths("UnnecessaryUsings.TupleDeconstruct.NetFx.cs").Verify(); + [TestMethod] + public void UnnecessaryUsings_TupleDeconstruct_NetFx() => + builder.AddPaths("UnnecessaryUsings.TupleDeconstruct.NetFx.cs").Verify(); #endif - [TestMethod] - public void UnnecessaryUsings_CodeFix() => - builder.AddPaths("UnnecessaryUsings.cs") - .WithCodeFix() - .WithCodeFixedPaths("UnnecessaryUsings.Fixed.cs", "UnnecessaryUsings.Fixed.Batch.cs") - .VerifyCodeFix(); - - [TestMethod] - public void EquivalentNameSyntax_Equals_Object() - { - var main = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Lorem")); - object same = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Lorem")); - object different = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Ipsum")); - - main.Equals(same).Should().BeTrue(); - main.Equals(null).Should().BeFalse(); - main.Equals("different type").Should().BeFalse(); - main.Equals(different).Should().BeFalse(); - } - - [TestMethod] - public void EquivalentNameSyntax_Equals_EquivalentNameSyntax() - { - var main = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Lorem")); - var same = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Lorem")); - var different = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Ipsum")); - - main.Equals(same).Should().BeTrue(); - main.Equals(null).Should().BeFalse(); - main.Equals(different).Should().BeFalse(); - } + [TestMethod] + public void UnnecessaryUsings_CodeFix() => + builder.AddPaths("UnnecessaryUsings.cs") + .WithCodeFix() + .WithCodeFixedPaths("UnnecessaryUsings.Fixed.cs", "UnnecessaryUsings.Fixed.Batch.cs") + .VerifyCodeFix(); + + [TestMethod] + public void EquivalentNameSyntax_Equals_Object() + { + var main = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Lorem")); + object same = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Lorem")); + object different = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Ipsum")); + + main.Equals(same).Should().BeTrue(); + main.Equals(null).Should().BeFalse(); + main.Equals("different type").Should().BeFalse(); + main.Equals(different).Should().BeFalse(); + } + + [TestMethod] + public void EquivalentNameSyntax_Equals_EquivalentNameSyntax() + { + var main = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Lorem")); + var same = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Lorem")); + var different = new EquivalentNameSyntax(SyntaxFactory.IdentifierName("Ipsum")); + + main.Equals(same).Should().BeTrue(); + main.Equals(null).Should().BeFalse(); + main.Equals(different).Should().BeFalse(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Constructors.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Constructors.cs index 9310c6fa3e2..188d0f74ac0 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Constructors.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Constructors.cs @@ -64,33 +64,34 @@ public class InnerPublicClass [TestMethod] public void UnusedPrivateMember_Constructor_DirectReferences() => - builder.AddSnippet(@" -public abstract class PrivateConstructors -{ - public class Constructor1 - { - public static readonly Constructor1 Instance = new Constructor1(); - private Constructor1() { var x = 5; } - } - - public class Constructor2 - { - public Constructor2(int a) { } - private Constructor2() { var x = 5; } // Compliant - FN - } - - public class Constructor3 - { - public Constructor3(int a) : this() { } - private Constructor3() { var x = 5; } - } - - public class Constructor4 - { - static Constructor4() { var x = 5; } - } -} -").Verify(); + builder.AddSnippet(""" + public abstract class PrivateConstructors + { + public class Constructor1 + { + public static readonly Constructor1 Instance = new Constructor1(); + private Constructor1() { var x = 5; } + } + + public class Constructor2 + { + public Constructor2(int a) { } + private Constructor2() { var x = 5; } // Compliant - FN + } + + public class Constructor3 + { + public Constructor3(int a) : this() { } + private Constructor3() { var x = 5; } + } + + public class Constructor4 + { + static Constructor4() { var x = 5; } + } + } + + """).VerifyNoIssues(); [TestMethod] public void UnusedPrivateMember_Constructor_Inheritance() => @@ -122,12 +123,13 @@ private class DerivedClass2 : BaseClass2 // Noncompliant {{Remove the unused pri [TestMethod] public void UnusedPrivateMember_Empty_Constructors() => - builder.AddSnippet(@" -public class PrivateConstructors -{ - private PrivateConstructors(int i) { } // Compliant, empty ctors are reported from another rule -} -").Verify(); + builder.AddSnippet(""" + public class PrivateConstructors + { + private PrivateConstructors(int i) { } // Compliant, empty ctors are reported from another rule + } + + """).VerifyNoIssues(); [TestMethod] public void UnusedPrivateMember_Illegal_Interface_Constructor() => @@ -164,19 +166,20 @@ private class Foo // Noncompliant [TestMethod] public void UnusedPrivateMember_RecordPositionalConstructor() => - builder.AddSnippet(@" -// https://github.com/SonarSource/sonar-dotnet/issues/5381 -public abstract record Foo -{ - Foo(string value) - { - Value = value; - } - - public string Value { get; } - - public sealed record Bar(string Value) : Foo(Value); -}").WithOptions(ParseOptionsHelper.FromCSharp9).Verify(); + builder.AddSnippet(""" + // https://github.com/SonarSource/sonar-dotnet/issues/5381 + public abstract record Foo + { + Foo(string value) + { + Value = value; + } + + public string Value { get; } + + public sealed record Bar(string Value) : Foo(Value); + } + """).WithOptions(ParseOptionsHelper.FromCSharp9).VerifyNoIssues(); [TestMethod] public void UnusedPrivateMember_NonExistentRecordPositionalConstructor() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Fields.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Fields.cs index a48a241bbb0..6a3cae33ffa 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Fields.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Fields.cs @@ -157,6 +157,6 @@ public void Bar() WNetAddConnection2(netResource, "password", "username", 0); } } - """).Verify(); + """).VerifyNoIssues(); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Methods.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Methods.cs index 36596d5d5da..8efbdba276e 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Methods.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Methods.cs @@ -81,53 +81,54 @@ public class InterfaceImpl : IInterface [TestMethod] public void UnusedPrivateMember_Methods_DirectReferences() => - builder.AddSnippet(@" -using System; -using System.Linq; -public class MethodUsages -{ - private int Method1() { return 0; } - private int Method2() { return 0; } - private int Method3() { return 0; } - private int Method4() { return 0; } - private int Method5() { return 0; } - private int Method6() { return 0; } - private int Method7() { return 0; } - public int Test1(MethodUsages other) - { - int i; - i = Method1(); - i = this.Method2(); - Console.Write(Method3()); - new MethodUsages().Method4(); - Func x = () => Method5(); - other.Method6(); - return Method7(); - } - - private int Method8() { return 0; } - public int ExpressionBodyMethod() => Method8(); - - private static int Method9() { return 0; } - public MethodUsages(int number) { } - public MethodUsages() : this(Method9()) { } - - private int Method10() { return 0; } - private int Method11() { return 0; } - public object Test2() - { - var x = new[] { Method10() }; - var name = nameof(Method11); - return null; - } - - private int Method12(int i) { return 0; } - public void Test3() - { - new[] { 1, 2, 3 }.Select(Method12); - } -} -").Verify(); + builder.AddSnippet(""" + using System; + using System.Linq; + public class MethodUsages + { + private int Method1() { return 0; } + private int Method2() { return 0; } + private int Method3() { return 0; } + private int Method4() { return 0; } + private int Method5() { return 0; } + private int Method6() { return 0; } + private int Method7() { return 0; } + public int Test1(MethodUsages other) + { + int i; + i = Method1(); + i = this.Method2(); + Console.Write(Method3()); + new MethodUsages().Method4(); + Func x = () => Method5(); + other.Method6(); + return Method7(); + } + + private int Method8() { return 0; } + public int ExpressionBodyMethod() => Method8(); + + private static int Method9() { return 0; } + public MethodUsages(int number) { } + public MethodUsages() : this(Method9()) { } + + private int Method10() { return 0; } + private int Method11() { return 0; } + public object Test2() + { + var x = new[] { Method10() }; + var name = nameof(Method11); + return null; + } + + private int Method12(int i) { return 0; } + public void Test3() + { + new[] { 1, 2, 3 }.Select(Method12); + } + } + + """).VerifyNoIssues(); [TestMethod] public void UnusedPrivateMember_Methods_Main() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Properties.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Properties.cs index 57e3ef0792d..14ffcf40bed 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Properties.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Properties.cs @@ -18,13 +18,13 @@ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +public partial class UnusedPrivateMemberTest { - public partial class UnusedPrivateMemberTest - { - [TestMethod] - public void UnusedPrivateMember_Property_Accessibility() => - builder.AddSnippet(@" + [TestMethod] + public void UnusedPrivateMember_Property_Accessibility() => + builder.AddSnippet(@" public class PrivateMembers { private int PrivateProperty { get; set; } // Noncompliant {{Remove the unused private property 'PrivateProperty'.}} @@ -80,67 +80,67 @@ public class InterfaceImpl : IInterface } ").Verify(); - [TestMethod] - public void UnusedPrivateMember_Properties_DirectReferences() => - builder.AddSnippet(@" -using System; -public class PropertyUsages -{ - private int Property1 { get; set; } - private int Property2 { get; set; } - private int Property4 { get; set; } - private int Property5 { get; set; } - private int Property6 { get; set; } - public int Method1(PropertyUsages other) - { - Property1 = 0; - this.Property2 = 0; - ((Property4)) = 0; - Console.Write(Property4); - new PropertyUsages().Property5 = 0; - Func x = () => Property5; - other.Property6 = 0; - return Property6; - } - - private int Property7 { get; set; } = 0; - public int ExpressionBodyMethod() => Property7; - - private static int Property8 { get; set; } = 0; - public int SomeProperty { get; set; } = Property8; - - private static int Property9 { get; set; } - static PropertyUsages() - { - Property9 = 0; - } - public PropertyUsages(int number) { } - public PropertyUsages() : this(Property9) { } - - private int Property10 { get; set; } - private int Property11 { get; set; } - public object Method2() - { - if ((Property10 = 0) == 0) { } - var x = new[] { Property10 }; - var name = nameof(Property11); - return null; - } - - private int this[string i] { get { return 5; } set { } } - public void Method3() - { - var x = this[""5""]; - this[""5""] = 10; - } - - private int Property12 { get; set; } = 42; // FN -} -").Verify(); - - [TestMethod] - public void UnusedPrivateMember_Properties_Accessors() => - builder.AddSnippet(@" + [TestMethod] + public void UnusedPrivateMember_Properties_DirectReferences() => + builder.AddSnippet(""" + using System; + public class PropertyUsages + { + private int Property1 { get; set; } + private int Property2 { get; set; } + private int Property4 { get; set; } + private int Property5 { get; set; } + private int Property6 { get; set; } + public int Method1(PropertyUsages other) + { + Property1 = 0; + this.Property2 = 0; + ((Property4)) = 0; + Console.Write(Property4); + new PropertyUsages().Property5 = 0; + Func x = () => Property5; + other.Property6 = 0; + return Property6; + } + + private int Property7 { get; set; } = 0; + public int ExpressionBodyMethod() => Property7; + + private static int Property8 { get; set; } = 0; + public int SomeProperty { get; set; } = Property8; + + private static int Property9 { get; set; } + static PropertyUsages() + { + Property9 = 0; + } + public PropertyUsages(int number) { } + public PropertyUsages() : this(Property9) { } + + private int Property10 { get; set; } + private int Property11 { get; set; } + public object Method2() + { + if ((Property10 = 0) == 0) { } + var x = new[] { Property10 }; + var name = nameof(Property11); + return null; + } + + private int this[string i] { get { return 5; } set { } } + public void Method3() + { + var x = this["5"]; + this["5"] = 10; + } + + private int Property12 { get; set; } = 42; // FN + } + """).VerifyNoIssues(); + + [TestMethod] + public void UnusedPrivateMember_Properties_Accessors() => + builder.AddSnippet(@" using System; public class PropertyUsages { @@ -191,5 +191,4 @@ public void Method(string str) } } ").Verify(); - } } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Types.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Types.cs index 8e86a9d7a99..ebcc9d101b4 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Types.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.Types.cs @@ -67,25 +67,26 @@ internal class InternalClass { } // Compliant, internal types are not reported w [TestMethod] public void UnusedPrivateMember_Types_Internals() => - builder.AddSnippet(@" -// https://github.com/SonarSource/sonar-dotnet/issues/1225 -// https://github.com/SonarSource/sonar-dotnet/issues/904 -using System; -public class Class1 -{ - public void Method1() - { - var x = Sample.Constants.X; - } -} - -public class Sample -{ - internal class Constants - { - public const int X = 5; - } -}").Verify(); + builder.AddSnippet(""" + // https://github.com/SonarSource/sonar-dotnet/issues/1225 + // https://github.com/SonarSource/sonar-dotnet/issues/904 + using System; + public class Class1 + { + public void Method1() + { + var x = Sample.Constants.X; + } + } + + public class Sample + { + internal class Constants + { + public const int X = 5; + } + } + """).VerifyNoIssues(); [TestMethod] public void UnusedPrivateMember_Types_DirectReferences() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.cs index 6f651067ae8..3172bce608e 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UnusedPrivateMemberTest.cs @@ -51,34 +51,36 @@ public void Method() [TestMethod] public void UnusedPrivateMember_Members_With_Attributes_Are_Not_Removable() => - builder.AddSnippet(@" -using System; -public class FieldUsages -{ - [Obsolete] - private int field1; + builder.AddSnippet(""" + using System; + public class FieldUsages + { + [Obsolete] + private int field1; - [Obsolete] - private int Property1 { get; set; } + [Obsolete] + private int Property1 { get; set; } - [Obsolete] - private int Method1() { return 0; } + [Obsolete] + private int Method1() { return 0; } - [Obsolete] - private class Class1 { } -}").Verify(); + [Obsolete] + private class Class1 { } + } + """).VerifyNoIssues(); [TestMethod] public void UnusedPrivateMember_Assembly_Level_Attributes() => - builder.AddSnippet(@" -[assembly: System.Reflection.AssemblyCompany(Foo.Constants.AppCompany)] -public static class Foo -{ - internal static class Constants // Compliant, detect usages from assembly level attributes. - { - public const string AppCompany = ""foo""; - } -}").Verify(); + builder.AddSnippet(""" + [assembly: System.Reflection.AssemblyCompany(Foo.Constants.AppCompany)] + public static class Foo + { + internal static class Constants // Compliant, detect usages from assembly level attributes. + { + public const string AppCompany = "foo"; + } + } + """).VerifyNoIssues(); [TestMethod] public void UnusedPrivateMemberWithPartialClasses() => @@ -103,54 +105,56 @@ public partial class PartialClass [TestMethod] public void UnusedPrivateMember_Unity3D_Ignored() => - builder.AddSnippet(@" -// https://github.com/SonarSource/sonar-dotnet/issues/159 -public class UnityMessages1 : UnityEngine.MonoBehaviour -{ - private void SomeMethod(bool hasFocus) { } // Compliant -} - -public class UnityMessages2 : UnityEngine.ScriptableObject -{ - private void SomeMethod(bool hasFocus) { } // Compliant -} - -public class UnityMessages3 : UnityEditor.AssetPostprocessor -{ - private void SomeMethod(bool hasFocus) { } // Compliant -} - -public class UnityMessages4 : UnityEditor.AssetModificationProcessor -{ - private void SomeMethod(bool hasFocus) { } // Compliant -} - -// Unity3D does not seem to be available as a nuget package and we cannot use the original classes -namespace UnityEngine -{ - public class MonoBehaviour { } - public class ScriptableObject { } -} -namespace UnityEditor -{ - public class AssetPostprocessor { } - public class AssetModificationProcessor { } -}").Verify(); + builder.AddSnippet(""" + // https://github.com/SonarSource/sonar-dotnet/issues/159 + public class UnityMessages1 : UnityEngine.MonoBehaviour + { + private void SomeMethod(bool hasFocus) { } // Compliant + } + + public class UnityMessages2 : UnityEngine.ScriptableObject + { + private void SomeMethod(bool hasFocus) { } // Compliant + } + + public class UnityMessages3 : UnityEditor.AssetPostprocessor + { + private void SomeMethod(bool hasFocus) { } // Compliant + } + + public class UnityMessages4 : UnityEditor.AssetModificationProcessor + { + private void SomeMethod(bool hasFocus) { } // Compliant + } + + // Unity3D does not seem to be available as a nuget package and we cannot use the original classes + namespace UnityEngine + { + public class MonoBehaviour { } + public class ScriptableObject { } + } + namespace UnityEditor + { + public class AssetPostprocessor { } + public class AssetModificationProcessor { } + } + """).VerifyNoIssues(); [TestMethod] public void EntityFrameworkMigration_Ignored() => - builder.AddSnippet(@" -namespace EntityFrameworkMigrations -{ - using Microsoft.EntityFrameworkCore.Migrations; + builder.AddSnippet(""" + namespace EntityFrameworkMigrations + { + using Microsoft.EntityFrameworkCore.Migrations; - public class SkipMigration : Migration - { - private void SomeMethod(bool condition) { } // Compliant + public class SkipMigration : Migration + { + private void SomeMethod(bool condition) { } // Compliant - protected override void Up(MigrationBuilder migrationBuilder) { } - } -}").AddReferences(EntityFrameworkCoreReferences("7.0.14")).Verify(); + protected override void Up(MigrationBuilder migrationBuilder) { } + } + } + """).AddReferences(EntityFrameworkCoreReferences("7.0.14")).VerifyNoIssues(); [DataTestMethod] [DataRow(ProjectType.Product)] @@ -197,7 +201,7 @@ public class SkipMigration : Migration public void UnusedPrivateMember_FromCSharp12() => builder.AddPaths("UnusedPrivateMember.CSharp12.cs") .WithOptions(ParseOptionsHelper.FromCSharp12) - .Verify(); + .VerifyNoIssues(); #endif @@ -210,7 +214,7 @@ public class SkipMigration : Migration [TestMethod] public void UnusedPrivateMember_UsedInGeneratedFile() => - builder.AddPaths("UnusedPrivateMember.CalledFromGenerated.cs", "UnusedPrivateMember.Generated.cs").Verify(); + builder.AddPaths("UnusedPrivateMember.CalledFromGenerated.cs", "UnusedPrivateMember.Generated.cs").VerifyNoIssues(); [TestMethod] public void UnusedPrivateMember_Performance() => @@ -219,7 +223,7 @@ public class SkipMigration : Migration // The threshold is set here to 30 seconds to avoid flaky builds due to slow build agents or network connections. builder.AddPaths("UnusedPrivateMember.Performance.cs") .AddReferences(EntityFrameworkCoreReferences("5.0.12")) // The latest before 6.0.0 for .NET 6 that has Linq versioning collision issue - .Invoking(x => x.Verify()) + .Invoking(x => x.VerifyNoIssues()) .ExecutionTime().Should().BeLessOrEqualTo(30.Seconds()); private static ImmutableArray EntityFrameworkCoreReferences(string entityFrameworkVersion) => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UseAwaitableMethodTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UseAwaitableMethodTest.cs index ead8ee2c595..d0322bd730a 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UseAwaitableMethodTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UseAwaitableMethodTest.cs @@ -58,7 +58,7 @@ async Task MethodInvocations() ActionProperty(); // Compliant; } } - """).Verify(); + """).VerifyNoIssues(); [TestMethod] public void UseAwaitableMethod_Sockets() => diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UseCharOverloadOfStringMethodsTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UseCharOverloadOfStringMethodsTest.cs index aa4ed2b39fa..800a0d21ce8 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UseCharOverloadOfStringMethodsTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UseCharOverloadOfStringMethodsTest.cs @@ -37,7 +37,7 @@ public class UseCharOverloadOfStringMethodsTest [TestMethod] public void UseCharOverloadOfStringMethods_VB() => - builderVB.AddPaths("UseCharOverloadOfStringMethods.Framework.vb").Verify(); + builderVB.AddPaths("UseCharOverloadOfStringMethods.Framework.vb").VerifyNoIssues(); #else diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UseFindSystemTimeZoneByIdTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UseFindSystemTimeZoneByIdTest.cs index 454302f162d..80094a9495f 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UseFindSystemTimeZoneByIdTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UseFindSystemTimeZoneByIdTest.cs @@ -60,12 +60,12 @@ public class UseFindSystemTimeZoneByIdTest [TestMethod] public void UseFindSystemTimeZoneById_CS() => builderCS.AddReferences(NuGetMetadataReference.TimeZoneConverter()) - .AddPaths("UseFindSystemTimeZoneById.cs").Verify(); + .AddPaths("UseFindSystemTimeZoneById.cs").VerifyNoIssues(); [TestMethod] public void UseFindSystemTimeZoneById_VB() => builderVB.AddReferences(NuGetMetadataReference.TimeZoneConverter()) - .AddPaths("UseFindSystemTimeZoneById.vb").Verify(); + .AddPaths("UseFindSystemTimeZoneById.vb").VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/UseGenericWithRefParametersTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/UseGenericWithRefParametersTest.cs index de68fee4e84..0c0614dd95a 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/UseGenericWithRefParametersTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/UseGenericWithRefParametersTest.cs @@ -20,24 +20,23 @@ using SonarAnalyzer.Rules.CSharp; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class UseGenericWithRefParametersTest { - [TestClass] - public class UseGenericWithRefParametersTest - { - private readonly VerifierBuilder builder = new VerifierBuilder(); + private readonly VerifierBuilder builder = new VerifierBuilder(); - [TestMethod] - public void UseGenericWithRefParameters() => - builder.AddPaths("UseGenericWithRefParameters.cs").Verify(); + [TestMethod] + public void UseGenericWithRefParameters() => + builder.AddPaths("UseGenericWithRefParameters.cs").Verify(); - [TestMethod] - public void UseGenericWithRefParameters_InvalidCode() => - builder.AddSnippet(@" -public void (ref object o1) -{ -}") - .WithErrorBehavior(CompilationErrorBehavior.Ignore) - .Verify(); - } + [TestMethod] + public void UseGenericWithRefParameters_InvalidCode() => + builder.AddSnippet(""" + public void (ref object o1) + { + } + """) + .VerifyNoIssuesIgnoreErrors(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/ValueTypeShouldImplementIEquatableTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/ValueTypeShouldImplementIEquatableTest.cs index 4bd0b45bdf8..3a153da8091 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/ValueTypeShouldImplementIEquatableTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/ValueTypeShouldImplementIEquatableTest.cs @@ -37,7 +37,7 @@ public class ValueTypeShouldImplementIEquatableTest [TestMethod] public void ValueTypeShouldImplementIEquatable_CSharp10() => - builderCS.AddPaths("ValueTypeShouldImplementIEquatable.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify(); + builderCS.AddPaths("ValueTypeShouldImplementIEquatable.CSharp10.cs").WithOptions(ParseOptionsHelper.FromCSharp10).VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/VariableUnusedTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/VariableUnusedTest.cs index 90b02cc6dd7..a8eb3797312 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/VariableUnusedTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/VariableUnusedTest.cs @@ -48,7 +48,7 @@ public class VariableUnusedTest [TestMethod] public void VariableUnused_CSharp12() => - builderCS.AddPaths("VariableUnused.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).Verify(); + builderCS.AddPaths("VariableUnused.CSharp12.cs").WithOptions(ParseOptionsHelper.FromCSharp12).VerifyNoIssues(); #endif diff --git a/analyzers/tests/SonarAnalyzer.Test/SymbolicExecution/Roslyn/CollectionConstraintTests.cs b/analyzers/tests/SonarAnalyzer.Test/SymbolicExecution/Roslyn/CollectionConstraintTests.cs index 2728c921f08..2ae786f54b3 100644 --- a/analyzers/tests/SonarAnalyzer.Test/SymbolicExecution/Roslyn/CollectionConstraintTests.cs +++ b/analyzers/tests/SonarAnalyzer.Test/SymbolicExecution/Roslyn/CollectionConstraintTests.cs @@ -75,7 +75,7 @@ void Foo(Sample sample) } } """) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CollectionConstraint_ShouldNotLearnConstraintForNonCollectionProperties() => @@ -96,7 +96,7 @@ void Test(List foo) } } """) - .Verify(); + .VerifyNoIssues(); [TestMethod] public void CollectionConstraint_ShouldNotLearnConstraintFromBinariesForNonTrackedTypes() => @@ -123,5 +123,5 @@ void Foo(NotACollection notACollection) } } """) - .Verify(); + .VerifyNoIssues(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/AspNet/AvoidUnderPosting.CSharp12.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/AspNet/AvoidUnderPosting.CSharp12.cs index 2e58fb56c59..8ce3dfd293b 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/AspNet/AvoidUnderPosting.CSharp12.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/AspNet/AvoidUnderPosting.CSharp12.cs @@ -5,11 +5,18 @@ namespace CSharp12 { public class ModelWithPrimaryConstructor(int vp, int rvp, int nvp) { - public int ValueProperty { get; set; } = vp; // Compliant - no parameterless constructor, type cannot be used for Model Binding + public int ValueProperty { get; set; } = vp; // Compliant: no parameterless constructor, type cannot be used for Model Binding + } + + public class ModelWithPrimaryAndParameterlessConstructor(int vp, int rvp, int nvp) + { + public ModelWithPrimaryAndParameterlessConstructor() : this(0, 0, 0) { } + public int ValueProperty { get; set; } = vp; // Noncompliant } public class DerivedFromController : Controller { [HttpPost] public IActionResult Create(ModelWithPrimaryConstructor model) => View(model); + [HttpDelete] public IActionResult Remove(ModelWithPrimaryAndParameterlessConstructor model) => View(model); } } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/AspNet/ControllerReuseClient.CSharp12.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/AspNet/ControllerReuseClient.CSharp12.cs index 4ca8def6418..1de36c196cf 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/AspNet/ControllerReuseClient.CSharp12.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/AspNet/ControllerReuseClient.CSharp12.cs @@ -10,14 +10,15 @@ public class C(HttpClient client) : ControllerBase; [ApiController] [Route("SomeRoute")] -public class D(HttpClient client) : C(new HttpClient()) // Compliant +public class D(HttpClient client) : C(new HttpClient()) // Compliant { - public D() : this(new HttpClient()) { } // Compliant + public D() : this(new HttpClient()) { } // Compliant + private HttpClient Client { get => new HttpClient(); } // Noncompliant } [ApiController] [Route("SomeRoute")] public class E : C { - public E() : base(new HttpClient()) { } // Compliant + public E() : base(new HttpClient()) { } // Compliant } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/DebuggerDisplayUsesExistingMembers.CSharp8.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/DebuggerDisplayUsesExistingMembers.CSharp8.cs index 96ea4a0d938..8dfd063c41b 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/DebuggerDisplayUsesExistingMembers.CSharp8.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/DebuggerDisplayUsesExistingMembers.CSharp8.cs @@ -7,13 +7,16 @@ public class BaseClass { private protected int PrivateProtectedProperty => 1; - [DebuggerDisplay("{PrivateProtectedProperty}")] + [DebuggerDisplay("{PrivateProtectedProperty}")] // Compliant public int SomeProperty => 1; + + [DebuggerDisplay("{Nonexistent}")] // Noncompliant + public int OtherProperty => 1; } public class SubClass : BaseClass { - [DebuggerDisplay("{PrivateProtectedProperty}")] + [DebuggerDisplay("{PrivateProtectedProperty}")] // Compliant public int OtherProperty => 1; } } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/FindInsteadOfFirstOrDefault.Net.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/FindInsteadOfFirstOrDefault.Net.cs index 6efca7dd66e..7fc47016cdf 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/FindInsteadOfFirstOrDefault.Net.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/FindInsteadOfFirstOrDefault.Net.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System; @@ -6,13 +6,15 @@ public class FindInsteadOfFirstOrDefault { public void List(List data) { - data.FirstOrDefault(default(int)); // Compliant - data.FirstOrDefault(x => false, default(int)); // Compliant + data.FirstOrDefault(x => true); // Noncompliant + data.FirstOrDefault(default(int)); // Compliant + data.FirstOrDefault(x => false, default(int)); // Compliant } public void Array(int[] data) { - data.FirstOrDefault(default(int)); // Compliant - data.FirstOrDefault(x => false, default(int)); // Compliant + data.FirstOrDefault(x => true); // Noncompliant + data.FirstOrDefault(default(int)); // Compliant + data.FirstOrDefault(x => false, default(int)); // Compliant } } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/FindInsteadOfFirstOrDefault.Net.vb b/analyzers/tests/SonarAnalyzer.Test/TestCases/FindInsteadOfFirstOrDefault.Net.vb index d9de6267ead..2958a7e836e 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/FindInsteadOfFirstOrDefault.Net.vb +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/FindInsteadOfFirstOrDefault.Net.vb @@ -1,15 +1,17 @@ -Imports System.Collections.Generic +Imports System.Collections.Generic Imports System.Linq Imports System Public Class FindInsteadOfFirstOrDefault Public Sub List(data As List(Of Integer)) - Dim unused = data.FirstOrDefault(0) ' Compliant - unused = data.FirstOrDefault(Function(x) False, 0) ' Compliant + Dim unused = data.FirstOrDefault(Function(x) True) ' Noncompliant + unused = data.FirstOrDefault(0) ' Compliant + unused = data.FirstOrDefault(Function(x) False, 0) ' Compliant End Sub Public Sub Array(data As Integer()) - Dim unused = data.FirstOrDefault(0) ' Compliant - unused = data.FirstOrDefault(Function(x) False, 0) ' Compliant + Dim unused = data.FirstOrDefault(Function(x) True) ' Noncompliant + unused = data.FirstOrDefault(0) ' Compliant + unused = data.FirstOrDefault(Function(x) False, 0) ' Compliant End Sub End Class diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/GenericTypeParameterUnused.CSharp11.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/GenericTypeParameterUnused.CSharp11.cs index 460d9742306..f6dfc4192f2 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/GenericTypeParameterUnused.CSharp11.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/GenericTypeParameterUnused.CSharp11.cs @@ -5,9 +5,14 @@ namespace Tests.Diagnostics public interface Interface { - static abstract int AddAbstract(int a, int b); // Compliant + static int AddStatic(int a, int b) // Noncompliant + { + return a + b; + } + + static abstract int AddAbstract(int a, int b); // Compliant - static virtual int AddVirtual(int a, int b) // Compliant (T might be used in implementation of the interface) + static virtual int AddVirtual(int a, int b) // Compliant: T might be used in implementation of the interface { return a + b; } @@ -15,7 +20,7 @@ static virtual int AddVirtual(int a, int b) // Compliant (T might be used in public class InterfaceImplementation : Interface { - public static int AddAbstract(int a, int b) // Compliant, it is implementing the interface. + public static int AddAbstract(int a, int b) // Compliant: it is implementing the interface. { return 0; } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/DisablingCSRFProtection.CSharp11.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/DisablingCSRFProtection.CSharp11.cs index f764bdd92d3..da15478bf7c 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/DisablingCSRFProtection.CSharp11.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/DisablingCSRFProtection.CSharp11.cs @@ -7,9 +7,10 @@ namespace Net6Poc.DisablingCSRFProtection { internal class TestCases { - [GenericIgnoreAntiforgeryToken] // FN - for performance reasons inheritance is not supported + [GenericIgnoreAntiforgeryToken] // FN: for performance reasons inheritance is not supported public void A() { } + [IgnoreAntiforgeryTokenAttribute] // Noncompliant public void B() { } } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/DoNotHardcodeCredentials.DefaultValues.CSharp8.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/DoNotHardcodeCredentials.DefaultValues.CSharp8.cs index 49f03ccae55..145c6d14c28 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/DoNotHardcodeCredentials.DefaultValues.CSharp8.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/DoNotHardcodeCredentials.DefaultValues.CSharp8.cs @@ -8,6 +8,7 @@ public void Concatenations() // Reassigned secret ??= "hardcoded"; - var a = "Server = localhost; Database = Test; User = SA; Password = " + secret; // Compliant, this is not symbolic execution rule and ConstantValueFinder cannot detect that. + var a = "Server = localhost; Database = Test; User = SA; Password = " + secret; // Compliant: this is not symbolic execution rule and ConstantValueFinder cannot detect that. + var b = "Server = localhost; Database = Test; User = SA; Password = secret"; // Noncompliant } } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/ExecutingSqlQueries.CSharp10.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/ExecutingSqlQueries.CSharp10.cs index f15a7d16bf7..999d798aa31 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/ExecutingSqlQueries.CSharp10.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/Hotspots/ExecutingSqlQueries.CSharp10.cs @@ -7,9 +7,10 @@ const string part2 = " mytable WHERE mycol="; const string querry = $"{part1}{part2}"; -void Foo(DbContext context, SqliteConnection connection, params object[] parameters) +void Foo(DbContext context, SqliteConnection connection, string notConstant, params object[] parameters) { - context.Query().FromSql("" + querry, parameters); // Compliant + context.Query().FromSql("" + querry, parameters); // Compliant + context.Query().FromSql("" + notConstant, parameters); // Noncompliant } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/MemberInitializedToDefault.CSharp8.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/MemberInitializedToDefault.CSharp8.cs index e438ee6535a..d6ac934e4ff 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/MemberInitializedToDefault.CSharp8.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/MemberInitializedToDefault.CSharp8.cs @@ -10,7 +10,8 @@ public class C // If the field is not initialized and nullable is set to enabled then // there's a warning "CS8618: Non-nullable property 'MyProperty' must contain a non-null value when exiting constructor. Consider declaring the property as nullable." // To silence the warning one needs to use a field initializer and the suppression operator. We should not raise and issue in the case ! is present. - public object MyProperty { get; set; } = default!; // Compliant + public object Noncompliant { get; set; } = default; // FN + public object MyProperty { get; set; } = default!; // Compliant public object MyPropertyNull { get; set; } = null!; // Compliant } } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/MethodOverloadsShouldBeGrouped.CSharp12.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/MethodOverloadsShouldBeGrouped.CSharp12.cs index 9818ea6769b..b25d4adc7c0 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/MethodOverloadsShouldBeGrouped.CSharp12.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/MethodOverloadsShouldBeGrouped.CSharp12.cs @@ -1,8 +1,10 @@ class SomeClass(int arg) { - public void RandomMethod1() { } + public void RandomMethod1() { } // Noncompliant public SomeClass() : this(5) { } + public void RandomMethod1(int i) { } // Secondary + public void RandomMethod2() { } } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/NativeMethodsShouldBeWrapped.CSharp10.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/NativeMethodsShouldBeWrapped.CSharp10.cs deleted file mode 100644 index 3fe1bf22170..00000000000 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/NativeMethodsShouldBeWrapped.CSharp10.cs +++ /dev/null @@ -1,7 +0,0 @@ -using System.Runtime.InteropServices; - -interface Foo -{ - [DllImport("mynativelib")] - extern public static void Bar(string s, int x); // Compliant, FN -} diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/NativeMethodsShouldBeWrapped.CSharp9.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/NativeMethodsShouldBeWrapped.CSharp9.cs index b68fb11753b..ff317779156 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/NativeMethodsShouldBeWrapped.CSharp9.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/NativeMethodsShouldBeWrapped.CSharp9.cs @@ -32,3 +32,9 @@ public void Method() public static extern bool RemoveDirectory(string name); // Noncompliant } } + +interface Foo +{ + [DllImport("mynativelib")] + extern public static void Bar(string s, int x); // FN +} diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/ConditionEvaluatesToConstant.CSharp12.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/ConditionEvaluatesToConstant.CSharp12.cs index 2873f04d665..da77db99faa 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/ConditionEvaluatesToConstant.CSharp12.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/ConditionEvaluatesToConstant.CSharp12.cs @@ -8,28 +8,45 @@ void CollectionExpressions(int[] array) int[] knownLength = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (var i = 0; i < knownLength.Length; i++) { - if (i > 5) // Compliant + if (i > 5) // Compliant { Console.WriteLine(i); } } + if (knownLength.Length == 0) { } // FN + if (knownLength.Length < 0) { } // Noncompliant + + int[] knownLength2 = [1, 2, .. knownLength, 3, 4]; + for (var i = 0; i < knownLength.Length; i++) + { + if (i > 5) // Compliant + { + Console.WriteLine(i); + } + } + if (knownLength2.Length == 0) { } // FN + if (knownLength2.Length < 0) { } // Noncompliant int[] unknownLength = [1, 2, .. array, 3, 4]; for (var i = 0; i < unknownLength.Length; i++) { - if (i > 5) // Compliant + if (i > 5) // Compliant { Console.WriteLine(i); } } + if (unknownLength.Length == 0) { } // FN + if (unknownLength.Length < 0) { } // Noncompliant - int[] knownLength2 = [1, 2, .. knownLength, 3, 4]; - for (var i = 0; i < knownLength.Length; i++) + int[] unknownLength2 = [.. array]; + for (var i = 0; i < unknownLength2.Length; i++) { - if (i > 5) // Compliant + if (i > 5) // Compliant { Console.WriteLine(i); } } + if (unknownLength2.Length == 0) { } // Compliant + if (unknownLength2.Length < 0) { } // Noncompliant } } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/EmptyNullableValueAccess.NullableContext.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/EmptyNullableValueAccess.NullableContext.cs index d70ad0fbd7c..7816be14fe1 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/EmptyNullableValueAccess.NullableContext.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/EmptyNullableValueAccess.NullableContext.cs @@ -7,12 +7,12 @@ class NullForgivingOperator { void Basics(int? i) { - _ = i!.Value; // Compliant, user-asserted non-empty via bang + _ = i!.Value; // Compliant: unknown i = SomeMethod(); _ = i!.Value; // Compliant i = null; - _ = i!.Value; // Compliant + _ = i!.Value; // Compliant: user-asserted non-empty via bang i = new int?(); _ = i!.Value; // Compliant i = new Nullable(); @@ -20,16 +20,19 @@ void Basics(int? i) i = 42; _ = i!.Value; // Compliant + + i = null; + _ = i.Value; // Noncompliant } void CastToValueType(int? i) { - _ = (int)i!; // Compliant, user-asserted non-empty via bang + _ = (int)i!; // Compliant: unknown i = SomeMethod(); _ = (int)i!; // Compliant i = null; - _ = (int)i!; // Compliant + _ = (int)i!; // Compliant: user-asserted non-empty via bang i = new int?(); _ = (int)i!; // Compliant i = new Nullable(); @@ -38,7 +41,7 @@ void CastToValueType(int? i) void CastToNullableType(int? i) { - _ = ((int?)i)!.Value; // Compliant, user-asserted non-empty via bang + _ = ((int?)i)!.Value; // Compliant: user-asserted non-empty via bang _ = (i as int?)!.Value; // Compliant _ = ((int?)null)!.Value; // Compliant diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/PublicMethodArgumentsShouldBeCheckedForNull.razor b/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/PublicMethodArgumentsShouldBeCheckedForNull.razor index 9b16f2d7cc6..0878b00540a 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/PublicMethodArgumentsShouldBeCheckedForNull.razor +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/PublicMethodArgumentsShouldBeCheckedForNull.razor @@ -6,4 +6,6 @@ @code { public RenderFragment Render => base.BuildRenderTree; + + public int Method(string arg1) => arg1.Length; // Noncompliant } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Sonar/SymbolicExecutionRules.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Sonar/SymbolicExecutionRules.cs index c622906282a..7970e12e216 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Sonar/SymbolicExecutionRules.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Sonar/SymbolicExecutionRules.cs @@ -10,20 +10,22 @@ public static void Main() { using var resource1 = GetNullResource(); - if (resource1 == null) // Compliant - "resource1" can be null + if (resource1 == null) // Compliant: "resource1" can be null { throw new Exception(); } + if (resource1 == null) { } // Noncompliant: "resource1" cannot be null + var resource2 = GetNullResource(); - if (resource2 == null) // Compliant - "resource2" can be null + if (resource2 == null) // Compliant: "resource2" can be null { throw new Exception(); } using (var resource3 = GetNullResource()) { - if (resource3 == null) // Compliant - "resource3" can be null + if (resource3 == null) // Compliant: "resource3" can be null { throw new Exception(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/ThreadStaticNonStaticField.CSharp11.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/ThreadStaticNonStaticField.CSharp11.cs index 68a8f856ffe..21575a2f79b 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/ThreadStaticNonStaticField.CSharp11.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/ThreadStaticNonStaticField.CSharp11.cs @@ -4,8 +4,11 @@ namespace Tests.Diagnostics { public class ThreadStaticNonStaticField { - [ThreadStaticAttribute] // FN for performance reasons we decided not to handle derived classes + [ThreadStaticAttribute] // FN: for performance reasons we decided not to handle derived classes private int count1 = 0, count11 = 0; + + [ThreadStaticAttribute] // Noncompliant + private int count2 = 0; } public class ThreadStaticAttribute : ThreadStaticAttribute { } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/ThreadStaticWithInitializer.CSharp11.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/ThreadStaticWithInitializer.CSharp11.cs index ce453d9c615..b397dca3f39 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/ThreadStaticWithInitializer.CSharp11.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/ThreadStaticWithInitializer.CSharp11.cs @@ -7,7 +7,10 @@ public class ThreadStaticWithInitializer public class Foo { [ThreadStaticAttribute] - public static object PerThreadObject = new object(); // FN for performance reasons we decided not to handle derived classes + public static object PerThreadObject1 = new object(); // FN: for performance reasons we decided not to handle derived classes + + [ThreadStaticAttribute] + public static object PerThreadObject2 = new object(); // Noncompliant } public class ThreadStaticAttribute : ThreadStaticAttribute { } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/UseCurlyBraces.CSharp7.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/UseCurlyBraces.CSharp7.cs index 19a2e5a4096..9d1d5d3219c 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/UseCurlyBraces.CSharp7.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/UseCurlyBraces.CSharp7.cs @@ -12,6 +12,8 @@ public UseCurlyBraces(object obj) { Console.WriteLine(str); } + if (obj is string str2) // Noncompliant + Console.WriteLine(str2); } } } diff --git a/analyzers/tests/SonarAnalyzer.TestFramework.Test/Verification/VerifierTest.cs b/analyzers/tests/SonarAnalyzer.TestFramework.Test/Verification/VerifierTest.cs index d7429a47adf..f0db6af2451 100644 --- a/analyzers/tests/SonarAnalyzer.TestFramework.Test/Verification/VerifierTest.cs +++ b/analyzers/tests/SonarAnalyzer.TestFramework.Test/Verification/VerifierTest.cs @@ -19,6 +19,7 @@ */ using System.IO; +using System.Reflection; using Microsoft.CodeAnalysis.CSharp; using SonarAnalyzer.Protobuf; using SonarAnalyzer.Rules.CSharp; @@ -513,27 +514,31 @@ public void Verify_AutogenerateConcurrentFiles() public void Verify_TestProject() { var builder = new VerifierBuilder() // Rule with scope Main - .AddSnippet("public class Sample { public void Main() { System.Console.WriteLine(); } }"); - builder.Invoking(x => x.Verify()).Should().Throw(); - builder.AddTestReference().Invoking(x => x.Verify()).Should().NotThrow("Project references should be recognized as Test code."); + .AddSnippet("class Sample { void Main() { System.Console.WriteLine(); } } // Noncompliant"); + builder.Invoking(x => x.Verify()).Should().NotThrow(); + builder.AddTestReference().Invoking(x => x.Verify()).Should().Throw("project references should be recognized as Test code").WithMessage(""" + There are differences for CSharp7 snippet0.cs: + Line 1: Missing expected issue + """); } [TestMethod] public void Verify_ParseOptions() { var builder = WithSnippetCS(""" - public class Sample + class Sample { - private System.Exception ex = new(); // C# 9 target-typed new + int i = 42; // Noncompliant + System.Exception ex = new(); // C# 9 target-typed new } """); builder.WithOptions(ParseOptionsHelper.FromCSharp9).Invoking(x => x.Verify()).Should().NotThrow(); builder.WithOptions(ParseOptionsHelper.BeforeCSharp9).Invoking(x => x.Verify()).Should().Throw().WithMessage(""" There are differences for CSharp5 File.Concurrent.cs: - Line 3: Unexpected error, use // Error [CS8026] Feature 'target-typed object creation' is not available in C# 5. Please use language version 9.0 or greater. + Line 4: Unexpected error, use // Error [CS8026] Feature 'target-typed object creation' is not available in C# 5. Please use language version 9.0 or greater. There are differences for CSharp5 File.cs: - Line 3: Unexpected error, use // Error [CS8026] Feature 'target-typed object creation' is not available in C# 5. Please use language version 9.0 or greater. + Line 4: Unexpected error, use // Error [CS8026] Feature 'target-typed object creation' is not available in C# 5. Please use language version 9.0 or greater. """); } @@ -548,29 +553,37 @@ public void Verify_BasePath() [TestMethod] public void Verify_ErrorBehavior() { - var builder = WithSnippetCS("undefined"); + var builder = WithSnippetCS(""" + class Sample + { + int a = 42; // Noncompliant + } + undefined + """); builder.Invoking(x => x.Verify()).Should().Throw() .WithMessage(""" There are differences for CSharp7 File.Concurrent.cs: - Line 1: Unexpected error, use // Error [CS0116] A namespace cannot directly contain members such as fields, methods or statements + Line 5: Unexpected error, use // Error [CS0116] A namespace cannot directly contain members such as fields, methods or statements There are differences for CSharp7 File.cs: - Line 1: Unexpected error, use // Error [CS0246] The type or namespace name 'undefined' could not be found (are you missing a using directive or an assembly reference?) - Line 1: Unexpected error, use // Error [CS8107] Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. - Line 1: Unexpected error, use // Error [CS8805] Program using top-level statements must be an executable. - Line 1: Unexpected error, use // Error [CS1001] Identifier expected - Line 1: Unexpected error, use // Error [CS1002] ; expected + Line 5: Unexpected error, use // Error [CS0246] The type or namespace name 'undefined' could not be found (are you missing a using directive or an assembly reference?) + Line 5: Unexpected error, use // Error [CS8107] Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. + Line 5: Unexpected error, use // Error [CS8803] Top-level statements must precede namespace and type declarations. + Line 5: Unexpected error, use // Error [CS8805] Program using top-level statements must be an executable. + Line 5: Unexpected error, use // Error [CS1001] Identifier expected + Line 5: Unexpected error, use // Error [CS1002] ; expected """); builder.WithErrorBehavior(CompilationErrorBehavior.FailTest).Invoking(x => x.Verify()).Should().Throw().WithMessage(""" There are differences for CSharp7 File.Concurrent.cs: - Line 1: Unexpected error, use // Error [CS0116] A namespace cannot directly contain members such as fields, methods or statements + Line 5: Unexpected error, use // Error [CS0116] A namespace cannot directly contain members such as fields, methods or statements There are differences for CSharp7 File.cs: - Line 1: Unexpected error, use // Error [CS0246] The type or namespace name 'undefined' could not be found (are you missing a using directive or an assembly reference?) - Line 1: Unexpected error, use // Error [CS8107] Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. - Line 1: Unexpected error, use // Error [CS8805] Program using top-level statements must be an executable. - Line 1: Unexpected error, use // Error [CS1001] Identifier expected - Line 1: Unexpected error, use // Error [CS1002] ; expected + Line 5: Unexpected error, use // Error [CS0246] The type or namespace name 'undefined' could not be found (are you missing a using directive or an assembly reference?) + Line 5: Unexpected error, use // Error [CS8107] Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. + Line 5: Unexpected error, use // Error [CS8803] Top-level statements must precede namespace and type declarations. + Line 5: Unexpected error, use // Error [CS8805] Program using top-level statements must be an executable. + Line 5: Unexpected error, use // Error [CS1001] Identifier expected + Line 5: Unexpected error, use // Error [CS1002] ; expected """); builder.WithErrorBehavior(CompilationErrorBehavior.Ignore).Invoking(x => x.Verify()).Should().NotThrow(); } @@ -611,13 +624,13 @@ public void Method() There are differences for CSharp7 File.cs: Line 10: Unexpected issue 'Change this condition so that it does not always evaluate to 'True'.' Rule S2589 """); - builder.WithOnlyDiagnostics(NullPointerDereference.S2259).Invoking(x => x.Verify()).Should().NotThrow(); + builder.WithOnlyDiagnostics(NullPointerDereference.S2259).Invoking(x => x.VerifyNoIssues()).Should().NotThrow(); } [TestMethod] public void Verify_NonConcurrentAnalysis() { - var builder = WithSnippetCS("var topLevelStatement = true;").WithOptions(ParseOptionsHelper.FromCSharp9).WithOutputKind(OutputKind.ConsoleApplication); + var builder = WithSnippetCS("var topLevelStatement = 42; // Noncompliant").WithOptions(ParseOptionsHelper.FromCSharp9).WithOutputKind(OutputKind.ConsoleApplication); builder.Invoking(x => x.Verify()).Should().Throw("Default Verifier behavior duplicates the source file.").WithMessage(""" There are differences for CSharp9 File.Concurrent.cs: Line 1: Unexpected error, use // Error [CS0825] The contextual keyword 'var' may only appear within a local variable declaration or in script code @@ -629,7 +642,7 @@ public void Verify_NonConcurrentAnalysis() [TestMethod] public void Verify_OutputKind() { - var builder = WithSnippetCS("var topLevelStatement = true;").WithOptions(ParseOptionsHelper.FromCSharp9); + var builder = WithSnippetCS("var topLevelStatement = 42; // Noncompliant").WithOptions(ParseOptionsHelper.FromCSharp9); builder.WithTopLevelStatements().Invoking(x => x.Verify()).Should().NotThrow(); builder.WithOutputKind(OutputKind.ConsoleApplication).WithConcurrentAnalysis(false).Invoking(x => x.Verify()).Should().NotThrow(); builder.Invoking(x => x.Verify()).Should().Throw().WithMessage(""" @@ -762,25 +775,46 @@ public void VerifyCodeFix_NoIssueRaised() } [TestMethod] - public void VerifyNoIssueReported_NoIssues_Succeeds() => + public void VerifyNoIssues_NoIssues_Succeeds() => WithSnippetCS("// Noncompliant - this comment is ignored").Invoking(x => x.VerifyNoIssues()).Should().NotThrow(); [TestMethod] - public void VerifyNoIssueReported_WithIssues_Throws() => + public void VerifyNoIssues_WithIssues_Throws() => WithSnippetCS(""" public class Sample { - private int a = 42; // This will raise an issue + private int a = 42; // Noncompliant } """).Invoking(x => x.VerifyNoIssues()).Should().Throw(); + [TestMethod] + public void VerifyNoIssues_InvalidCode_Throws() => + WithSnippetCS("Nonsense").Invoking(x => x.VerifyNoIssues()).Should().Throw(); + + [TestMethod] + public void VerifyNoIssuesIgnoreErrors_NoIssues_Succeeds() => + WithSnippetCS("// Noncompliant - this comment is ignored").Invoking(x => x.VerifyNoIssuesIgnoreErrors()).Should().NotThrow(); + + [TestMethod] + public void VerifyNoIssuesIgnoreErrors_WithIssues_Throws() => + WithSnippetCS(""" + public class Sample + { + private int a = 42; // Noncompliant + } + """).Invoking(x => x.VerifyNoIssuesIgnoreErrors()).Should().Throw(); + + [TestMethod] + public void VerifyNoIssuesIgnoreErrors_InvalidCode_Throws() => + WithSnippetCS("Nonsense").Invoking(x => x.VerifyNoIssuesIgnoreErrors()).Should().NotThrow(); + [TestMethod] public void Verify_ConcurrentAnalysis_FileEndingWithComment_CS() => - WithSnippetCS("// Nothing to see here, file ends with a comment").Invoking(x => x.Verify()).Should().NotThrow(); + WithSnippetCS("// Nothing to see here, file ends with a comment").Invoking(x => x.VerifyNoIssues()).Should().NotThrow(); [TestMethod] public void Verify_ConcurrentAnalysis_FileEndingWithComment_VB() => - WithSnippetVB("' Nothing to see here, file ends with a comment").Invoking(x => x.Verify()).Should().NotThrow(); + WithSnippetVB("' Nothing to see here, file ends with a comment").Invoking(x => x.VerifyNoIssues()).Should().NotThrow(); [TestMethod] public void VerifyUtilityAnalyzerProducesEmptyProtobuf_EmptyFile() diff --git a/analyzers/tests/SonarAnalyzer.TestFramework/Verification/DiagnosticVerifier.cs b/analyzers/tests/SonarAnalyzer.TestFramework/Verification/DiagnosticVerifier.cs index 378488e68f3..c7d8e4ba84e 100644 --- a/analyzers/tests/SonarAnalyzer.TestFramework/Verification/DiagnosticVerifier.cs +++ b/analyzers/tests/SonarAnalyzer.TestFramework/Verification/DiagnosticVerifier.cs @@ -27,21 +27,19 @@ public static class DiagnosticVerifier private const string AD0001 = nameof(AD0001); private const string LineContinuationVB12 = "BC36716"; // Visual Basic 12.0 does not support line continuation comments. - public static void Verify( - Compilation compilation, - DiagnosticAnalyzer analyzer, - string additionalFilePath = null, - string[] onlyDiagnostics = null, - string[] additionalSourceFiles = null) => + public static int Verify(Compilation compilation, + DiagnosticAnalyzer analyzer, + string additionalFilePath = null, + string[] onlyDiagnostics = null, + string[] additionalSourceFiles = null) => Verify(compilation, [analyzer], CompilationErrorBehavior.FailTest, additionalFilePath, onlyDiagnostics, additionalSourceFiles); - public static void Verify( - Compilation compilation, - DiagnosticAnalyzer[] analyzers, - CompilationErrorBehavior checkMode, // ToDo: Remove this parameter in https://github.com/SonarSource/sonar-dotnet/issues/8588 - string additionalFilePath = null, - string[] onlyDiagnostics = null, - string[] additionalSourceFiles = null) + public static int Verify(Compilation compilation, + DiagnosticAnalyzer[] analyzers, + CompilationErrorBehavior checkMode, // ToDo: Remove this parameter in https://github.com/SonarSource/sonar-dotnet/issues/8588 + string additionalFilePath = null, + string[] onlyDiagnostics = null, + string[] additionalSourceFiles = null) { SuppressionHandler.HookSuppression(); try @@ -58,6 +56,7 @@ public static class DiagnosticVerifier { SuppressionHandler.ExtensionMethodsCalledForAllDiagnostics(analyzers).Should().BeTrue("The ReportIssue should be used instead of ReportDiagnostic"); } + return diagnostics.Length; } finally { diff --git a/analyzers/tests/SonarAnalyzer.TestFramework/Verification/Verifier.cs b/analyzers/tests/SonarAnalyzer.TestFramework/Verification/Verifier.cs index 7f1602acac1..f14bfbdb730 100644 --- a/analyzers/tests/SonarAnalyzer.TestFramework/Verification/Verifier.cs +++ b/analyzers/tests/SonarAnalyzer.TestFramework/Verification/Verifier.cs @@ -97,15 +97,19 @@ public Verifier(VerifierBuilder builder) public void Verify() // This should never have any arguments { - if (codeFix != null) + if (codeFix is not null) { throw new InvalidOperationException($"Cannot use {nameof(Verify)} with {nameof(builder.CodeFix)} set."); } - foreach (var compilation in Compile(builder.ConcurrentAnalysis)) - { - var additionalSourceFiles = razorFilePaths.Concat(compilation.AdditionalSourceFiles ?? []).ToArray(); - DiagnosticVerifier.Verify(compilation.Compilation, analyzers, builder.ErrorBehavior, builder.AdditionalFilePath, onlyDiagnosticIds, additionalSourceFiles); - } + var numberOfIssues = Compile(builder.ConcurrentAnalysis) + .Sum(x => DiagnosticVerifier.Verify( + x.Compilation, + analyzers, + builder.ErrorBehavior, + builder.AdditionalFilePath, + onlyDiagnosticIds, + razorFilePaths.Concat(x.AdditionalSourceFiles ?? []).ToArray())); + numberOfIssues.Should().BeGreaterThan(0, $"otherwise you should use '{nameof(VerifyNoIssues)}' instead"); } public void VerifyNoIssues() // This should never have any arguments diff --git a/analyzers/tests/SonarAnalyzer.TestFramework/Verification/VerifierBuilder.cs b/analyzers/tests/SonarAnalyzer.TestFramework/Verification/VerifierBuilder.cs index fa6fd94168d..4a019fe2da5 100644 --- a/analyzers/tests/SonarAnalyzer.TestFramework/Verification/VerifierBuilder.cs +++ b/analyzers/tests/SonarAnalyzer.TestFramework/Verification/VerifierBuilder.cs @@ -145,12 +145,21 @@ public VerifierBuilder WithTopLevelStatements() public IEnumerable Compile() => Build().Compile(false).Select(x => x.Compilation); + /// + /// Verifies that the diagnostics match the expected diagnostics and at least one diagnostic is found. + /// public void Verify() => Build().Verify(); + /// + /// Verifies that no diagnostics are found. + /// public void VerifyNoIssues() => Build().VerifyNoIssues(); + /// + /// Verifies that no diagnostics, except errors, are found. + /// public void VerifyNoIssuesIgnoreErrors() => Build().VerifyNoIssuesIgnoreErrors();