|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using CommunityToolkit.Mvvm.ComponentModel; |
| 8 | +using Microsoft.CodeAnalysis.CSharp.Testing; |
| 9 | +using Microsoft.CodeAnalysis.CSharp; |
| 10 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 11 | +using Microsoft.CodeAnalysis.Testing.Verifiers; |
| 12 | +using Microsoft.CodeAnalysis.Testing; |
| 13 | +using Microsoft.CodeAnalysis; |
| 14 | + |
| 15 | +namespace CommunityToolkit.Mvvm.SourceGenerators.UnitTests.Helpers; |
| 16 | + |
| 17 | +/// <summary> |
| 18 | +/// A custom <see cref="CSharpAnalyzerTest{TAnalyzer, TVerifier}"/> that uses a specific C# language version to parse code. |
| 19 | +/// </summary> |
| 20 | +/// <typeparam name="TAnalyzer">The type of the analyzer to test.</typeparam> |
| 21 | +internal sealed class CSharpAnalyzerWithLanguageVersionTest<TAnalyzer> : CSharpAnalyzerTest<TAnalyzer, MSTestVerifier> |
| 22 | + where TAnalyzer : DiagnosticAnalyzer, new() |
| 23 | +{ |
| 24 | + /// <summary> |
| 25 | + /// The C# language version to use to parse code. |
| 26 | + /// </summary> |
| 27 | + private readonly LanguageVersion languageVersion; |
| 28 | + |
| 29 | + /// <summary> |
| 30 | + /// Creates a new <see cref="CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}"/> instance with the specified paramaters. |
| 31 | + /// </summary> |
| 32 | + /// <param name="languageVersion">The C# language version to use to parse code.</param> |
| 33 | + private CSharpAnalyzerWithLanguageVersionTest(LanguageVersion languageVersion) |
| 34 | + { |
| 35 | + this.languageVersion = languageVersion; |
| 36 | + } |
| 37 | + |
| 38 | + /// <inheritdoc/> |
| 39 | + protected override ParseOptions CreateParseOptions() |
| 40 | + { |
| 41 | + return new CSharpParseOptions(this.languageVersion, DocumentationMode.Diagnose); |
| 42 | + } |
| 43 | + |
| 44 | + /// <inheritdoc cref="AnalyzerVerifier{TAnalyzer, TTest, TVerifier}.VerifyAnalyzerAsync"/> |
| 45 | + /// <param name="languageVersion">The language version to use to run the test.</param> |
| 46 | + public static Task VerifyAnalyzerAsync(string source, LanguageVersion languageVersion, params DiagnosticResult[] expected) |
| 47 | + { |
| 48 | + CSharpAnalyzerWithLanguageVersionTest<TAnalyzer> test = new(languageVersion) { TestCode = source }; |
| 49 | + |
| 50 | + test.TestState.ReferenceAssemblies = ReferenceAssemblies.Net.Net60; |
| 51 | + test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(ObservableObject).Assembly.Location)); |
| 52 | + |
| 53 | + test.ExpectedDiagnostics.AddRange(expected); |
| 54 | + |
| 55 | + return test.RunAsync(CancellationToken.None); |
| 56 | + } |
| 57 | +} |
0 commit comments