Beispiel #1
0
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
        /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
        /// <returns>A Project created out of the Douments created from the source strings</returns>
        public static Project CreateProject(string[] sources,
                                            string language,
                                            LanguageVersion languageVersionCSharp,
                                            Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var          fileNamePrefix = DefaultFilePathPrefix;
            string       fileExt;
            ParseOptions parseOptions;

            if (language == LanguageNames.CSharp)
            {
                fileExt      = CSharpDefaultFileExt;
                parseOptions = new CSharpParseOptions(languageVersionCSharp);
            }
            else
            {
                fileExt      = VisualBasicDefaultExt;
                parseOptions = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions(languageVersionVB);
            }

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

#pragma warning disable CC0022
            var workspace = new AdhocWorkspace();
#pragma warning restore CC0022

            var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), TestProjectName,
                                                 TestProjectName, language,
                                                 parseOptions: parseOptions,
                                                 metadataReferences: ImmutableList.Create(
                                                     CorlibReference, SystemCoreReference, RegexReference,
                                                     CSharpSymbolsReference, CodeAnalysisReference, JsonNetReference));

            workspace.AddProject(projectInfo);

            var count = 0;
            foreach (var source in sources)
            {
                var newFileName = fileNamePrefix + count + "." + fileExt;
                workspace.AddDocument(projectId, newFileName, SourceText.From(source));
                count++;
            }

            var project = workspace.CurrentSolution.GetProject(projectId);
            var newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(diagOptions);
            var newSolution           = workspace.CurrentSolution.WithProjectCompilationOptions(projectId, newCompilationOptions);
            var newProject            = newSolution.GetProject(projectId);
            return(newProject);
        }
        /// <summary>
        /// Called to test a VB codefix when applied on the inputted string as a source
        /// </summary>
        /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param>
        /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param>
        /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param>
        /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param>
        /// <param name="formatBeforeCompare">Format the code before comparing, bot the old source and the new.</param>
        /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param>
        /// <param name="languageVersionVB">The VB language version.</param>
        protected async Task VerifyBasicFixAsync(string oldSource, string newSource, int?codeFixIndex = null, bool allowNewCompilerDiagnostics = false, bool formatBeforeCompare = false, CodeFixProvider codeFixProvider = null, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14)
        {
            if (formatBeforeCompare)
            {
                oldSource = await FormatSourceAsync(LanguageNames.VisualBasic, oldSource, languageVersionVB : languageVersionVB).ConfigureAwait(true);

                newSource = await FormatSourceAsync(LanguageNames.VisualBasic, newSource, languageVersionVB : languageVersionVB).ConfigureAwait(true);
            }
            codeFixProvider = codeFixProvider ?? GetCodeFixProvider();
            var diagnosticAnalyzer = GetDiagnosticAnalyzer();

            if (diagnosticAnalyzer != null)
            {
                await VerifyFixAsync(LanguageNames.VisualBasic, diagnosticAnalyzer, codeFixProvider, oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics, LanguageVersion.CSharp6, languageVersionVB).ConfigureAwait(true);
            }
            else
            {
                await VerifyFixAsync(LanguageNames.VisualBasic, codeFixProvider.FixableDiagnosticIds, codeFixProvider, oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics, LanguageVersion.CSharp6, languageVersionVB).ConfigureAwait(true);
            }
        }
        /// <summary>
        /// General verifier for a diagnostics that should not have fix registred.
        /// Creates a Document from the source string, then gets diagnostics on it and verify if it has no fix registred.
        /// It will fail the test if it has any fix registred to it
        /// </summary>
        /// <param name="language">The language the source code is in</param>
        /// <param name="analyzer">The analyzer to be applied to the source code</param>
        /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param>
        /// <param name="source">A class in the form of a string before the CodeFix was applied to it</param>
        /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
        /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
        private async static Task VerifyHasNoFixAsync(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string source, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var document            = CreateDocument(source, language, languageVersionCSharp, languageVersionVB);
            var analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzer, new[] { document }).ConfigureAwait(true);

            foreach (var analyzerDiagnostic in analyzerDiagnostics)
            {
                var actions = new List <CodeAction>();
                var context = new CodeFixContext(document, analyzerDiagnostic, (a, d) => actions.Add(a), CancellationToken.None);
                await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(true);

                Assert.False(actions.Any(), $"Should not have a code fix registered for diagnostic '{analyzerDiagnostic.Id}'");
            }
        }
        private async static Task VerifyFixAllAsync(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string[] oldSources, string[] newSources, bool allowNewCompilerDiagnostics, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB, string equivalenceKey = null)
        {
            var project             = CreateProject(oldSources, language, languageVersionCSharp, languageVersionVB);
            var compilerDiagnostics = (await Task.WhenAll(project.Documents.Select(d => GetCompilerDiagnosticsAsync(d))).ConfigureAwait(true)).SelectMany(d => d);
            var fixAllProvider      = codeFixProvider.GetFixAllProvider();

            if (equivalenceKey == null)
            {
                equivalenceKey = codeFixProvider.GetType().Name;
            }
            FixAllContext fixAllContext;

            if (analyzer != null)
            {
                var analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzer, project.Documents.ToArray()).ConfigureAwait(true);

                Func <Document, ImmutableHashSet <string>, CancellationToken, Task <IEnumerable <Diagnostic> > > getDocumentDiagnosticsAsync = (doc, ids, ct) =>
                                                                                                                                               Task.FromResult(analyzerDiagnostics.Where(d => d.Location.SourceTree.FilePath == doc.Name));
                Func <Project, bool, ImmutableHashSet <string>, CancellationToken, Task <IEnumerable <Diagnostic> > > getProjectDiagnosticsAsync = (proj, b, ids, ct) =>
                                                                                                                                                   Task.FromResult((IEnumerable <Diagnostic>)analyzerDiagnostics); //todo: verify, probably wrong
                var fixAllDiagnosticProvider = new FixAllDiagnosticProvider(codeFixProvider.FixableDiagnosticIds.ToImmutableHashSet(), getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync);
                fixAllContext = new FixAllContext(project.Documents.First(), codeFixProvider, FixAllScope.Solution,
                                                  equivalenceKey,
                                                  codeFixProvider.FixableDiagnosticIds,
                                                  fixAllDiagnosticProvider,
                                                  CancellationToken.None);
            }
            else
            {
                Func <Document, ImmutableHashSet <string>, CancellationToken, Task <IEnumerable <Diagnostic> > > getDocumentDiagnosticsAsync = async(doc, ids, ct) =>
                {
                    var compilerDiags = await GetCompilerDiagnosticsAsync(doc).ConfigureAwait(true);

                    return(compilerDiags.Where(d => codeFixProvider.FixableDiagnosticIds.Contains(d.Id)));
                };
                Func <Project, bool, ImmutableHashSet <string>, CancellationToken, Task <IEnumerable <Diagnostic> > > getProjectDiagnosticsAsync = async(proj, b, ids, ct) =>
                {
                    var theDocs = proj.Documents;
                    var diags   = await Task.WhenAll(theDocs.Select(d => getDocumentDiagnosticsAsync(d, ids, ct))).ConfigureAwait(true);

                    return(diags.SelectMany(d => d));
                };
                var fixAllDiagnosticProvider = new FixAllDiagnosticProvider(codeFixProvider.FixableDiagnosticIds.ToImmutableHashSet(), getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync);
                fixAllContext = new FixAllContext(project.Documents.First(), codeFixProvider, FixAllScope.Solution,
                                                  equivalenceKey,
                                                  codeFixProvider.FixableDiagnosticIds,
                                                  fixAllDiagnosticProvider,
                                                  CancellationToken.None);
            }
            var action = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(true);

            if (action == null)
            {
                throw new Exception("No action supplied for the code fix.");
            }
            project = await ApplyFixAsync(project, action).ConfigureAwait(true);

            //check if applying the code fix introduced any new compiler diagnostics
            var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, (await Task.WhenAll(project.Documents.Select(d => GetCompilerDiagnosticsAsync(d))).ConfigureAwait(true)).SelectMany(d => d));

            if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
            {
                Assert.True(false, $"Fix introduced new compiler diagnostics:\r\n{string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString()))}\r\n");
            }
            var docs = project.Documents.ToArray();

            for (int i = 0; i < docs.Length; i++)
            {
                var document = docs[i];
                var actual   = await GetStringFromDocumentAsync(document).ConfigureAwait(true);

                newSources[i].Should().Be(actual);
            }
        }
        private async static Task VerifyFixAllAsync(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string newSource, bool allowNewCompilerDiagnostics, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB, string equivalenceKey = null)
        {
            var document            = CreateDocument(oldSource, language, languageVersionCSharp, languageVersionVB);
            var compilerDiagnostics = await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true);

            var getDocumentDiagnosticsAsync = analyzer != null
                ? (Func <Document, ImmutableHashSet <string>, CancellationToken, Task <IEnumerable <Diagnostic> > >)(async(doc, ids, ct) =>
                                                                                                                     await GetSortedDiagnosticsFromDocumentsAsync(analyzer, new[] { doc }).ConfigureAwait(true))
                : (async(doc, ids, ct) =>
            {
                var compilerDiags = await GetCompilerDiagnosticsAsync(doc).ConfigureAwait(true);
                return(compilerDiags.Where(d => codeFixProvider.FixableDiagnosticIds.Contains(d.Id)));
            });
            Func <Project, bool, ImmutableHashSet <string>, CancellationToken, Task <IEnumerable <Diagnostic> > > getProjectDiagnosticsAsync = async(proj, b, ids, ct) =>
            {
                var theDocs = proj.Documents;
                var diags   = await Task.WhenAll(theDocs.Select(d => getDocumentDiagnosticsAsync?.Invoke(d, ids, ct))).ConfigureAwait(true);

                return(diags.SelectMany(d => d));
            };
            var fixAllProvider           = codeFixProvider.GetFixAllProvider();
            var fixAllDiagnosticProvider = new FixAllDiagnosticProvider(codeFixProvider.FixableDiagnosticIds.ToImmutableHashSet(), getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync);

            if (equivalenceKey == null)
            {
                equivalenceKey = codeFixProvider.GetType().Name;
            }
            var fixAllContext = new FixAllContext(document, codeFixProvider, FixAllScope.Document,
                                                  equivalenceKey,
                                                  codeFixProvider.FixableDiagnosticIds,
                                                  fixAllDiagnosticProvider,
                                                  CancellationToken.None);
            var action = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(true);

            if (action == null)
            {
                throw new Exception("No action supplied for the code fix.");
            }
            document = await ApplyFixAsync(document, action).ConfigureAwait(true);

            //check if applying the code fix introduced any new compiler diagnostics
            var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true));

            if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
            {
                // Format and get the compiler diagnostics again so that the locations make sense in the output
                document = document.WithSyntaxRoot(Formatter.Format(await document.GetSyntaxRootAsync().ConfigureAwait(true), Formatter.Annotation, document.Project.Solution.Workspace));
                newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true));
                Assert.True(false, $"Fix introduced new compiler diagnostics:\r\n{string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString()))}\r\n\r\nNew document:\r\n{(await document.GetSyntaxRootAsync().ConfigureAwait(true)).ToFullString()}\r\n");
            }
            var actual = await GetStringFromDocumentAsync(document).ConfigureAwait(true);

            Assert.Equal(newSource, actual);
        }
        protected async Task VerifyBasicFixAllAsync(string oldSource, string newSource, bool allowNewCompilerDiagnostics = false, bool formatBeforeCompare = true, CodeFixProvider codeFixProvider = null, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14, string equivalenceKey = null)
        {
            if (formatBeforeCompare)
            {
                oldSource = await FormatSourceAsync(LanguageNames.VisualBasic, oldSource, languageVersionVB : languageVersionVB).ConfigureAwait(true);

                newSource = await FormatSourceAsync(LanguageNames.VisualBasic, newSource, languageVersionVB : languageVersionVB).ConfigureAwait(true);
            }
            codeFixProvider = codeFixProvider ?? GetCodeFixProvider();
            await VerifyFixAllAsync(LanguageNames.VisualBasic, GetDiagnosticAnalyzer(), codeFixProvider, oldSource, newSource, allowNewCompilerDiagnostics, LanguageVersion.CSharp6, languageVersionVB, equivalenceKey).ConfigureAwait(true);
        }
        private async static Task VerifyFixAsync(string language, ImmutableArray <string> diagnosticIds, CodeFixProvider codeFixProvider, string oldSource, string newSource, int?codeFixIndex, bool allowNewCompilerDiagnostics, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var document            = CreateDocument(oldSource, language, languageVersionCSharp, languageVersionVB);
            var compilerDiagnostics = (await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true)).ToList();
            var analyzerDiagnostics = compilerDiagnostics.Where(c => diagnosticIds.Contains(c.Id)).ToList();
            var attempts            = analyzerDiagnostics.Count;

            for (int i = 0; i < attempts; ++i)
            {
                var actions = new List <CodeAction>();
                var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
                await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(true);

                if (!actions.Any())
                {
                    break;
                }

                document = codeFixIndex != null
                    ? await ApplyFixAsync(document, actions.ElementAt((int)codeFixIndex)).ConfigureAwait(true)
                    : await ApplyFixAsync(document, actions.ElementAt(0)).ConfigureAwait(true);

                var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true));
                compilerDiagnostics = (await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true)).ToList();
                analyzerDiagnostics = compilerDiagnostics.Where(c => diagnosticIds.Contains(c.Id)).ToList();

                //check if applying the code fix introduced any new compiler diagnostics
                if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
                {
                    // Format and get the compiler diagnostics again so that the locations make sense in the output
                    document = document.WithSyntaxRoot(Formatter.Format(await document.GetSyntaxRootAsync().ConfigureAwait(true), Formatter.Annotation, document.Project.Solution.Workspace));
                    newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true));

                    Assert.True(false, $"Fix introduced new compiler diagnostics:\r\n{string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString()))}\r\n\r\nNew document:\r\n{(await document.GetSyntaxRootAsync().ConfigureAwait(true)).ToFullString()}\r\n");
                }

                //check if there are analyzer diagnostics left after the code fix
                if (!analyzerDiagnostics.Any())
                {
                    break;
                }
            }

            //after applying all of the code fixes, compare the resulting string to the inputted one
            var actual = await GetStringFromDocumentAsync(document).ConfigureAwait(true);

            Assert.Equal(newSource, actual);
        }
