예제 #1
0
        private static (TestWorkspace workspace, DiagnosticAnalyzerService analyzerService, CodeFixService codeFixService, IErrorLoggerService errorLogger) ServiceSetup(
            CodeFixProvider codefix,
            bool includeConfigurationFixProviders = false,
            bool throwExceptionInFixerCreation    = false)
        {
            var fixers = SpecializedCollections.SingletonEnumerable(
                new Lazy <CodeFixProvider, CodeChangeProviderMetadata>(
                    () => throwExceptionInFixerCreation ? throw new Exception() : codefix,
                    new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp)));

            var code = @"class Program { }";

            var workspace         = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true);
            var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            Assert.IsType <MockDiagnosticUpdateSourceRegistrationService>(workspace.GetService <IDiagnosticUpdateSourceRegistrationService>());
            var diagnosticService = Assert.IsType <DiagnosticAnalyzerService>(workspace.GetService <IDiagnosticAnalyzerService>());
            var logger            = SpecializedCollections.SingletonEnumerable(new Lazy <IErrorLoggerService>(() => new TestErrorLogger()));
            var errorLogger       = logger.First().Value;

            var configurationFixProviders = includeConfigurationFixProviders
                ? workspace.ExportProvider.GetExports <IConfigurationFixProvider, CodeChangeProviderMetadata>()
                : SpecializedCollections.EmptyEnumerable <Lazy <IConfigurationFixProvider, CodeChangeProviderMetadata> >();

            var fixService = new CodeFixService(
                diagnosticService,
                logger,
                fixers,
                configurationFixProviders);

            return(workspace, diagnosticService, fixService, errorLogger);
        }
예제 #2
0
        private static (TestWorkspace workspace, TestDiagnosticAnalyzerService analyzerService, CodeFixService codeFixService, IErrorLoggerService errorLogger) ServiceSetup(
            CodeFixProvider codefix,
            bool includeConfigurationFixProviders = false)
        {
            var fixers = SpecializedCollections.SingletonEnumerable(
                new Lazy <CodeFixProvider, CodeChangeProviderMetadata>(
                    () => codefix,
                    new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp)));

            var code = @"class Program { }";

            var workspace         = TestWorkspace.CreateCSharp(code, openDocuments: true);
            var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            var diagnosticService         = new TestDiagnosticAnalyzerService();
            var logger                    = SpecializedCollections.SingletonEnumerable(new Lazy <IErrorLoggerService>(() => new TestErrorLogger()));
            var errorLogger               = logger.First().Value;
            var configurationFixProviders = includeConfigurationFixProviders
                ? TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExports <IConfigurationFixProvider, CodeChangeProviderMetadata>()
                : SpecializedCollections.EmptyEnumerable <Lazy <IConfigurationFixProvider, CodeChangeProviderMetadata> >();
            var fixService = new CodeFixService(
                workspace.ExportProvider.GetExportedValue <IThreadingContext>(),
                diagnosticService, logger, fixers, configurationFixProviders);

            return(workspace, diagnosticService, fixService, errorLogger);
        }
예제 #3
0
        public DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            IReadOnlyDictionary <string, ImmutableArray <DiagnosticAnalyzer> >?analyzerMap = null,
            IDiagnosticUpdateSource?updateSource = null,
            bool createTaggerProvider            = true
            )
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            var analyzerReference = new TestAnalyzerReferenceByLanguage(
                analyzerMap ?? DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()
                );

            workspace.TryApplyChanges(
                workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })
                );

            _workspace = workspace;

            _registrationService =
                (SolutionCrawlerRegistrationService)workspace.Services.GetRequiredService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            if (
                !_registrationService
                .GetTestAccessor()
                .TryGetWorkCoordinator(workspace, out var coordinator)
                )
            {
                throw new InvalidOperationException();
            }

            AnalyzerService = (DiagnosticAnalyzerService?)_registrationService
                              .GetTestAccessor()
                              .AnalyzerProviders.SelectMany(pair => pair.Value)
                              .SingleOrDefault(
                lazyProvider =>
                lazyProvider.Metadata.Name == WellKnownSolutionCrawlerAnalyzers.Diagnostic &&
                lazyProvider.Metadata.HighPriorityForActiveFile
                )
                              ?.Value;
            DiagnosticService =
                (DiagnosticService)workspace.ExportProvider.GetExportedValue <IDiagnosticService>();

            if (updateSource is object)
            {
                DiagnosticService.Register(updateSource);
            }

            if (createTaggerProvider)
            {
                _ = TaggerProvider;
            }
        }
