Created
October 6, 2022 05:40
-
-
Save plainionist/13e27a6442f64d5c6517dde7d4668149 to your computer and use it in GitHub Desktop.
Code analyzer preventing test assemblies from being referenced
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[DiagnosticAnalyzer(LanguageNames.CSharp)] | |
public class UnitTestAssembliesMustNotBeReferenced : DiagnosticAnalyzer | |
{ | |
public const string DiagnosticId = "Architecture"; | |
private static DiagnosticDescriptor Descriptor { get; } = | |
new DiagnosticDescriptor("AR0001", | |
"UnitTest assemblies must not be referenced by other assemblies", | |
"The assembly '{0}' references the unit test assembly: {1}", | |
category: "Architecture", | |
defaultSeverity: DiagnosticSeverity.Error, | |
isEnabledByDefault: true); | |
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => | |
ImmutableArray.Create(Descriptor); | |
public override void Initialize(AnalysisContext context) | |
{ | |
context.EnableConcurrentExecution(); | |
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | |
context.RegisterCompilationAction(AnalyzeCompilation); | |
} | |
private void AnalyzeCompilation(CompilationAnalysisContext context) | |
{ | |
foreach (var item in context.Compilation.References) | |
{ | |
if (Path.GetFileNameWithoutExtension(item.Display) | |
.EndsWith(".UnitTests", StringComparison.OrdinalIgnoreCase)) | |
{ | |
context.ReportDiagnostic( | |
Diagnostic.Create( | |
Descriptor, | |
null, | |
context.Compilation.AssemblyName, | |
Path.GetFileNameWithoutExtension(item.Display))); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment