Пример #1
0
        private static async Task TestThirdPartyCodeFixer <TCodefix, TAnalyzer>(string code = null, string expected = null, DiagnosticSeverity severity = DiagnosticSeverity.Warning)
            where TAnalyzer : DiagnosticAnalyzer, new()
            where TCodefix : CodeFixProvider, new()
        {
            using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf.AddParts(typeof(TCodefix)));

            var options = CodeActionOptions.DefaultProvider;

            var project       = workspace.CurrentSolution.Projects.Single();
            var analyzer      = (DiagnosticAnalyzer) new TAnalyzer();
            var diagnosticIds = analyzer.SupportedDiagnostics.SelectAsArray(d => d.Id);

            var editorconfigText = "is_global = true";

            foreach (var diagnosticId in diagnosticIds)
            {
                editorconfigText += $"\ndotnet_diagnostic.{diagnosticId}.severity = {severity.ToEditorConfigString()}";
            }

            var map = new Dictionary <string, ImmutableArray <DiagnosticAnalyzer> > {
                { LanguageNames.CSharp, ImmutableArray.Create(analyzer) }
            };

            project = project.AddAnalyzerReference(new TestAnalyzerReferenceByLanguage(map));
            project = project.Solution.WithProjectFilePath(project.Id, @$ "z:\\{project.FilePath}").GetProject(project.Id);
            project = project.AddAnalyzerConfigDocument(".editorconfig", SourceText.From(editorconfigText), filePath: @"z:\\.editorconfig").Project;
            workspace.TryApplyChanges(project.Solution);

            // register this workspace to solution crawler so that analyzer service associate itself with given workspace
            var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue <IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider;

            incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace);

            var hostdoc  = workspace.Documents.Single();
            var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);

            var codeCleanupService = document.GetLanguageService <ICodeCleanupService>();

            var enabledDiagnostics = codeCleanupService.GetAllDiagnostics();

            var newDoc = await codeCleanupService.CleanupAsync(
                document, enabledDiagnostics, new ProgressTracker(), options, CancellationToken.None);

            var actual = await newDoc.GetTextAsync();

            Assert.Equal(expected, actual.ToString());
        }