コード例 #1
0
        private async Task InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp)
        {
            using (var workspace = await TestWorkspace.CreateAsync(
                       SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: code))
            {
                var analyzer   = new Analyzer();
                var lazyWorker = new Lazy <IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
                var service    = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));

                service.Register(workspace);

                var testDocument = workspace.Documents.First();

                var insertPosition = testDocument.CursorPosition;
                var textBuffer     = testDocument.GetTextBuffer();

                using (var edit = textBuffer.CreateEdit())
                {
                    edit.Insert(insertPosition.Value, text);
                    edit.Apply();
                }

                await WaitAsync(service, workspace);

                service.Unregister(workspace);

                Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
                Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count);
            }
        }
コード例 #2
0
        protected async Task AssertNavigatedAsync(string code, bool next, SourceCodeKind?sourceCodeKind = null)
        {
            var kinds = sourceCodeKind != null
                ? SpecializedCollections.SingletonEnumerable(sourceCodeKind.Value)
                : new[] { SourceCodeKind.Regular, SourceCodeKind.Script };

            foreach (var kind in kinds)
            {
                using (var workspace = await TestWorkspace.CreateAsync(
                           LanguageName,
                           compilationOptions: null,
                           parseOptions: DefaultParseOptions.WithKind(kind),
                           content: code))
                {
                    var hostDocument = workspace.DocumentWithCursor;
                    var document     = workspace.CurrentSolution.GetDocument(hostDocument.Id);
                    Assert.Empty((await document.GetSyntaxTreeAsync()).GetDiagnostics());
                    var targetPosition = await GoToAdjacentMemberCommandHandler.GetTargetPositionAsync(
                        document,
                        hostDocument.CursorPosition.Value,
                        next,
                        CancellationToken.None);

                    Assert.NotNull(targetPosition);
                    Assert.Equal(hostDocument.SelectedSpans.Single().Start, targetPosition.Value);
                }
            }
        }
コード例 #3
0
        public async Task ExtractInterfaceCommandDisabledInSubmission()
        {
            var exportProvider = MinimalTestExportProvider.CreateExportProvider(
                TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveDocumentSupportsFeatureService)));

            using (var workspace = await TestWorkspace.CreateAsync(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);
            }
        }
コード例 #4
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 TestWorkspace.CreateAsync(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);
            }
        }
コード例 #5
0
        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 TestWorkspace.CreateAsync(workspaceXml))
            {
                var spans = (await GetDiagnosticsAndErrorSpans(workspace)).Item2;

                Assert.Equal(1, spans.Count());
                Assert.Equal(PredefinedErrorTypeNames.SyntaxError, spans.First().Tag.ErrorType);
            }
        }
コード例 #6
0
        protected async Task <TestWorkspace> SetupWorkspaceAsync(XElement workspaceElement)
        {
            var workspace = await TestWorkspace.CreateAsync(workspaceElement, exportProvider : s_exportProvider);

            InitializeWorkspace(workspace);
            return(workspace);
        }
コード例 #7
0
        protected async Task VerifyItemWithReferenceWorkerAsync(string xmlString, IEnumerable <SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers)
        {
            using (var testWorkspace = await TestWorkspace.CreateAsync(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);
            }
        }
コード例 #8
0
        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 TestWorkspace.CreateAsync(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);
            }
        }
コード例 #9
0
        public static async Task <CallHierarchyTestState> CreateAsync(XElement markup, params Type[] additionalTypes)
        {
            var exportProvider = CreateExportProvider(additionalTypes);
            var workspace      = await TestWorkspace.CreateAsync(markup, exportProvider : exportProvider);

            return(new CallHierarchyTestState(workspace));
        }