Beispiel #8
0
 /// <summary>
 /// Given classes in the form of strings, their language, and an IDiagnosticAnlayzer to apply to it, return the diagnostics found in the string after converting it to a document.
 /// </summary>
 /// <param name="sources">Classes in the form of strings</param>
 /// <param name="language">The language the soruce classes are in</param>
 /// <param name="analyzer">The analyzer to be run on the sources</param>
 /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
 /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
 /// <returns>An IEnumerable of Diagnostics that surfaced in teh source code, sorted by Location</returns>
 private static async Task <Diagnostic[]> GetSortedDiagnosticsAsync(string[] sources, string language, DiagnosticAnalyzer analyzer, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) =>
 await GetSortedDiagnosticsFromDocumentsAsync(analyzer, GetDocuments(sources, language, languageVersionCSharp, languageVersionVB)).ConfigureAwait(true);
Beispiel #9
0
        public static async Task <string> FormatSourceAsync(string language, string source, LanguageVersion languageVersionCSharp = LanguageVersion.CSharp6, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14)
        {
            var document = CreateDocument(source, language, languageVersionCSharp, languageVersionVB);
            var newDoc   = await Formatter.FormatAsync(document).ConfigureAwait(true);

            return((await newDoc.GetSyntaxRootAsync().ConfigureAwait(true)).ToFullString());
        }
