Example #1
0
        public async Task TestWorkspaceTryApplyChangesDirectCall()
        {
            using (var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(WorkspaceXml))
            {
                var solution = workspace.CurrentSolution;

                var documentId = workspace.Documents.Single(d => !d.IsLinkFile).Id;
                var text       = await workspace.CurrentSolution.GetDocument(documentId).GetTextAsync();

                var linkedDocumentId = workspace.Documents.Single(d => d.IsLinkFile).Id;
                var linkedText       = await workspace.CurrentSolution.GetDocument(linkedDocumentId).GetTextAsync();

                var newSolution = solution
                                  .WithDocumentText(documentId, text.Replace(13, 1, "D"))
                                  .WithDocumentText(linkedDocumentId, linkedText.Replace(0, 6, "private"));

                workspace.TryApplyChanges(newSolution);

                var expectedMergedText = "private class D { }";
                Assert.Equal(expectedMergedText, (await workspace.CurrentSolution.GetDocument(documentId).GetTextAsync()).ToString());
                Assert.Equal(expectedMergedText, (await workspace.CurrentSolution.GetDocument(linkedDocumentId).GetTextAsync()).ToString());
            }
        }
        protected async Task VerifyItemInLinkedFilesAsync(string xmlString, string expectedItem, string expectedDescription)
        {
            using (var testWorkspace = await TestWorkspaceFactory.CreateWorkspaceAsync(xmlString))
            {
                var optionsService           = testWorkspace.Services.GetService <IOptionService>();
                var position                 = testWorkspace.Documents.First().CursorPosition.Value;
                var solution                 = testWorkspace.CurrentSolution;
                var textContainer            = testWorkspace.Documents.First().TextBuffer.AsTextContainer();
                var currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer);
                var document                 = solution.GetDocument(currentContextDocumentId);

                var triggerInfo    = new CompletionTriggerInfo();
                var completionList = GetCompletionList(document, position, triggerInfo);

                var item = completionList.Items.Single(c => c.DisplayText == expectedItem);
                Assert.NotNull(item);
                if (expectedDescription != null)
                {
                    var actualDescription = item.GetDescriptionAsync().Result.GetFullText();
                    Assert.Equal(expectedDescription, actualDescription);
                }
            }
        }
        protected void VerifyItemInLinkedFiles(string xmlString, string expectedItem, string expectedDescription)
        {
            using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString))
            {
                var      optionsService           = testWorkspace.Services.GetService <IOptionService>();
                int      cursorPosition           = testWorkspace.Documents.First().CursorPosition.Value;
                var      solution                 = testWorkspace.CurrentSolution;
                var      textContainer            = testWorkspace.Documents.First().TextBuffer.AsTextContainer();
                var      currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer);
                Document doc = solution.GetDocument(currentContextDocumentId);

                CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo();
                var completions = CompletionProvider.GetGroupAsync(doc, cursorPosition, completionTriggerInfo).WaitAndGetResult(CancellationToken.None);

                var item = completions.Items.Single(c => c.DisplayText == expectedItem);
                Assert.NotNull(item);
                if (expectedDescription != null)
                {
                    var actualDescription = item.GetDescriptionAsync().Result.GetFullText();
                    Assert.Equal(expectedDescription, actualDescription);
                }
            }
        }
        private static async Task VerifyAgainstWorkspaceDefinitionAsync(string expectedText, Solution newSolution)
        {
            using (var expectedWorkspace = await TestWorkspaceFactory.CreateWorkspaceAsync(expectedText))
            {
                var expectedSolution = expectedWorkspace.CurrentSolution;
                Assert.Equal(expectedSolution.Projects.Count(), newSolution.Projects.Count());
                foreach (var project in newSolution.Projects)
                {
                    var expectedProject = expectedSolution.GetProjectsByName(project.Name).Single();
                    Assert.Equal(expectedProject.Documents.Count(), project.Documents.Count());

                    foreach (var doc in project.Documents)
                    {
                        var root = await doc.GetSyntaxRootAsync();

                        var expectedDocument = expectedProject.Documents.Single(d => d.Name == doc.Name);
                        var expectedRoot     = await expectedDocument.GetSyntaxRootAsync();

                        Assert.Equal(expectedRoot.ToFullString(), root.ToFullString());
                    }
                }
            }
        }