예제 #4
0
        public DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            IReadOnlyDictionary <string, ImmutableArray <DiagnosticAnalyzer> >?analyzerMap = null,
            IDiagnosticUpdateSource?updateSource = null,
            bool createTaggerProvider            = true)
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            var analyzerReference = new TestAnalyzerReferenceByLanguage(analyzerMap ?? DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            // Change the background analysis scope to OpenFiles instead of ActiveFile (default),
            // so that every diagnostic tagger test does not need to mark test files as "active" file.
            var csKey = new OptionKey2(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp);
            var vbKey = new OptionKey2(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic);

            workspace.SetOptions(workspace.Options
                                 .WithChangedOption(csKey, BackgroundAnalysisScope.OpenFiles)
                                 .WithChangedOption(vbKey, BackgroundAnalysisScope.OpenFiles));

            _workspace = workspace;

            _registrationService = (SolutionCrawlerRegistrationService)workspace.Services.GetRequiredService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            if (!_registrationService.GetTestAccessor().TryGetWorkCoordinator(workspace, out var coordinator))
            {
                throw new InvalidOperationException();
            }

            AnalyzerService   = (DiagnosticAnalyzerService?)_registrationService.GetTestAccessor().AnalyzerProviders.SelectMany(pair => pair.Value).SingleOrDefault(lazyProvider => lazyProvider.Metadata.Name == WellKnownSolutionCrawlerAnalyzers.Diagnostic && lazyProvider.Metadata.HighPriorityForActiveFile)?.Value;
            DiagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue <IDiagnosticService>();

            if (updateSource is object)
            {
                DiagnosticService.Register(updateSource);
            }

            if (createTaggerProvider)
            {
                _ = TaggerProvider;
            }
        }
예제 #5
0
        public async Task TestGetFirstDiagnosticWithFixAsync()
        {
            var fixers = CreateFixers();
            var code   = @"
    a
";

            using var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true);

            Assert.IsType <MockDiagnosticUpdateSourceRegistrationService>(workspace.GetService <IDiagnosticUpdateSourceRegistrationService>());
            var diagnosticService = Assert.IsType <DiagnosticAnalyzerService>(workspace.GetService <IDiagnosticAnalyzerService>());

            var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            var logger     = SpecializedCollections.SingletonEnumerable(new Lazy <IErrorLoggerService>(() => workspace.Services.GetRequiredService <IErrorLoggerService>()));
            var fixService = new CodeFixService(
                diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable <Lazy <IConfigurationFixProvider, CodeChangeProviderMetadata> >());

            var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService;

            // register diagnostic engine to solution crawler
            var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace);

            var reference = new MockAnalyzerReference();
            var project   = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
            var document  = project.Documents.Single();
            var unused    = await fixService.GetMostSevereFixAsync(
                document, TextSpan.FromBounds(0, 0), CodeActionRequestPriority.None, CodeActionOptions.DefaultProvider, isBlocking : false, CancellationToken.None);

            var fixer1 = (MockFixer)fixers.Single().Value;
            var fixer2 = (MockFixer)reference.Fixer !;

            // check to make sure both of them are called.
            Assert.True(fixer1.Called);
            Assert.True(fixer2.Called);
        }
예제 #6
0
        public DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            IReadOnlyDictionary <string, ImmutableArray <DiagnosticAnalyzer> >?analyzerMap = null,
            IDiagnosticUpdateSource?updateSource = null,
            bool createTaggerProvider            = true)
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            if (updateSource == null)
            {
                updateSource = AnalyzerService = new MyDiagnosticAnalyzerService(_listenerProvider.GetListener(FeatureAttribute.DiagnosticService));
            }

            var analyzerReference = new TestAnalyzerReferenceByLanguage(analyzerMap ?? DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            _workspace = workspace;

            _registrationService = workspace.Services.GetRequiredService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            DiagnosticService = new DiagnosticService(_listenerProvider, Array.Empty <Lazy <IEventListener, EventListenerMetadata> >());
            DiagnosticService.Register(updateSource);

            if (createTaggerProvider)
            {
                _ = TaggerProvider;
            }

            if (AnalyzerService != null)
            {
                _incrementalAnalyzers   = ImmutableArray.Create(AnalyzerService.CreateIncrementalAnalyzer(workspace));
                _solutionCrawlerService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;
            }
        }