Beispiel #10
0
        /// <summary>
        /// Given an array of strings as sources and a language, turn them into a project and return the documents and spans of it.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
        /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
        /// <returns>A Tuple containing the Documents produced from the sources and thier TextSpans if relevant</returns>
        public static Document[] GetDocuments(string[] sources, string language, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            if (language != LanguageNames.CSharp && language != LanguageNames.VisualBasic)
            {
                throw new ArgumentException("Unsupported Language");
            }

            for (int i = 0; i < sources.Length; i++)
            {
                var fileName = language == LanguageNames.CSharp ? nameof(Test) + i + ".cs" : nameof(Test) + i + ".vb";
            }

            var project   = CreateProject(sources, language, languageVersionCSharp, languageVersionVB);
            var documents = project.Documents.ToArray();

            if (sources.Length != documents.Length)
            {
                throw new SystemException("Amount of sources did not match amount of Documents created");
            }

            return(documents);
        }
Beispiel #11
0
 /// <summary>
 /// Create a Document from a string through creating a project that contains it.
 /// </summary>
 /// <param name="source">Classes in the form of a string</param>
 /// <param name="language">The language the source code is in</param>
 /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
 /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
 /// <returns>A Document created from the source string</returns>
 public static Document CreateDocument(string source,
                                       string language,
                                       LanguageVersion languageVersionCSharp,
                                       Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) =>
 CreateProject(new[] { source }, language, languageVersionCSharp, languageVersionVB).Documents.First();
        /// <summary>
        /// General verifier for a diagnostics that verifies how many code actions a code fix registered.
        /// Creates a Document from the source string, then gets diagnostics on it and verify if it has x number of code actions registred.
        /// It will fail the test if it has a different number of code actions registred to it.
        /// </summary>
        /// <param name="language">The language the source code is in</param>
        /// <param name="analyzer">The analyzer to be applied to the source code</param>
        /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param>
        /// <param name="source">A class in the form of a string before the CodeFix was applied to it</param>
        /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
        /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
        /// <param name="numberOfCodeActions">The expected number of code actions provided by the code fix.</param>
        private async static Task VerifyNumberOfCodeActions(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string source, int numberOfCodeActions, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var document            = CreateDocument(source, language, languageVersionCSharp, languageVersionVB);
            var analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzer, new[] { document }).ConfigureAwait(true);

            foreach (var analyzerDiagnostic in analyzerDiagnostics)
            {
                var actions = new List <CodeAction>();
                var context = new CodeFixContext(document, analyzerDiagnostic, (a, d) => actions.Add(a), CancellationToken.None);
                await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(true);

                var numberOfCodeActionsFound = actions.Count();
                Assert.True(numberOfCodeActions == numberOfCodeActionsFound, $"Should have {numberOfCodeActions} code actions registered for diagnostic '{analyzerDiagnostic.Id}' but got {numberOfCodeActionsFound}.");
            }
        }