Example #5
0
        public void CanConstructPipeine()
        {
            var fileSystem = new Mock <IFileSystem>(MockBehavior.Strict).Object;
            var logger     = new Mock <ILogger>(MockBehavior.Loose).Object;

            var basePath = "z:\\fakepath";

            var workspaceManager = new WorkspaceManager(TestWorkspaceFactory.GetWorkspace());
            PipelineWorkspaceManagersWrapper workspaces = new PipelineWorkspaceManagersWrapper(workspaceManager, workspaceManager);
            BuilderRegistry builders = new BuilderRegistry();

            builders.Register <ICodeFileDestination>(new WorkspaceCodeFileDestinationBuilder(workspaces));
            builders.Register <ICodeFileSelector>(new CodeFileSelectorBuilder());

            var config = JObject.Parse(Resources.IntegrationTestConfig01);

            var subject = new PipelineBuilder(builders, workspaces, basePath, fileSystem, new DefaultTypeLoader(), logger);

            var result = subject.Build(config);

            result.Should().NotBeNull();

            var pipeline = result as CodeGenerationPipeline;

            pipeline.InputCodeStreamProvider.Should().NotBeNull();
            pipeline.PipelineEnvironment.Should().NotBeNull();

            pipeline.Batches.Should().NotBeNull();
            pipeline.Batches.Count.Should().Be(1);

            pipeline.Batches[0].Shadow.Should().NotBeNull();
            pipeline.Batches[0].Shadow.Count.Should().Be(1);
            pipeline.Batches[0].Shadow[0].Language.Should().Be("CSharp");
            pipeline.Batches[0].Shadow[0].Filter.Should().NotBeNull();
            pipeline.Batches[0].Shadow[0].Filter.Should().BeOfType <WorkspaceCodeFileLocationFilter>();
        }
        public static async Task <GenerateTypeTestState> CreateAsync(
            string initial,
            bool isLine,
            string projectToBeModified,
            string typeName,
            string existingFileName,
            string languageName)
        {
            var workspace = languageName == LanguageNames.CSharp
                  ? isLine ? await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(initial, exportProvider : s_exportProvider) : await TestWorkspaceFactory.CreateWorkspaceAsync(initial, exportProvider : s_exportProvider)
                  : isLine ? await VisualBasicWorkspaceFactory.CreateWorkspaceFromFileAsync(initial, exportProvider : s_exportProvider) : await TestWorkspaceFactory.CreateWorkspaceAsync(initial, exportProvider : s_exportProvider);

            return(new GenerateTypeTestState(projectToBeModified, typeName, existingFileName, workspace));
        }
        public static async Task <ChangeSignatureTestState> CreateAsync(XElement workspaceXml)
        {
            var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceXml);

            return(new ChangeSignatureTestState(workspace));
        }
