public async Task ErrorTagGeneratedForWarningAsError()
        {
            var workspaceXml =
                @"<Workspace>
    <Project Language=""C#"" CommonReferences=""true"">
        <CompilationOptions ReportDiagnostic = ""Error"" />
            <Document FilePath = ""Test.cs"" >
                class Program
                {
                    void Test()
                    {
                        int a = 5;
                    }
                }
        </Document>
    </Project>
</Workspace>";

            using (var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceXml))
            {
                var spans = await GetErrorSpans(workspace);

                Assert.Equal(1, spans.Count());
                Assert.Equal(PredefinedErrorTypeNames.SyntaxError, spans.First().Tag.ErrorType);
            }
        }
示例#2
0
        public static async Task <CallHierarchyTestState> CreateAsync(XElement markup, params Type[] additionalTypes)
        {
            var exportProvider = CreateExportProvider(additionalTypes);
            var workspace      = await TestWorkspaceFactory.CreateWorkspaceAsync(markup, exportProvider : exportProvider);

            return(new CallHierarchyTestState(workspace));
        }
        protected async Task VerifyItemWithReferenceWorkerAsync(string xmlString, IEnumerable <SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers)
        {
            using (var testWorkspace = await TestWorkspaceFactory.CreateWorkspaceAsync(xmlString))
            {
                var optionsService = testWorkspace.Services.GetService <IOptionService>();
                var cursorPosition = testWorkspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
                var documentId     = testWorkspace.Documents.First(d => d.Name == "SourceDocument").Id;
                var document       = testWorkspace.CurrentSolution.GetDocument(documentId);
                var code           = (await document.GetTextAsync()).ToString();

                optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(Microsoft.CodeAnalysis.Completion.CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers));

                IList <TextSpan> textSpans = null;

                var selectedSpans = testWorkspace.Documents.First(d => d.Name == "SourceDocument").SelectedSpans;
                if (selectedSpans.Any())
                {
                    textSpans = selectedSpans;
                }

                TextSpan?textSpan = null;
                if (textSpans != null && textSpans.Any())
                {
                    textSpan = textSpans.First();
                }

                await TestSignatureHelpWorkerSharedAsync(code, cursorPosition, SourceCodeKind.Regular, document, textSpan, expectedOrderedItems);
            }
        }
        public async Task LiveErrorZeroLengthSpan()
        {
            var workspaceXml =
                @"<Workspace>
    <Project Language=""C#"" CommonReferences=""true"">
        <Document FilePath = ""Test.cs"" >
            class Test
{
}
        </Document>
    </Project>
</Workspace>";

            using (var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceXml))
            {
                var document = workspace.Documents.First();

                var updateArgs = DiagnosticsUpdatedArgs.DiagnosticsCreated(
                    new LiveId(), workspace, workspace.CurrentSolution, document.Project.Id, document.Id,
                    ImmutableArray.Create(
                        CreateDiagnosticData(workspace, document, new TextSpan(0, 0)),
                        CreateDiagnosticData(workspace, document, new TextSpan(0, 1))));

                var spans = await GetErrorsFromUpdateSource(workspace, document, updateArgs);

                Assert.Equal(2, spans.Count());
                var first  = spans.First();
                var second = spans.Last();

                Assert.Equal(1, first.Span.Span.Length);
                Assert.Equal(1, second.Span.Span.Length);
            }
        }
        public async Task ExtractInterfaceCommandDisabledInSubmission()
        {
            var exportProvider = MinimalTestExportProvider.CreateExportProvider(
                TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveDocumentSupportsFeatureService)));

            using (var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(XElement.Parse(@"
                <Workspace>
                    <Submission Language=""C#"" CommonReferences=""true"">  
                        public class $$C
                        {
                            public void M() { }
                        }
                    </Submission>
                </Workspace> "),
                                                                                   workspaceKind: WorkspaceKind.Interactive,
                                                                                   exportProvider: exportProvider))
            {
                // Force initialization.
                workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList();

                var textView = workspace.Documents.Single().GetTextView();

                var handler                     = new ExtractInterfaceCommandHandler();
                var delegatedToNext             = false;
                Func <CommandState> nextHandler = () =>
                {
                    delegatedToNext = true;
                    return(CommandState.Unavailable);
                };

                var state = handler.GetCommandState(new Commands.ExtractInterfaceCommandArgs(textView, textView.TextBuffer), nextHandler);
                Assert.True(delegatedToNext);
                Assert.False(state.IsAvailable);
            }
        }
