/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(UnitTestWorkspace workspace) { string fileNamePrefix = DefaultFilePathPrefix; var projectName = workspace.ProjectName ?? DefaultTestProjectName; var projectId = ProjectId.CreateNewId(debugName: projectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, projectName, projectName, LanguageNames.CSharp) .AddMetadataReference(projectId, CorlibReference) .AddMetadataReference(projectId, AttributeHolderReference) .AddMetadataReference(projectId, SystemCoreReference) .AddMetadataReference(projectId, CSharpSymbolsReference) .AddMetadataReference(projectId, CodeAnalysisReference) .AddMetadataReference(projectId, NUnitReference); int count = 0; foreach (var source in workspace.SourceFiles) { var newFileName = workspace.FileNames?.Length > count ? workspace.FileNames[count] : fileNamePrefix + count + "Tests." + CSharpDefaultFileExt; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return(solution.GetProject(projectId)); }
/// <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> /// <returns>A Tuple containing the Documents produced from the sources and their TextSpans if relevant</returns> private static Document[] GetDocuments(UnitTestWorkspace workspace) { var project = CreateProject(workspace); var documents = project.Documents.ToArray(); if (workspace.SourceFiles.Length != documents.Length) { throw new InvalidOperationException("Amount of sources did not match amount of Documents created"); } return(documents); }
/// <summary> /// Given classes in the form of strings, their language, and an IDiagnosticAnalyzer to apply to it, return the diagnostics found in the string after converting it to a document. /// </summary> /// <param name="workspace"></param> /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns> private static Diagnostic[] GetSortedDiagnostics(UnitTestWorkspace workspace) { return(GetSortedDiagnosticsFromDocuments(workspace.Analyzer, GetDocuments(workspace))); }
/// <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> protected static void Verify(UnitTestWorkspace workspace, params DiagnosticResult[] expected) { var diagnostics = GetSortedDiagnostics(workspace); Verify(diagnostics, workspace.Analyzer, expected); }