Example #8
0
 public ChangeSignatureTestState(XElement workspaceXml) : this(TestWorkspaceFactory.CreateWorkspace(workspaceXml))
 {
 }
        public async Task SuggestionTagsForUnnecessaryCode()
        {
            var workspaceXml =
                @"<Workspace>
    <Project Language=""C#"" CommonReferences=""true"">
        <Document FilePath = ""Test.cs"" >
// System is used - rest are unused.
using System.Collections;
using System;
using System.Diagnostics;
using System.Collections.Generic;

class Program
{
    void Test()
    {
        Int32 x = 2; // Int32 can be simplified.
        x += 1;
    }
}
        </Document>
    </Project>
</Workspace>";

            using (var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceXml))
            {
                var analyzerMap = new Dictionary <string, DiagnosticAnalyzer[]>
                {
                    {
                        LanguageNames.CSharp,
                        new DiagnosticAnalyzer[]
                        {
                            new CSharpSimplifyTypeNamesDiagnosticAnalyzer(),
                            new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer()
                        }
                    }
                };

                var spans =
                    (await GetErrorSpans(workspace, analyzerMap))
                    .OrderBy(s => s.Span.Span.Start).ToImmutableArray();

                Assert.Equal(3, spans.Length);
                var first  = spans[0];
                var second = spans[1];
                var third  = spans[2];

                Assert.Equal(PredefinedErrorTypeNames.Suggestion, first.Tag.ErrorType);
                Assert.Equal(CSharpFeaturesResources.RemoveUnnecessaryUsingsDiagnosticTitle, first.Tag.ToolTipContent);
                Assert.Equal(40, first.Span.Start);
                Assert.Equal(25, first.Span.Length);

                Assert.Equal(PredefinedErrorTypeNames.Suggestion, second.Tag.ErrorType);
                Assert.Equal(CSharpFeaturesResources.RemoveUnnecessaryUsingsDiagnosticTitle, second.Tag.ToolTipContent);
                Assert.Equal(82, second.Span.Start);
                Assert.Equal(60, second.Span.Length);

                Assert.Equal(PredefinedErrorTypeNames.Suggestion, third.Tag.ErrorType);
                Assert.Equal(WorkspacesResources.NameCanBeSimplified, third.Tag.ToolTipContent);
                Assert.Equal(196, third.Span.Start);
                Assert.Equal(5, third.Span.Length);
            }
        }
        protected void Test(
            string initialMarkup,
            string expectedMarkup,
            ParseOptions parseOptions,
            CompilationOptions compilationOptions,
            int index          = 0,
            bool compareTokens = true,
            bool isLine        = true,
            IDictionary <OptionKey, object> options = null,
            bool isAddedDocument = false,
            string fixAllActionEquivalenceKey = null)
        {
            string expected;
            IDictionary <string, IList <TextSpan> > spanMap;

            MarkupTestFile.GetSpans(expectedMarkup.NormalizeLineEndings(), out expected, out spanMap);

            var conflictSpans = spanMap.GetOrAdd("Conflict", _ => new List <TextSpan>());
            var renameSpans   = spanMap.GetOrAdd("Rename", _ => new List <TextSpan>());
            var warningSpans  = spanMap.GetOrAdd("Warning", _ => new List <TextSpan>());

            using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup))
            {
                if (options != null)
                {
                    ApplyOptionsToWorkspace(options, workspace);
                }

                var diagnosticAndFixes = GetDiagnosticAndFix(workspace, fixAllActionEquivalenceKey);
                Assert.NotNull(diagnosticAndFixes);
                TestActions(
                    workspace, expected, index,
                    diagnosticAndFixes.Item2.Fixes.Select(f => f.Action).ToList(),
                    conflictSpans, renameSpans, warningSpans,
                    compareTokens: compareTokens,
                    isAddedDocument: isAddedDocument);
            }
        }
 private void TestAddDocument(
     string initialMarkup,
     string expected,
     int index,
     IList <string> expectedContainers,
     string expectedDocumentName,
     ParseOptions parseOptions,
     CompilationOptions compilationOptions,
     bool compareTokens,
     bool isLine)
 {
     using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup))
     {
         var diagnosticAndFix = GetDiagnosticAndFix(workspace);
         TestAddDocument(workspace, expected, index, expectedContainers, expectedDocumentName,
                         diagnosticAndFix.Item2.Fixes.Select(f => f.Action).ToList(), compareTokens);
     }
 }
        protected Tuple <Solution, Solution> TestActions(
            TestWorkspace workspace,
            string expectedText,
            IEnumerable <CodeActionOperation> operations,
            DocumentId expectedChangedDocumentId   = null,
            IList <TextSpan> expectedConflictSpans = null,
            IList <TextSpan> expectedRenameSpans   = null,
            IList <TextSpan> expectedWarningSpans  = null,
            bool compareTokens   = true,
            bool isAddedDocument = false)
        {
            var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
            var oldSolution    = appliedChanges.Item1;
            var newSolution    = appliedChanges.Item2;

            Document document = null;

            if (expectedText.TrimStart('\r', '\n', ' ').StartsWith(@"<Workspace>"))
            {
                using (var expectedWorkspace = TestWorkspaceFactory.CreateWorkspace(expectedText))
                {
                    var expectedSolution = expectedWorkspace.CurrentSolution;
                    Assert.Equal(expectedSolution.Projects.Count(), newSolution.Projects.Count());
                    foreach (var project in newSolution.Projects)
                    {
                        var expectedProject = expectedSolution.GetProjectsByName(project.Name).Single();
                        Assert.Equal(expectedProject.Documents.Count(), project.Documents.Count());

                        foreach (var doc in project.Documents)
                        {
                            var root             = doc.GetSyntaxRootAsync().Result;
                            var expectedDocument = expectedProject.Documents.Single(d => d.Name == doc.Name);
                            var expectedRoot     = expectedDocument.GetSyntaxRootAsync().Result;
                            Assert.Equal(expectedRoot.ToFullString(), root.ToFullString());
                        }
                    }
                }
            }
            else
            {
                // If the expectedChangedDocumentId is not mentioned then we expect only single document to be changed
                if (expectedChangedDocumentId == null)
                {
                    if (!isAddedDocument)
                    {
                        // This method assumes that only one document changed and rest(Project state) remains unchanged
                        document = SolutionUtilities.GetSingleChangedDocument(oldSolution, newSolution);
                    }
                    else
                    {
                        // This method assumes that only one document added and rest(Project state) remains unchanged
                        document = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
                        Assert.Empty(SolutionUtilities.GetChangedDocuments(oldSolution, newSolution));
                    }
                }
                else
                {
                    // This method obtains only the document changed and does not check the project state.
                    document = newSolution.GetDocument(expectedChangedDocumentId);
                }

                var fixedRoot  = document.GetSyntaxRootAsync().Result;
                var actualText = compareTokens ? fixedRoot.ToString() : fixedRoot.ToFullString();

                if (compareTokens)
                {
                    TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
                }
                else
                {
                    Assert.Equal(expectedText, actualText);
                }

                TestAnnotations(expectedText, expectedConflictSpans, fixedRoot, ConflictAnnotation.Kind, compareTokens);
                TestAnnotations(expectedText, expectedRenameSpans, fixedRoot, RenameAnnotation.Kind, compareTokens);
                TestAnnotations(expectedText, expectedWarningSpans, fixedRoot, WarningAnnotation.Kind, compareTokens);
            }

            return(Tuple.Create(oldSolution, newSolution));
        }
 private async Task TestAddDocument(
     string initialMarkup, string expectedMarkup,
     int index,
     IList <string> expectedContainers,
     string expectedDocumentName,
     ParseOptions parseOptions, CompilationOptions compilationOptions,
     bool compareTokens, bool isLine)
 {
     using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup))
     {
         var codeActions = GetCodeActions(workspace, fixAllActionEquivalenceKey: null);
         await TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName,
                               codeActions, compareTokens).ConfigureAwait(true);
     }
 }
Example #14
0
 public TypeSymbolsForTest()
 {
     this.Compilation = TestWorkspaceFactory.CompileCodeOrThrow(SourceCode, references: ThisAssemblyLocation);
 }