示例#6
0
        protected async Task TestAsync(
            string initialMarkup, string expectedMarkup,
            ParseOptions parseOptions, CompilationOptions compilationOptions,
            int index = 0, bool compareTokens = true,
            IDictionary <OptionKey, object> options = null,
            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 = IsWorkspaceElement(initialMarkup)
                ? await TestWorkspaceFactory.CreateWorkspaceAsync(initialMarkup)
                : await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions))
            {
                ApplyOptionsToWorkspace(workspace, options);

                var actions = await GetCodeActionsAsync(workspace, fixAllActionEquivalenceKey);
                await TestActionsAsync(
                    workspace, expected, index,
                    actions,
                    conflictSpans, renameSpans, warningSpans,
                    compareTokens : compareTokens);
            }
        }
示例#7
0
        private static Task <TestWorkspace> CreateTestWorkspaceAsync(string code, string languageName, ExportProvider exportProvider = null)
        {
            var xml = string.Format(@"
<Workspace>
    <Project Language=""{0}"" CommonReferences=""true"">
        <Document>{1}</Document>
    </Project>
</Workspace>", languageName, code);

            return(TestWorkspaceFactory.CreateWorkspaceAsync(xml, exportProvider: exportProvider));
        }
        private async Task VerifyItemWithMscorlib45WorkerAsync(string xmlString, string expectedItem, string expectedDescription)
        {
            using (var testWorkspace = await TestWorkspaceFactory.CreateWorkspaceAsync(xmlString))
            {
                var position   = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
                var solution   = testWorkspace.CurrentSolution;
                var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id;
                var document   = solution.GetDocument(documentId);

                var triggerInfo    = new CompletionTriggerInfo();
                var completionList = GetCompletionList(document, position, triggerInfo);
                var item           = completionList.Items.FirstOrDefault(i => i.DisplayText == expectedItem);
                Assert.Equal(expectedDescription, item.GetDescriptionAsync().Result.GetFullText());
            }
        }
示例#9
0
        public async Task TestCodeActionPreviewAndApply()
        {
            using (var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(WorkspaceXml))
            {
                var codeIssueOrRefactoring = GetCodeRefactoring(workspace);

                var expectedCode = "private class D { }";

                await TestActionsOnLinkedFiles(
                    workspace,
                    expectedText : expectedCode,
                    index : 0,
                    actions : codeIssueOrRefactoring.Actions.ToList(),
                    expectedPreviewContents : expectedCode);
            }
        }
 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
         ? await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions)
         : await TestWorkspaceFactory.CreateWorkspaceAsync(initialMarkup))
     {
         var codeActions = await GetCodeActionsAsync(workspace, fixAllActionEquivalenceKey : null);
         await TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName,
                               codeActions, compareTokens);
     }
 }
