public void EncapsulateFieldCommandDisabledInSubmission() { var exportProvider = MinimalTestExportProvider.CreateExportProvider( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveDocumentSupportsCodeFixService))); using (var workspace = TestWorkspaceFactory.CreateWorkspace(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$foo; } </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 EncapsulateFieldCommandHandler(workspace.GetService <Host.IWaitIndicator>(), workspace.GetService <ITextBufferUndoManagerProvider>()); var delegatedToNext = false; Func <CommandState> nextHandler = () => { delegatedToNext = true; return(CommandState.Unavailable); }; var state = handler.GetCommandState(new Commands.EncapsulateFieldCommandArgs(textView, textView.TextBuffer), nextHandler); Assert.True(delegatedToNext); Assert.False(state.IsAvailable); } }
protected void VerifyItemWithReferenceWorker(string xmlString, IEnumerable <SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(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 = document.GetTextAsync().Result.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(); } TestSignatureHelpWorkerShared(code, cursorPosition, SourceCodeKind.Regular, document, textSpan, expectedOrderedItems); } }
public void 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 = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var spans = GetErrorSpans(workspace); Assert.Equal(1, spans.Count()); Assert.Equal(PredefinedErrorTypeNames.SyntaxError, spans.First().Tag.ErrorType); } }
public async Task BuildErrorZeroLengthSpan() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath = ""Test.cs"" > class Test { } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var document = workspace.Documents.First(); var updateArgs = DiagnosticsUpdatedArgs.DiagnosticsCreated( new object(), 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).ConfigureAwait(true); Assert.Equal(1, spans.Count()); var first = spans.First(); Assert.Equal(1, first.Span.Span.Length); } }
public void LiveErrorZeroLengthSpan() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath = ""Test.cs"" > class Test { } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var document = workspace.Documents.First(); var updateArgs = new DiagnosticsUpdatedArgs( 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 = 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); } }
protected void Test( 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) ? TestWorkspaceFactory.CreateWorkspace(initialMarkup) : CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { ApplyOptionsToWorkspace(workspace, options); var actions = GetCodeActions(workspace, fixAllActionEquivalenceKey); TestActions( workspace, expected, index, actions, conflictSpans, renameSpans, warningSpans, compareTokens: compareTokens); } }
public void 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 = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var analyzerMap = ImmutableDictionary.CreateBuilder <string, ImmutableArray <DiagnosticAnalyzer> >(); analyzerMap.Add(LanguageNames.CSharp, ImmutableArray.Create <DiagnosticAnalyzer>( new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer())); var spans = GetErrorSpans(workspace, analyzerMap.ToImmutable()) .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); } }
private static TestWorkspace CreateTestWorkspace(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.CreateWorkspace(xml, exportProvider: exportProvider)); }
public AbstractCompletionCommandHandlerTestState(XElement workspaceElement) { _workspace = TestWorkspaceFactory.CreateWorkspace(workspaceElement); _view = _workspace.Documents.Single().GetTextView(); int caretPosition = _workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value; _view.Caret.MoveTo(new SnapshotPoint(_view.TextBuffer.CurrentSnapshot, caretPosition)); _editorOperations = _workspace.GetService <IEditorOperationsFactoryService>().GetEditorOperations(_view); }
/// <summary> /// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$), /// and use it to create a selected span in the TextView. /// /// For instance, the following will create a TextView that has a multiline selection with the cursor at the end. /// /// Sub Foo /// {|Selection:SomeMethodCall() /// AnotherMethodCall()$$|} /// End Sub /// </summary> public AbstractCommandHandlerTestState( XElement workspaceElement, ExportProvider exportProvider, string workspaceKind) { this.Workspace = TestWorkspaceFactory.CreateWorkspace( workspaceElement, exportProvider: exportProvider, workspaceKind: workspaceKind); var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue); _textView = cursorDocument.GetTextView(); _subjectBuffer = cursorDocument.GetTextBuffer(); IList <Text.TextSpan> selectionSpanList; if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out selectionSpanList)) { var span = selectionSpanList.First(); var cursorPosition = cursorDocument.CursorPosition.Value; Assert.True(cursorPosition == span.Start || cursorPosition == span.Start + span.Length, "cursorPosition wasn't at an endpoint of the 'Selection' annotated span"); _textView.Selection.Select( new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(span.Start, span.Length)), isReversed: cursorPosition == span.Start); if (selectionSpanList.Count > 1) { _textView.Selection.Mode = TextSelectionMode.Box; foreach (var additionalSpan in selectionSpanList.Skip(1)) { _textView.Selection.Select( new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(additionalSpan.Start, additionalSpan.Length)), isReversed: false); } } } else { _textView.Caret.MoveTo( new SnapshotPoint( _textView.TextBuffer.CurrentSnapshot, cursorDocument.CursorPosition.Value)); } this.EditorOperations = GetService <IEditorOperationsFactoryService>().GetEditorOperations(_textView); this.UndoHistoryRegistry = GetService <ITextUndoHistoryRegistry>(); }
public CallHierarchyTestState(XElement markup, params Type[] additionalTypes) { var exportProvider = CreateExportProvider(additionalTypes); this.Workspace = TestWorkspaceFactory.CreateWorkspace(markup, exportProvider: exportProvider); var testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue); _textView = testDocument.GetTextView(); _subjectBuffer = testDocument.GetTextBuffer(); var provider = Workspace.GetService <CallHierarchyProvider>(); _presenter = new MockCallHierarchyPresenter(); _commandHandler = new CallHierarchyCommandHandler(new[] { _presenter }, provider, TestWaitIndicator.Default); }
private void VerifyItemWithMscorlib45Worker(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(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()); } }
public void TestCodeActionPreviewAndApply() { using (var workspace = TestWorkspaceFactory.CreateWorkspace(WorkspaceXml)) { var codeIssueOrRefactoring = GetCodeRefactoring(workspace); var expectedCode = "private class D { }"; TestActionsOnLinkedFiles( workspace, expectedText: expectedCode, index: 0, actions: codeIssueOrRefactoring.Actions.ToList(), expectedPreviewContents: expectedCode); } }
public void NoNavigationToGeneratedFiles() { using (var workspace = TestWorkspaceFactory.CreateWorkspace(@" <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); } }
public CallHierarchyTestState(XElement markup, params Type[] additionalTypes) { var exportProvider = CreateExportProvider(additionalTypes); this.Workspace = TestWorkspaceFactory.CreateWorkspace(markup, exportProvider: exportProvider); var testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue); _textView = testDocument.GetTextView(); _subjectBuffer = testDocument.GetTextBuffer(); var provider = Workspace.GetService<CallHierarchyProvider>(); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; _presenter = new MockCallHierarchyPresenter(); _commandHandler = new CallHierarchyCommandHandler(new[] { _presenter }, provider, TestWaitIndicator.Default); }
public void ChangeSignatureCommandDisabledInSubmission() { var exportProvider = MinimalTestExportProvider.CreateExportProvider( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveDocumentSupportsFeatureService))); using (var workspace = TestWorkspaceFactory.CreateWorkspace(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { void M$$(int x) { } } </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 ChangeSignatureCommandHandler(); var delegatedToNext = false; Func <CommandState> nextHandler = () => { delegatedToNext = true; return(CommandState.Unavailable); }; var state = handler.GetCommandState(new Commands.RemoveParametersCommandArgs(textView, textView.TextBuffer), nextHandler); Assert.True(delegatedToNext); Assert.False(state.IsAvailable); delegatedToNext = false; state = handler.GetCommandState(new Commands.ReorderParametersCommandArgs(textView, textView.TextBuffer), nextHandler); Assert.True(delegatedToNext); Assert.False(state.IsAvailable); } }
private void VerifyItemWithReferenceWorker(string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(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 = GetCompletionList(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 = completionList.Items.Single(c => CompareItems(c.DisplayText, expectedItem)).GetDescriptionAsync().Result; 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)); } } } }
private static void VerifyAgainstWorkspaceDefinition(string expectedText, Solution newSolution) { 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()); } } } }
private static TestWorkspace CreateWorkspace(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.CreateWorkspace(xmlString)); }
protected void TestSignatureHelpWithMscorlib45( 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 = TestWorkspaceFactory.CreateWorkspace(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 = document.GetTextAsync().Result.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(); } TestSignatureHelpWorkerShared(code, cursorPosition, SourceCodeKind.Regular, document, textSpan, expectedOrderedItems); } }
public void TestWorkspaceTryApplyChangesDirectCall() { using (var workspace = TestWorkspaceFactory.CreateWorkspace(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 void VerifyItemInLinkedFiles(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(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); } } }
public ChangeSignatureTestState(XElement workspaceXml) : this(TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { }
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); } }
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)); }
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); } }