Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add analyzer for value type usage with Assert.AreSame #4493

Merged
merged 5 commits into from
Jan 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
; Unshipped analyzer release
; Unshipped analyzer release
; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
### New Rules

Rule ID | Category | Severity | Notes
--------|----------|----------|-------
MSTEST0038 | `Usage` | Warning | AvoidAssertAreSameWithValueTypesAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0038)
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Immutable;

using Analyzer.Utilities.Extensions;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;

using MSTest.Analyzers.Helpers;
using MSTest.Analyzers.RoslynAnalyzerHelpers;

namespace MSTest.Analyzers;

/// <summary>
/// MSTEST0025: <inheritdoc cref="Resources.AvoidAssertAreSameWithValueTypesTitle"/>.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AvoidAssertAreSameWithValueTypesAnalyzer : DiagnosticAnalyzer
{
private static readonly LocalizableResourceString Title = new(nameof(Resources.AvoidAssertAreSameWithValueTypesTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.AvoidAssertAreSameWithValueTypesMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableResourceString Description = new(nameof(Resources.AvoidAssertAreSameWithValueTypesDescription), Resources.ResourceManager, typeof(Resources));

internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(
DiagnosticIds.AvoidAssertAreSameWithValueTypesRuleId,
Title,
MessageFormat,
Description,
Category.Usage,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
= ImmutableArray.Create(Rule);

public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

context.RegisterCompilationStartAction(context =>
{
Compilation compilation = context.Compilation;
INamedTypeSymbol? assertSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert);
if (assertSymbol is not null)
{
context.RegisterOperationAction(context => AnalyzeOperation(context, assertSymbol), OperationKind.Invocation);
}
});
}

private static void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol assertSymbol)
{
var operation = (IInvocationOperation)context.Operation;
IMethodSymbol targetMethod = operation.TargetMethod;
if (targetMethod.Name != "AreSame" ||
!assertSymbol.Equals(operation.TargetMethod.ContainingType, SymbolEqualityComparer.Default))
{
return;
}

IArgumentOperation? argExpected = operation.Arguments.FirstOrDefault(arg => arg.Parameter?.Ordinal == 0);
IArgumentOperation? argActual = operation.Arguments.FirstOrDefault(arg => arg.Parameter?.Ordinal == 1);
if (argExpected is null || argActual is null)
{
return;
}

if (argExpected.Value.WalkDownConversion().Type?.IsValueType == true ||
argActual.Value.WalkDownConversion().Type?.IsValueType == true)
{
context.ReportDiagnostic(operation.CreateDiagnostic(Rule));
}
}
}
1 change: 1 addition & 0 deletions src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,5 @@ internal static class DiagnosticIds
public const string UseDeploymentItemWithTestMethodOrTestClassRuleId = "MSTEST0035";
public const string DoNotUseShadowingRuleId = "MSTEST0036";
public const string UseProperAssertMethodsRuleId = "MSTEST0037";
public const string AvoidAssertAreSameWithValueTypesRuleId = "MSTEST0038";
}
4 changes: 4 additions & 0 deletions src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
#nullable enable
MSTest.Analyzers.AvoidAssertAreSameWithValueTypesAnalyzer
MSTest.Analyzers.AvoidAssertAreSameWithValueTypesAnalyzer.AvoidAssertAreSameWithValueTypesAnalyzer() -> void
override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void
override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DiagnosticDescriptor!>
27 changes: 27 additions & 0 deletions src/Analyzers/MSTest.Analyzers/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 10 additions & 1 deletion src/Analyzers/MSTest.Analyzers/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -543,4 +543,13 @@ The type declaring these methods should also respect the following rules:
<data name="DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod" xml:space="preserve">
<value>'[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported.</value>
</data>
</root>
<data name="AvoidAssertAreSameWithValueTypesTitle" xml:space="preserve">
<value>Don't use 'Assert.AreSame' with value types</value>
</data>
<data name="AvoidAssertAreSameWithValueTypesMessageFormat" xml:space="preserve">
<value>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</value>
</data>
<data name="AvoidAssertAreSameWithValueTypesDescription" xml:space="preserve">
<value>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</value>
</data>
</root>
15 changes: 15 additions & 0 deletions src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,21 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla:
<target state="translated">Argumenty kontrolního výrazu musí být předány ve správném pořadí</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesDescription">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesMessageFormat">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesTitle">
<source>Don't use 'Assert.AreSame' with value types</source>
<target state="new">Don't use 'Assert.AreSame' with value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidExpectedExceptionAttributeDescription">
<source>Prefer 'Assert.ThrowsException' or 'Assert.ThrowsExceptionAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exeption.</source>
<target state="translated">Preferujte Assert.ThrowsException nebo Assert.ThrowsExceptionAsync před [ExpectedException], protože zajišťuje, že očekávanou výjimku vyvolá pouze očekávané volání. Rozhraní API assert také poskytují větší flexibilitu a umožňují vyhodnocovat další vlastnosti výjimky.</target>
Expand Down
15 changes: 15 additions & 0 deletions src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,21 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte
<target state="translated">Assertionsargumente sollten in der richtigen Reihenfolge übergeben werden.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesDescription">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesMessageFormat">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesTitle">
<source>Don't use 'Assert.AreSame' with value types</source>
<target state="new">Don't use 'Assert.AreSame' with value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidExpectedExceptionAttributeDescription">
<source>Prefer 'Assert.ThrowsException' or 'Assert.ThrowsExceptionAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exeption.</source>
<target state="translated">„Assert.ThrowsException“ oder „Assert.ThrowsExceptionAsync“ gegenüber „[ExpectedException]“ bevorzugen, da dadurch sichergestellt wird, dass nur der erwartete Aufruf die erwartete Ausnahme auslöst. Die Assert-APIs bieten außerdem mehr Flexibilität und ermöglichen es Ihnen, zusätzliche Eigenschaften der Ausführung zu bestätigen.</target>
Expand Down
15 changes: 15 additions & 0 deletions src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,21 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes:
<target state="translated">Los argumentos de aserción deben pasarse en el orden correcto</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesDescription">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesMessageFormat">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesTitle">
<source>Don't use 'Assert.AreSame' with value types</source>
<target state="new">Don't use 'Assert.AreSame' with value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidExpectedExceptionAttributeDescription">
<source>Prefer 'Assert.ThrowsException' or 'Assert.ThrowsExceptionAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exeption.</source>
<target state="translated">Preferir "Assert.ThrowsException" o "Assert.ThrowsExceptionAsync" en lugar de '[ExpectedException]' ya que garantiza que solo la llamada esperada inicia la excepción esperada. Las API de aserción también proporcionan más flexibilidad y le permiten declarar propiedades adicionales de la ejecución.</target>
Expand Down
15 changes: 15 additions & 0 deletions src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,21 @@ Le type doit être une classe
<target state="translated">Les arguments d’assertion doivent être passés dans l’ordre approprié</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesDescription">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesMessageFormat">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesTitle">
<source>Don't use 'Assert.AreSame' with value types</source>
<target state="new">Don't use 'Assert.AreSame' with value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidExpectedExceptionAttributeDescription">
<source>Prefer 'Assert.ThrowsException' or 'Assert.ThrowsExceptionAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exeption.</source>
<target state="translated">Préférez « Assert.ThrowsException » ou « Assert.ThrowsExceptionAsync » à « [ExpectedException] », car cela assure que seul l’appel attendu lève l’exception attendue. Les API d’assertion offrent également plus de flexibilité et vous permettent de déclarer des propriétés supplémentaires de l’exception.</target>
Expand Down
15 changes: 15 additions & 0 deletions src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti:
<target state="translated">Gli argomenti dell'asserzione devono essere passati nell'ordine corretto</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesDescription">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types. Passing a value type to 'Assert.AreSame' will be boxed (creating a new object). Because 'Assert.AreSame' does the comparison by reference, it will fail when boxing happens.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesMessageFormat">
<source>Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</source>
<target state="new">Use 'Assert.AreEqual' instead of 'Assert.AreSame' when comparing value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssertAreSameWithValueTypesTitle">
<source>Don't use 'Assert.AreSame' with value types</source>
<target state="new">Don't use 'Assert.AreSame' with value types</target>
<note />
</trans-unit>
<trans-unit id="AvoidExpectedExceptionAttributeDescription">
<source>Prefer 'Assert.ThrowsException' or 'Assert.ThrowsExceptionAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exeption.</source>
<target state="translated">Preferisci 'Assert.ThrowsException' o 'Assert.ThrowsExceptionAsync' a '[ExpectedException]', perché garantisce che solo la chiamata prevista lanci l'eccezione prevista. Le API di asserzione forniscono anche una maggiore flessibilità e consentono l’asserzione delle proprietà aggiuntive dell'eccezione.</target>
Expand Down
Loading
Loading