示例#11
0
        public async Task NoNavigationToGeneratedFiles()
        {
            using (var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(@"
<Workspace>
    <Project Language=""C#"" CommonReferences=""true"">
        <Document FilePath=""File1.cs"">
            namespace N
            {
                public partial class C
                {
                    public void VisibleMethod() { }
                }
            }
        </Document>
        <Document FilePath=""File1.g.cs"">
            namespace N
            {
                public partial class C
                {
                    public void VisibleMethod_Not() { }
                }
            }
        </Document>
    </Project>
</Workspace>
"))
            {
                var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener();

                _provider   = new NavigateToItemProvider(workspace, _glyphServiceMock.Object, aggregateListener);
                _aggregator = new NavigateToTestAggregator(_provider);

                var items         = _aggregator.GetItems("VisibleMethod");
                var expectedItems = new List <NavigateToItem>()
                {
                    new NavigateToItem("VisibleMethod", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null)
                };

                // The pattern matcher should match 'VisibleMethod' to both 'VisibleMethod' and 'VisibleMethod_Not', except that
                // the _Not method is declared in a generated file.
                VerifyNavigateToResultItems(expectedItems, items);
            }
        }
        private async Task VerifyItemWithReferenceWorkerAsync(string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers)
        {
            using (var testWorkspace = await TestWorkspaceFactory.CreateWorkspaceAsync(xmlString))
            {
                var optionsService = testWorkspace.Services.GetService <IOptionService>();
                var position       = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
                var solution       = testWorkspace.CurrentSolution;
                var documentId     = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id;
                var document       = solution.GetDocument(documentId);

                optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers));

                var triggerInfo = new CompletionTriggerInfo();

                var completionList = await GetCompletionListAsync(document, position, triggerInfo);

                if (expectedSymbols >= 1)
                {
                    AssertEx.Any(completionList.Items, c => CompareItems(c.DisplayText, expectedItem));

                    // Throw if multiple to indicate a bad test case
                    var description = await completionList.Items.Single(c => CompareItems(c.DisplayText, expectedItem)).GetDescriptionAsync();

                    if (expectedSymbols == 1)
                    {
                        Assert.DoesNotContain("+", description.GetFullText(), StringComparison.Ordinal);
                    }
                    else
                    {
                        Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.GetFullText(), StringComparison.Ordinal);
                    }
                }
                else
                {
                    if (completionList != null)
                    {
                        AssertEx.None(completionList.Items, c => CompareItems(c.DisplayText, expectedItem));
                    }
                }
            }
        }
        protected async Task TestSignatureHelpWithMscorlib45Async(
            string markup,
            IEnumerable <SignatureHelpTestItem> expectedOrderedItems,
            string sourceLanguage)
        {
            var xmlString = string.Format(@"
<Workspace>
    <Project Language=""{0}"" CommonReferencesNet45=""true"">
        <Document FilePath=""SourceDocument"">
{1}
        </Document>
    </Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup));

            using (var testWorkspace = await TestWorkspaceFactory.CreateWorkspaceAsync(xmlString))
            {
                var cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
                var documentId     = testWorkspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
                var document       = testWorkspace.CurrentSolution.GetDocument(documentId);
                var code           = (await document.GetTextAsync()).ToString();

                IList <TextSpan> textSpans = null;

                var selectedSpans = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").SelectedSpans;
                if (selectedSpans.Any())
                {
                    textSpans = selectedSpans;
                }

                TextSpan?textSpan = null;
                if (textSpans != null && textSpans.Any())
                {
                    textSpan = textSpans.First();
                }

                await TestSignatureHelpWorkerSharedAsync(code, cursorPosition, SourceCodeKind.Regular, document, textSpan, expectedOrderedItems);
            }
        }
            private static Task <TestWorkspace> CreateWorkspaceAsync(string projectLanguage, IEnumerable <string> metadataSources, bool includeXmlDocComments, string sourceWithSymbolReference)
            {
                var xmlString = string.Concat(@"
<Workspace>
    <Project Language=""", projectLanguage, @""" CommonReferences=""true"">");

                metadataSources = metadataSources ?? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource };

                foreach (var source in metadataSources)
                {
                    var metadataLanguage = DeduceLanguageString(source);

                    xmlString = string.Concat(xmlString, string.Format(@"
        <MetadataReferenceFromSource Language=""{0}"" CommonReferences=""true"" IncludeXmlDocComments=""{2}"">
            <Document FilePath=""MetadataDocument"">
{1}
            </Document>
        </MetadataReferenceFromSource>",
                                                                       metadataLanguage,
                                                                       SecurityElement.Escape(source),
                                                                       includeXmlDocComments.ToString()));
                }

                if (sourceWithSymbolReference != null)
                {
                    xmlString = string.Concat(xmlString, string.Format(@"
        <Document FilePath=""SourceDocument"">
{0}
        </Document>",
                                                                       sourceWithSymbolReference));
                }

                xmlString = string.Concat(xmlString, @"
    </Project>
</Workspace>");

                return(TestWorkspaceFactory.CreateWorkspaceAsync(xmlString));
            }
示例#15
0
        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());
                    }
                }
            }
        }
示例#16
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       = workspace.CurrentSolution.GetDocument(documentId).GetTextAsync().Result;

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

                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, workspace.CurrentSolution.GetDocument(documentId).GetTextAsync().Result.ToString());
                Assert.Equal(expectedMergedText, workspace.CurrentSolution.GetDocument(linkedDocumentId).GetTextAsync().Result.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 = await GetCompletionListAsync(document, position, triggerInfo);

                var item = completionList.Items.Single(c => c.DisplayText == expectedItem);
                Assert.NotNull(item);
                if (expectedDescription != null)
                {
                    var actualDescription = (await item.GetDescriptionAsync()).GetFullText();
                    Assert.Equal(expectedDescription, actualDescription);
                }
            }
        }
示例#18
0
        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 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);
            }
        }
示例#20
0
        public static async Task <ChangeSignatureTestState> CreateAsync(XElement workspaceXml)
        {
            var workspace = await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceXml);

            return(new ChangeSignatureTestState(workspace));
        }