Beispiel #13
0
 /// <summary>
 /// Called to test a VB DiagnosticAnalyzer when applied on the inputted strings as a source
 /// Note: input a DiagnosticResult for each Diagnostic expected
 /// </summary>
 /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
 /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
 /// <param name="languageVersion">The VB language version, defaults to the latest stable version.</param>
 protected async Task VerifyBasicDiagnosticAsync(string[] sources, DiagnosticResult[] expected, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersion = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14) =>
 await VerifyDiagnosticsAsync(sources, LanguageNames.VisualBasic, GetDiagnosticAnalyzer(), expected, LanguageVersion.CSharp6, languageVersion).ConfigureAwait(true);
Beispiel #14
0
 protected async Task VerifyBasicDiagnosticAsync(string source, DiagnosticResult expected1, DiagnosticResult expected2, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14) =>
 await VerifyDiagnosticsAsync(new[] { source }, LanguageNames.VisualBasic, GetDiagnosticAnalyzer(), new[] { expected1, expected2 }, LanguageVersion.CSharp6, languageVersionVB).ConfigureAwait(true);
Beispiel #15
0
 protected async Task VerifyBasicHasNoDiagnosticsAsync(string[] sources, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14) =>
 await VerifyBasicDiagnosticAsync(sources, new DiagnosticResult[] { }, languageVersionVB).ConfigureAwait(true);
Beispiel #16
0
        /// <summary>
        /// General method that gets a collection of actual diagnostics found in the source after the analyzer is run,
        /// then verifies each of them.
        /// </summary>
        /// <param name="sources">An array of strings to create source documents from to run teh analyzers on</param>
        /// <param name="language">The language of the classes represented by the source strings</param>
        /// <param name="analyzer">The analyzer to be run on the source code</param>
        /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
        /// <param name="languageVersionCSharp">The C# language version, default to latest.</param>
        /// <param name="languageVersionVB">The VB language version, default to latest.</param>
        private async static Task VerifyDiagnosticsAsync(string[] sources, string language, DiagnosticAnalyzer analyzer, DiagnosticResult[] expected, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var diagnostics = await GetSortedDiagnosticsAsync(sources, language, analyzer, languageVersionCSharp, languageVersionVB).ConfigureAwait(true);

            var defaultFilePath = language == LanguageNames.CSharp ? CSharpDefaultFilePath : VisualBasicDefaultFilePath;

            VerifyDiagnosticResults(diagnostics, analyzer, defaultFilePath, expected);
        }