コード例 #10
0
        protected async Task VerifyItemInLinkedFilesAsync(string xmlString, string expectedItem, string expectedDescription)
        {
            using (var testWorkspace = await TestWorkspace.CreateAsync(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    = CompletionTrigger.Default;
                var completionList = await GetCompletionListAsync(document, position, triggerInfo);

                var completionService = document.Project.LanguageServices.GetService <CompletionService>();

                var item = completionList.Items.Single(c => c.DisplayText == expectedItem);
                Assert.NotNull(item);
                if (expectedDescription != null)
                {
                    var actualDescription = (await completionService.GetDescriptionAsync(document, item)).Text;
                    Assert.Equal(expectedDescription, actualDescription);
                }
            }
        }
コード例 #11
0
        protected static async Task RunCountTest(XElement input, int cap = 0)
        {
            using (var workspace = await TestWorkspace.CreateAsync(input))
            {
                foreach (var annotatedDocument in workspace.Documents.Where(d => d.AnnotatedSpans.Any()))
                {
                    var document   = workspace.CurrentSolution.GetDocument(annotatedDocument.Id);
                    var syntaxNode = await document.GetSyntaxRootAsync();

                    foreach (var annotatedSpan in annotatedDocument.AnnotatedSpans)
                    {
                        var isCapped = annotatedSpan.Key.StartsWith("capped");
                        var expected = int.Parse(annotatedSpan.Key.Substring(isCapped ? 6 : 0));

                        foreach (var span in annotatedSpan.Value)
                        {
                            var declarationSyntaxNode = syntaxNode.FindNode(span);
                            var result = await new CodeLensReferencesService().GetReferenceCountAsync(workspace.CurrentSolution, annotatedDocument.Id,
                                                                                                      declarationSyntaxNode, cap, CancellationToken.None);
                            Assert.NotNull(result);
                            Assert.Equal(expected, result.Count);
                            Assert.Equal(isCapped, result.IsCapped);
                        }
                    }
                }
            }
        }
コード例 #12
0
        private async Task TestAsync(
            string initialMarkup, string expectedMarkup,
            ParseOptions parseOptions, CompilationOptions compilationOptions,
            int index, bool compareTokens,
            IDictionary <OptionKey, object> options,
            string fixAllActionEquivalenceKey,
            object fixProviderData,
            CodeActionPriority?priority)
        {
            MarkupTestFile.GetSpans(expectedMarkup.NormalizeLineEndings(), out var expected, out IDictionary <string, IList <TextSpan> > 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 TestWorkspace.CreateAsync(initialMarkup)
                : await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions))
            {
                workspace.ApplyOptions(options);

                var actions = await GetCodeActionsAsync(workspace, fixAllActionEquivalenceKey, fixProviderData);
                await TestActionsAsync(
                    workspace, expected, index,
                    actions,
                    conflictSpans, renameSpans, warningSpans,
                    compareTokens : compareTokens,
                    parseOptions : parseOptions,
                    priority : priority);
            }
        }
コード例 #13
0
        public async Task CrefCompletionSpeculatesOutsideTrivia()
        {
            var text = @"
/// <see cref=""$$
class C
{
}";

            using (var workspace = await TestWorkspace.CreateAsync(LanguageNames.CSharp, new CSharpCompilationOptions(OutputKind.ConsoleApplication), new CSharpParseOptions(), new[] { text }))
            {
                var called   = false;
                var provider = new CrefCompletionProvider(testSpeculativeNodeCallbackOpt: n =>
                {
                    // asserts that we aren't be asked speculate on nodes inside documentation trivia.
                    // This verifies that the provider is asking for a speculative SemanticModel
                    // by walking to the node the documentation is attached to.

                    called     = true;
                    var parent = n.GetAncestor <DocumentationCommentTriviaSyntax>();
                    Assert.Null(parent);
                });

                var hostDocument = workspace.DocumentWithCursor;
                var document     = workspace.CurrentSolution.GetDocument(hostDocument.Id);
                var service      = CreateCompletionService(workspace,
                                                           ImmutableArray.Create <CompletionProvider>(provider));
                var completionList = await GetCompletionListAsync(service, document, hostDocument.CursorPosition.Value, CompletionTrigger.Invoke);

                Assert.True(called);
            }
        }
コード例 #14
0
        protected static async Task RunMethodReferenceTest(XElement input)
        {
            using (var workspace = await TestWorkspace.CreateAsync(input))
            {
                foreach (var annotatedDocument in workspace.Documents.Where(d => d.AnnotatedSpans.Any()))
                {
                    var document   = workspace.CurrentSolution.GetDocument(annotatedDocument.Id);
                    var syntaxNode = await document.GetSyntaxRootAsync();

                    foreach (var annotatedSpan in annotatedDocument.AnnotatedSpans)
                    {
                        var expected = int.Parse(annotatedSpan.Key);

                        foreach (var span in annotatedSpan.Value)
                        {
                            var declarationSyntaxNode = syntaxNode.FindNode(span);
                            var result = await new CodeLensReferencesService().FindReferenceMethodsAsync(workspace.CurrentSolution,
                                                                                                         annotatedDocument.Id, declarationSyntaxNode, CancellationToken.None);
                            var count = result.Count();
                            Assert.Equal(expected, count);
                        }
                    }
                }
            }
        }
コード例 #15
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(TestWorkspace.CreateAsync(xml, exportProvider: exportProvider));
        }
コード例 #16
0
        protected async Task <TestWorkspace> CreateWorkspaceFromOptionsAsync(
            string initialMarkup, TestParameters parameters)
        {
            var workspace = TestWorkspace.IsWorkspaceElement(initialMarkup)
                 ? await TestWorkspace.CreateAsync(initialMarkup)
                 : await CreateWorkspaceFromFileAsync(initialMarkup, parameters);

            workspace.ApplyOptions(parameters.options);

            return(workspace);
        }
コード例 #17
0
        public static async Task <RenameTrackingTestState> CreateFromWorkspaceXmlAsync(
            string workspaceXml,
            string languageName,
            bool onBeforeGlobalSymbolRenamedReturnValue = true,
            bool onAfterGlobalSymbolRenamedReturnValue  = true)
        {
            var workspace = await TestWorkspace.CreateAsync(
                workspaceXml,
                exportProvider : TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic());

            return(new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue));
        }
コード例 #18
0
        public static async Task <RenameTrackingTestState> CreateFromWorkspaceXmlAsync(
            string workspaceXml,
            string languageName,
            bool onBeforeGlobalSymbolRenamedReturnValue = true,
            bool onAfterGlobalSymbolRenamedReturnValue  = true)
        {
            var workspace = await TestWorkspace.CreateAsync(
                workspaceXml,
                exportProvider : EditorServicesUtil.CreateExportProvider());

            return(new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue));
        }
コード例 #19
0
        protected async Task VerifyNoRegionsAsync(string markupCode)
        {
            using (var workspace = await TestWorkspace.CreateAsync(WorkspaceKind, LanguageName, compilationOptions: null, parseOptions: null, content: markupCode))
            {
                var hostDocument = workspace.Documents.Single();
                Assert.True(hostDocument.CursorPosition.HasValue, "Test must specify a position.");
                var position = hostDocument.CursorPosition.Value;

                var document      = workspace.CurrentSolution.GetDocument(hostDocument.Id);
                var actualRegions = await GetRegionsAsync(document, position);

                Assert.True(actualRegions.Length == 0, $"Expected no regions but found {actualRegions.Length}.");
            }
        }
コード例 #20
0
        public static async Task <GenerateTypeTestState> CreateAsync(
            string initial,
            string projectToBeModified,
            string typeName,
            string existingFileName,
            string languageName)
        {
            var workspace = TestWorkspace.IsWorkspaceElement(initial)
                ? await TestWorkspace.CreateAsync(initial, exportProvider : s_exportProvider)
                : languageName == LanguageNames.CSharp
                  ? await TestWorkspace.CreateCSharpAsync(initial, exportProvider : s_exportProvider)
                  : await TestWorkspace.CreateVisualBasicAsync(initial, exportProvider : s_exportProvider);

            return(new GenerateTypeTestState(projectToBeModified, typeName, existingFileName, workspace));
        }
コード例 #21
0
        public async Task TestCodeActionPreviewAndApply()
        {
            using (var workspace = await TestWorkspace.CreateAsync(WorkspaceXml))
            {
                var codeIssueOrRefactoring = await GetCodeRefactoringAsync(workspace, new TestParameters());

                var expectedCode = "private class D { }";

                await TestActionsOnLinkedFiles(
                    workspace,
                    expectedText : expectedCode,
                    index : 0,
                    actions : codeIssueOrRefactoring.Actions.ToList(),
                    expectedPreviewContents : expectedCode);
            }
        }
コード例 #22
0
        private async Task VerifyItemWithMscorlib45WorkerAsync(string xmlString, string expectedItem, string expectedDescription)
        {
            using (var testWorkspace = await TestWorkspace.CreateAsync(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 = await GetCompletionListAsync(document, position, triggerInfo);

                var item = completionList.Items.FirstOrDefault(i => i.DisplayText == expectedItem);
                Assert.Equal(expectedDescription, (await item.GetDescriptionAsync()).GetFullText());
            }
        }
コード例 #23
0
        public async Task NavigateToGeneratedFiles()
        {
            using (var workspace = await TestWorkspace.CreateAsync(@"
<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_Generated() { }
                }
            }
        </Document>
    </Project>
</Workspace>
", exportProvider: s_exportProvider))
            {
                var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener();

                _provider = new NavigateToItemProvider(
                    workspace, _glyphServiceMock.Object, aggregateListener,
                    workspace.ExportProvider.GetExportedValues <Lazy <INavigateToHostVersionService, VisualStudioVersionMetadata> >());
                _aggregator = new NavigateToTestAggregator(_provider);

                var items = await _aggregator.GetItemsAsync("VisibleMethod");

                var expectedItems = new List <NavigateToItem>()
                {
                    new NavigateToItem("VisibleMethod", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null),
                    new NavigateToItem("VisibleMethod_Generated", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, 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);
            }
        }
コード例 #24
0
 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 TestWorkspace.CreateAsync(initialMarkup))
     {
         var codeActions = await GetCodeActionsAsync(workspace, fixAllActionEquivalenceKey : null);
         await TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName,
                               codeActions, compareTokens);
     }
 }
コード例 #25
0
        private async Task VerifyItemWithReferenceWorkerAsync(string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers)
        {
            using (var testWorkspace = await TestWorkspace.CreateAsync(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 = CompletionTrigger.Default;

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

                var completionService = document.Project.LanguageServices.GetService <CompletionService>();

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

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

                    if (expectedSymbols == 1)
                    {
                        Assert.DoesNotContain("+", description.Text, StringComparison.Ordinal);
                    }
                    else
                    {
                        Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.Text, StringComparison.Ordinal);
                    }
                }
                else
                {
                    if (completionList != null)
                    {
                        AssertEx.None(completionList.Items, c => CompareItems(c.DisplayText, expectedItem));
                    }
                }
            }
        }
コード例 #26
0
        protected async Task <int?> GetTargetPositionAsync(string code, bool next)
        {
            using (var workspace = await TestWorkspace.CreateAsync(
                       LanguageName,
                       compilationOptions: null,
                       parseOptions: DefaultParseOptions,
                       content: code))
            {
                var hostDocument = workspace.DocumentWithCursor;
                var document     = workspace.CurrentSolution.GetDocument(hostDocument.Id);
                Assert.Empty((await document.GetSyntaxTreeAsync()).GetDiagnostics());

                return(await GoToAdjacentMemberCommandHandler.GetTargetPositionAsync(
                           document,
                           hostDocument.CursorPosition.Value,
                           next,
                           CancellationToken.None));
            }
        }
コード例 #27
0
        public async void TestResetREPLWithProjectContext()
        {
            using (var workspace = await TestWorkspace.CreateAsync(WorkspaceXmlStr))
            {
                var project  = workspace.CurrentSolution.Projects.FirstOrDefault(p => p.AssemblyName == "ResetInteractiveTestsAssembly");
                var document = project.Documents.FirstOrDefault(d => d.FilePath == "ResetInteractiveTestsDocument");
                var replReferenceCommands = GetProjectReferences(workspace, project).Select(r => CreateReplReferenceCommand(r));

                Assert.True(replReferenceCommands.Any(rc => rc.EndsWith(@"ResetInteractiveTestsAssembly.dll""")));
                Assert.True(replReferenceCommands.Any(rc => rc.EndsWith(@"ResetInteractiveVisualBasicSubproject.dll""")));

                var expectedSubmissions = new List <string> {
                    string.Join("\r\n", replReferenceCommands) + "\r\n",
                    string.Join("\r\n", @"using ""ns1"";", @"using ""ns2"";") + "\r\n"
                };
                AssertResetInteractive(workspace, project, buildSucceeds: true, expectedSubmissions: expectedSubmissions);

                // Test that no submissions are executed if the build fails.
                AssertResetInteractive(workspace, project, buildSucceeds: false, expectedSubmissions: new List <string>());
            }
        }
コード例 #28
0
        protected async Task VerifyRegionsAsync(string markupCode, params Tuple <string, string, string, bool, bool>[] expectedRegionData)
        {
            using (var workspace = await TestWorkspace.CreateAsync(WorkspaceKind, LanguageName, compilationOptions: null, parseOptions: null, content: markupCode))
            {
                var hostDocument = workspace.Documents.Single();
                Assert.True(hostDocument.CursorPosition.HasValue, "Test must specify a position.");
                var position = hostDocument.CursorPosition.Value;

                var expectedRegions = expectedRegionData.Select(data => CreateOutliningSpan(data, hostDocument.AnnotatedSpans)).ToArray();

                var document      = workspace.CurrentSolution.GetDocument(hostDocument.Id);
                var actualRegions = await GetRegionsAsync(document, position);

                Assert.True(expectedRegions.Length == actualRegions.Length, $"Expected {expectedRegions.Length} regions but there were {actualRegions.Length}");

                for (int i = 0; i < expectedRegions.Length; i++)
                {
                    AssertRegion(expectedRegions[i], actualRegions[i]);
                }
            }
        }
コード例 #29
0
        public async Task CrefCompletionSpeculatesOutsideTrivia()
        {
            var text           = @"
/// <see cref=""$$
class C
{
}";
            var exportProvider = MinimalTestExportProvider.CreateExportProvider(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithPart(typeof(PickySemanticFactsService)));

            using (var workspace = await TestWorkspace.CreateAsync(LanguageNames.CSharp, new CSharpCompilationOptions(OutputKind.ConsoleApplication), new CSharpParseOptions(), new[] { text }, exportProvider))
            {
                // This test uses MEF to compose in an ISyntaxFactsService that
                // asserts it isn't asked to speculate on nodes inside documentation trivia.
                // This verifies that the provider is asking for a speculative SemanticModel
                // by walking to the node the documentation is attached to.

                var provider       = new CrefCompletionProvider();
                var hostDocument   = workspace.DocumentWithCursor;
                var document       = workspace.CurrentSolution.GetDocument(hostDocument.Id);
                var completionList = await GetCompletionListAsync(provider, document, hostDocument.CursorPosition.Value, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo());
            }
        }
コード例 #30
0
            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(TestWorkspace.CreateAsync(xmlString));
            }