提交 17fde7a3 编写于 作者: J Jason Malinowski

Redo when we create text buffers in TestWorkspace

With TestWorkspace we were creating text buffers for all types of
documents up front, and by default opening all buffers in the workspace.
This was problematic because if we're creating text buffers we should
be ensuring the text buffer's options for using tabs and spaces matches
the Workspace options, but the workspace sometimes wasn't available
at those times. This is also unnecessarily expensive if you have test
projects that aren't doing anything with editor experiences at all.

Also, a complicated "create a separate document in the TestWorkspace for
the cursor" was removed in favor of more direct code that just creates
a buffer. Creating an entire TestDocument was funky since the document
was never actually part of the workspace -- this revealed that it didn't
seem we were ever disposing the views created.

The "languageName" parameter to CreateProjectionBuffer was removed: it
didn't logically make sense (the projection buffer created isn't in
a Workspace, so it has no language name), but also wasn't being used
for anything else.
上级 2ac6ac0c
......@@ -85,12 +85,12 @@ private async Task ActionSets(TestWorkspace workspace, CodeRefactoringProvider p
out VisualStudio.Text.ITextBuffer textBuffer)
{
var document = GetDocument(workspace);
textBuffer = workspace.GetTestDocument(document.Id).GetTextBuffer();
var span = document.GetSyntaxRootAsync().Result.Span;
var context = new CodeRefactoringContext(document, span, (a) => codeActions.Add(a), CancellationToken.None);
provider.ComputeRefactoringsAsync(context).Wait();
var action = codeActions.Single();
extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager;
textBuffer = document.GetTextAsync().Result.Container.GetTextBuffer();
}
}
}
......@@ -2848,7 +2848,7 @@ public void Test(object session)
var subjectDocument = workspace.Documents.Single();
var projectedDocument =
workspace.CreateProjectionBufferDocument(HtmlMarkup, workspace.Documents, LanguageNames.CSharp);
workspace.CreateProjectionBufferDocument(HtmlMarkup, workspace.Documents);
if (workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>() is TestFormattingRuleFactoryServiceFactory.Factory provider)
{
......
......@@ -185,6 +185,7 @@ private static async Task TestAsync(string codeWithMarker, bool remote)
var worker = (TodoCommentIncrementalAnalyzer)provider.CreateIncrementalAnalyzer(workspace);
var document = workspace.Documents.First();
var initialTextSnapshot = document.GetTextBuffer().CurrentSnapshot;
var documentId = document.Id;
var reasons = new InvocationReasons(PredefinedInvocationReasons.DocumentAdded);
await worker.AnalyzeSyntaxAsync(workspace.CurrentSolution.GetDocument(documentId), InvocationReasons.Empty, CancellationToken.None);
......@@ -199,8 +200,8 @@ private static async Task TestAsync(string codeWithMarker, bool remote)
var todo = todoLists[i];
var span = expectedLists[i];
var line = document.InitialTextSnapshot.GetLineFromPosition(span.Start);
var text = document.InitialTextSnapshot.GetText(span.ToSpan());
var line = initialTextSnapshot.GetLineFromPosition(span.Start);
var text = initialTextSnapshot.GetText(span.ToSpan());
Assert.Equal(todo.MappedLine, line.LineNumber);
Assert.Equal(todo.MappedColumn, span.Start - line.Start);
......
......@@ -178,7 +178,7 @@ class D { }
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OpenDocument(document.Id);
await VerifyRootTypeNameAsync(workspace, "D");
......@@ -338,7 +338,7 @@ public void TestRemoveProjectWithOpenedDocuments()
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OpenDocument(document.Id);
workspace.OnProjectRemoved(project1.Id);
Assert.False(workspace.IsDocumentOpen(document.Id));
......@@ -355,7 +355,7 @@ public void TestRemoveProjectWithClosedDocuments()
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OpenDocument(document.Id);
workspace.CloseDocument(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
......@@ -370,7 +370,7 @@ public void TestRemoveOpenedDocument()
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OpenDocument(document.Id);
workspace.OnDocumentRemoved(document.Id);
......@@ -472,7 +472,7 @@ public async Task TestGetCompilationOnCrossLanguageDependentProjectChanged()
Assert.NotEqual(TypeKind.Error, classC.TypeKind);
// change the class name in document1
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OpenDocument(document1.Id);
var buffer1 = document1.GetTextBuffer();
// change C to X
......@@ -516,8 +516,8 @@ public async Task TestDependentSemanticVersionChangesWhenNotOriginallyAccessed()
Assert.NotEqual(TypeKind.Error, classCy.TypeKind);
// open both documents so background compiler works on their compilations
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer());
workspace.OpenDocument(document1.Id);
workspace.OpenDocument(document2.Id);
// change C to X
var buffer1 = document1.GetTextBuffer();
......@@ -570,8 +570,8 @@ public async Task TestGetCompilationOnCrossLanguageDependentProjectChangedInProg
Assert.NotEqual(TypeKind.Error, classCy.TypeKind);
// open both documents so background compiler works on their compilations
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer());
workspace.OpenDocument(document1.Id);
workspace.OpenDocument(document2.Id);
// change C to X
var buffer1 = document1.GetTextBuffer();
......@@ -618,7 +618,7 @@ public async Task TestOpenAndChangeDocument()
workspace.AddTestProject(project1);
var buffer = document.GetTextBuffer();
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OpenDocument(document.Id);
buffer.Insert(0, "class C {}");
......@@ -644,7 +644,7 @@ public async Task TestApplyChangesWithDocumentTextUpdated()
workspace.AddTestProject(project1);
var buffer = document.GetTextBuffer();
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OpenDocument(document.Id);
// prove the document has the correct text
Assert.Equal(startText, (await workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync()).ToString());
......@@ -1132,7 +1132,7 @@ public async Task TestLinkedFilesStayInSync()
</Project>
</Workspace>";
using var workspace = TestWorkspace.Create(input, exportProvider: TestExportProvider.ExportProviderWithCSharpAndVisualBasic);
using var workspace = TestWorkspace.Create(input, exportProvider: TestExportProvider.ExportProviderWithCSharpAndVisualBasic, openDocuments: true);
var eventArgs = new List<WorkspaceChangeEventArgs>();
workspace.WorkspaceChanged += (s, e) =>
......
......@@ -34,7 +34,7 @@ public async Task TestGetFirstDiagnosticWithFixAsync()
var code = @"
a
";
using var workspace = TestWorkspace.CreateCSharp(code);
using var workspace = TestWorkspace.CreateCSharp(code, openDocuments: true);
var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetService<IErrorLoggerService>()));
var fixService = new CodeFixService(
......@@ -140,7 +140,7 @@ private async Task GetFirstDiagnosticWithFixAsync(CodeFixProvider codefix)
() => codefix,
new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp)));
var code = @"class Program { }";
var workspace = TestWorkspace.CreateCSharp(code);
var workspace = TestWorkspace.CreateCSharp(code, openDocuments: true);
var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => new TestErrorLogger()));
var errorLogger = logger.First().Value;
var fixService = new CodeFixService(
......
......@@ -104,7 +104,7 @@ private sealed class Validator
var exportProvider = exportProviderFactory.CreateExportProvider();
Workspace = TestWorkspace.CreateCSharp(ActiveStatementsDescription.ClearTags(markedSource), exportProvider: exportProvider);
Workspace = TestWorkspace.CreateCSharp(ActiveStatementsDescription.ClearTags(markedSource), exportProvider: exportProvider, openDocuments: true);
if (adjustSolution != null)
{
......
......@@ -30,8 +30,8 @@ public async Task RegisterService()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawler);
var registrationService = new SolutionCrawlerRegistrationService(
SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(),
AsynchronousOperationListenerProvider.NullProvider);
SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(),
AsynchronousOperationListenerProvider.NullProvider);
// register and unregister workspace to the service
registrationService.Register(workspace);
......@@ -962,6 +962,8 @@ private async Task InsertText(string code, string text, bool expectDocumentAnaly
using var workspace = TestWorkspace.Create(
SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: code, exportProvider: EditorServicesUtil.ExportProvider);
SetOptions(workspace);
var testDocument = workspace.Documents.First();
var textBuffer = testDocument.GetTextBuffer();
var analyzer = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
......@@ -969,10 +971,7 @@ private async Task InsertText(string code, string text, bool expectDocumentAnaly
service.Register(workspace);
var testDocument = workspace.Documents.First();
var insertPosition = testDocument.CursorPosition;
var textBuffer = testDocument.GetTextBuffer();
using (var edit = textBuffer.CreateEdit())
{
......
......@@ -52,7 +52,7 @@ public void EmptyTextChanges()
var document = workspace.CurrentSolution.GetDocument(workspace.GetDocumentId(hostDocument));
var buffer = hostDocument.GetTextBuffer();
var startPosition = buffer.CurrentSnapshot.GetLineFromLineNumber(0).Start.Position;
var startingSnapshotVersion = buffer.CurrentSnapshot.Version;
var text = buffer.CurrentSnapshot.AsText();
var container = buffer.AsTextContainer();
Assert.Same(text.Container, container);
......@@ -64,8 +64,8 @@ public void EmptyTextChanges()
edit.Apply();
}
Assert.True(buffer.CurrentSnapshot.Version.VersionNumber == 2);
Assert.True(buffer.CurrentSnapshot.Version.ReiteratedVersionNumber == 1);
Assert.Equal(startingSnapshotVersion.VersionNumber + 1, buffer.CurrentSnapshot.Version.VersionNumber);
Assert.Equal(startingSnapshotVersion.VersionNumber, buffer.CurrentSnapshot.Version.ReiteratedVersionNumber);
var newText = buffer.CurrentSnapshot.AsText();
......
......@@ -51,13 +51,13 @@ class C
<Document>
{|S1: &lt;html&gt;@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:&lt;/html&gt;|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
......@@ -88,13 +88,13 @@ class C
<Document>
{|S1: &lt;html&gt;@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:&lt;/html&gt;|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
......@@ -123,13 +123,13 @@ class C
<Document>
{|S1: &lt;html&gt;@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:&lt;/html&gt;|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
......
......@@ -1204,13 +1204,13 @@ End Module|} </Document>)
{|S1:|}
{|S2: some text that's mapped to the surface buffer |}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.VisualBasic, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.VisualBasic, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
' Test a view that has a subject buffer with multiple projection buffers in between
Dim view = topProjectionBuffer.GetTextView()
......
......@@ -57,13 +57,13 @@ End Class
<Document>
{|S1: &lt;html&gt;@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.VisualBasic, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:&lt;/html&gt;|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.VisualBasic, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
......@@ -92,13 +92,13 @@ End Class
<Document>
{|S1: &lt;html&gt;@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:&lt;/html&gt;|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
......
......@@ -19,8 +19,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting
Protected Async Function VerifyHighlightsAsync(test As XElement, Optional optionIsEnabled As Boolean = True) As Tasks.Task
Using workspace = TestWorkspace.Create(test)
Dim testDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue)
Dim buffer = testDocument.TextBuffer
Dim snapshot = testDocument.InitialTextSnapshot
Dim snapshot = testDocument.GetTextBuffer().CurrentSnapshot
Dim caretPosition = testDocument.CursorPosition.Value
Dim document As Document = workspace.CurrentSolution.Projects.First.Documents.First
......
......@@ -52,7 +52,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar
</Workspace>, exportProvider:=TestExportProvider.ExportProviderWithCSharpAndVisualBasic)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument("LEADING TEXT {|Document:|} TRAILING TEXT", {subjectDocument}, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument("LEADING TEXT {|Document:|} TRAILING TEXT", {subjectDocument})
Dim view = projectedDocument.GetTextView()
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, projectedDocument.CursorPosition.Value))
......
......@@ -35,7 +35,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting
Dim hostDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue)
Dim caretPosition = hostDocument.CursorPosition.Value
Dim snapshot = hostDocument.InitialTextSnapshot
Dim snapshot = hostDocument.GetTextBuffer().CurrentSnapshot
workspace.Options = workspace.Options.WithChangedOption(FeatureOnOffOptions.ReferenceHighlighting, hostDocument.Project.Language, optionIsEnabled)
......
......@@ -636,13 +636,14 @@ End Class
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim initialTextSnapshot = textBuffer.CurrentSnapshot
textBuffer.Insert(caretPosition, "Bar")
session.Cancel()
' Assert the file is what it started as
Assert.Equal(workspace.Documents.Single().InitialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText())
Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText())
' Assert the file name didn't change
VerifyFileName(workspace, "Test1.cs")
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
......@@ -17,6 +19,7 @@
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.EditorUtilities;
using Roslyn.Test.Utilities;
using Xunit;
......@@ -28,14 +31,14 @@ internal abstract class AbstractCommandHandlerTestState : IDisposable
public readonly IEditorOperations EditorOperations;
public readonly ITextUndoHistoryRegistry UndoHistoryRegistry;
private readonly ITextView _textView;
private readonly DisposableTextView? _createdTextView;
private readonly ITextBuffer _subjectBuffer;
public AbstractCommandHandlerTestState(
XElement workspaceElement,
IList<Type> excludedTypes = null,
ComposableCatalog extraParts = null,
string workspaceKind = null)
: this(workspaceElement, GetExportProvider(excludedTypes, extraParts), workspaceKind)
ComposableCatalog extraParts,
string? workspaceKind = null)
: this(workspaceElement, GetExportProvider(excludedTypes: null, extraParts), workspaceKind)
{
}
......@@ -62,8 +65,8 @@ internal abstract class AbstractCommandHandlerTestState : IDisposable
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ExportProvider exportProvider,
string workspaceKind,
XElement cursorDocumentElement = null,
string? workspaceKind,
bool makeSeparateBufferForCursor = false,
ImmutableArray<string> roles = default)
{
this.Workspace = TestWorkspace.CreateWorkspace(
......@@ -71,62 +74,56 @@ internal abstract class AbstractCommandHandlerTestState : IDisposable
exportProvider: exportProvider,
workspaceKind: workspaceKind);
TestHostDocument cursorDocument;
if (cursorDocumentElement == null)
{
cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue);
}
else
if (makeSeparateBufferForCursor)
{
var languageName = Workspace.Projects.First().Language;
cursorDocument = TestWorkspace.CreateDocument(cursorDocumentElement, exportProvider, Workspace.Services.GetLanguageServices(languageName), roles);
var contentType = Workspace.Services.GetLanguageServices(languageName).GetRequiredService<IContentTypeLanguageService>().GetDefaultContentType();
_createdTextView = EditorFactory.CreateView(exportProvider, contentType, roles);
_textView = _createdTextView.TextView;
_subjectBuffer = _textView.TextBuffer;
}
_textView = cursorDocument.GetTextView();
_subjectBuffer = cursorDocument.GetTextBuffer();
if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out var selectionSpanList))
else
{
var firstSpan = selectionSpanList.First();
var lastSpan = selectionSpanList.Last();
var cursorPosition = cursorDocument.CursorPosition.Value;
Assert.True(cursorPosition == firstSpan.Start || cursorPosition == firstSpan.End
|| cursorPosition == lastSpan.Start || cursorPosition == lastSpan.End,
"cursorPosition wasn't at an endpoint of the 'Selection' annotated span");
var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue);
_textView = cursorDocument.GetTextView();
_subjectBuffer = cursorDocument.GetTextBuffer();
_textView.Selection.Mode = selectionSpanList.Length > 1
? TextSelectionMode.Box
: TextSelectionMode.Stream;
SnapshotPoint boxSelectionStart, boxSelectionEnd;
bool isReversed;
if (cursorPosition == firstSpan.Start || cursorPosition == lastSpan.End)
{
// Top-left and bottom-right corners used as anchor points.
boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.Start);
boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.End);
isReversed = cursorPosition == firstSpan.Start;
}
else
if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out var selectionSpanList))
{
// Top-right and bottom-left corners used as anchor points.
boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.End);
boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.Start);
isReversed = cursorPosition == firstSpan.End;
var firstSpan = selectionSpanList.First();
var lastSpan = selectionSpanList.Last();
var cursorPosition = cursorDocument.CursorPosition!.Value;
Assert.True(cursorPosition == firstSpan.Start || cursorPosition == firstSpan.End
|| cursorPosition == lastSpan.Start || cursorPosition == lastSpan.End,
"cursorPosition wasn't at an endpoint of the 'Selection' annotated span");
_textView.Selection.Mode = selectionSpanList.Length > 1
? TextSelectionMode.Box
: TextSelectionMode.Stream;
SnapshotPoint boxSelectionStart, boxSelectionEnd;
bool isReversed;
if (cursorPosition == firstSpan.Start || cursorPosition == lastSpan.End)
{
// Top-left and bottom-right corners used as anchor points.
boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.Start);
boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.End);
isReversed = cursorPosition == firstSpan.Start;
}
else
{
// Top-right and bottom-left corners used as anchor points.
boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.End);
boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.Start);
isReversed = cursorPosition == firstSpan.End;
}
_textView.Selection.Select(
new SnapshotSpan(boxSelectionStart, boxSelectionEnd),
isReversed: isReversed);
}
_textView.Selection.Select(
new SnapshotSpan(boxSelectionStart, boxSelectionEnd),
isReversed: isReversed);
}
else
{
_textView.Caret.MoveTo(
new SnapshotPoint(
_textView.TextBuffer.CurrentSnapshot,
cursorDocument.CursorPosition.Value));
}
this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView);
......@@ -135,6 +132,7 @@ internal abstract class AbstractCommandHandlerTestState : IDisposable
public void Dispose()
{
_createdTextView?.Dispose();
Workspace.Dispose();
}
......@@ -143,7 +141,7 @@ public T GetService<T>()
return Workspace.GetService<T>();
}
internal static ExportProvider GetExportProvider(IList<Type> excludedTypes, ComposableCatalog extraParts)
internal static ExportProvider GetExportProvider(IList<Type>? excludedTypes, ComposableCatalog extraParts)
{
excludedTypes = excludedTypes ?? Type.EmptyTypes;
......
......@@ -54,7 +54,7 @@ protected void ToggleCommentWithProjectionBuffer(string surfaceBufferMarkup, str
{
using (var workspace = GetWorkspace(subjectBufferMarkup, GetExportProvider()))
{
var document = workspace.CreateProjectionBufferDocument(surfaceBufferMarkup, workspace.Documents, LanguageNames.CSharp);
var document = workspace.CreateProjectionBufferDocument(surfaceBufferMarkup, workspace.Documents);
SetupSelection(document.GetTextView(), document.SelectedSpans.Select(s => Span.FromBounds(s.Start, s.End)));
var commandHandler = GetToggleCommentCommandHandler(workspace);
......
......@@ -124,6 +124,16 @@ private Action CreateInsertTextHandler(ITextView textView, string text)
{
var testDocument = workspace.Documents.Single();
var options = workspace.Options;
options = options.WithChangedOption(FormattingOptions.UseTabs, testDocument.Project.Language, useTabs);
options = options.WithChangedOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, testDocument.Project.Language, autoGenerateXmlDocComments);
options = options.WithChangedOption(FormattingOptions.NewLine, testDocument.Project.Language, newLine);
workspace.Options = options;
setOptionsOpt?.Invoke(workspace);
Assert.True(testDocument.CursorPosition.HasValue, "No caret position set!");
var startCaretPosition = testDocument.CursorPosition.Value;
......@@ -142,16 +152,6 @@ private Action CreateInsertTextHandler(ITextView textView, string text)
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
var options = workspace.Options;
options = options.WithChangedOption(FormattingOptions.UseTabs, testDocument.Project.Language, useTabs);
options = options.WithChangedOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, testDocument.Project.Language, autoGenerateXmlDocComments);
options = options.WithChangedOption(FormattingOptions.NewLine, testDocument.Project.Language, newLine);
workspace.Options = options;
setOptionsOpt?.Invoke(workspace);
execute(
view,
workspace.GetService<ITextUndoHistoryRegistry>(),
......
......@@ -2,6 +2,7 @@
#nullable enable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
......@@ -50,6 +51,17 @@ public static class EditorFactory
return exportProvider.GetExportedValue<ITextEditorFactoryService>().CreateDisposableTextView(buffer);
}
public static DisposableTextView CreateView(
ExportProvider exportProvider,
IContentType contentType,
ImmutableArray<string> roles)
{
WpfTestRunner.RequireWpfFact($"Creates an {nameof(IWpfTextView)} through {nameof(EditorFactory)}.{nameof(CreateView)}");
var buffer = CreateBuffer(exportProvider, contentType);
return exportProvider.GetExportedValue<ITextEditorFactoryService>().CreateDisposableTextView(buffer, roles);
}
public static string LinesToFullText(params string[] lines)
{
return string.Join("\r\n", lines);
......
......@@ -3,6 +3,7 @@
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
......@@ -13,19 +14,23 @@ public static DisposableTextView CreateDisposableTextView(this ITextEditorFactor
return new DisposableTextView(textEditorFactory.CreateTextView());
}
public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory, ITextBuffer buffer)
public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory, ITextBuffer buffer, ImmutableArray<string> roles = default)
{
// Every default role but outlining. Starting in 15.2, the editor
// OutliningManager imports JoinableTaskContext in a way that's
// difficult to satisfy in our unit tests. Since we don't directly
// depend on it, just disable it
var roles = textEditorFactory.CreateTextViewRoleSet(PredefinedTextViewRoles.Analyzable,
PredefinedTextViewRoles.Document,
PredefinedTextViewRoles.Editable,
PredefinedTextViewRoles.Interactive,
PredefinedTextViewRoles.Zoomable);
if (roles.IsDefault)
{
roles = ImmutableArray.Create(PredefinedTextViewRoles.Analyzable,
PredefinedTextViewRoles.Document,
PredefinedTextViewRoles.Editable,
PredefinedTextViewRoles.Interactive,
PredefinedTextViewRoles.Zoomable);
}
return new DisposableTextView(textEditorFactory.CreateTextView(buffer, roles));
var roleSet = textEditorFactory.CreateTextViewRoleSet(roles);
return new DisposableTextView(textEditorFactory.CreateTextView(buffer, roleSet));
}
}
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.EditorUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
......@@ -26,26 +30,31 @@ public class TestHostDocument
PredefinedTextViewRoles.Zoomable);
private readonly ExportProvider _exportProvider;
private HostLanguageServices _languageServiceProvider;
private readonly Lazy<string> _initialText;
private IWpfTextView _textView;
private DocumentId _id;
private TestHostProject _project;
public ITextBuffer TextBuffer;
public ITextSnapshot InitialTextSnapshot;
private readonly string _name;
private readonly SourceCodeKind _sourceCodeKind;
private readonly string _filePath;
private readonly IReadOnlyList<string> _folders;
private readonly IDocumentServiceProvider _documentServiceProvider;
private HostLanguageServices? _languageServiceProvider;
private readonly string _initialText;
private IWpfTextView? _textView;
private DocumentId? _id;
private TestHostProject? _project;
/// <summary>
/// The <see cref="ITextBuffer"/> for this document. Null if not yet created.
/// </summary>
private ITextBuffer? _textBuffer;
/// <summary>
/// The <see cref="ITextSnapshot"/> when the buffer was first created, which can be used for tracking changes to the current buffer.
/// </summary>
private ITextSnapshot? _initialTextSnapshot;
private readonly IReadOnlyList<string>? _folders;
private readonly IDocumentServiceProvider? _documentServiceProvider;
private readonly ImmutableArray<string> _roles;
public DocumentId Id
{
get
{
Contract.ThrowIfNull(_id);
return _id;
}
}
......@@ -54,33 +63,14 @@ public TestHostProject Project
{
get
{
Contract.ThrowIfNull(_project);
return _project;
}
}
public string Name
{
get
{
return _name;
}
}
public SourceCodeKind SourceCodeKind
{
get
{
return _sourceCodeKind;
}
}
public string FilePath
{
get
{
return _filePath;
}
}
public string Name { get; }
public SourceCodeKind SourceCodeKind { get; }
public string? FilePath { get; }
public bool IsGenerated
{
......@@ -92,8 +82,8 @@ public bool IsGenerated
public TextLoader Loader { get; }
public int? CursorPosition { get; }
public IList<TextSpan> SelectedSpans { get; }
public IDictionary<string, ImmutableArray<TextSpan>> AnnotatedSpans { get; }
public IList<TextSpan> SelectedSpans { get; } = new List<TextSpan>();
public IDictionary<string, ImmutableArray<TextSpan>> AnnotatedSpans { get; } = new Dictionary<string, ImmutableArray<TextSpan>>();
/// <summary>
/// If a file exists in ProjectA and is added to ProjectB as a link, then this returns
......@@ -103,62 +93,64 @@ public bool IsGenerated
internal TestHostDocument(
ExportProvider exportProvider,
HostLanguageServices languageServiceProvider,
ITextBuffer textBuffer,
HostLanguageServices? languageServiceProvider,
string code,
string filePath,
int? cursorPosition,
IDictionary<string, ImmutableArray<TextSpan>> spans,
SourceCodeKind sourceCodeKind = SourceCodeKind.Regular,
IReadOnlyList<string> folders = null,
IReadOnlyList<string>? folders = null,
bool isLinkFile = false,
IDocumentServiceProvider documentServiceProvider = null,
ImmutableArray<string> roles = default)
IDocumentServiceProvider? documentServiceProvider = null,
ImmutableArray<string> roles = default,
ITextBuffer? textBuffer = null)
{
Contract.ThrowIfNull(textBuffer);
Contract.ThrowIfNull(filePath);
_exportProvider = exportProvider;
_languageServiceProvider = languageServiceProvider;
this.TextBuffer = textBuffer;
this.InitialTextSnapshot = textBuffer.CurrentSnapshot;
_initialText = new Lazy<string>(() => this.InitialTextSnapshot.GetText());
_filePath = filePath;
_initialText = code;
FilePath = filePath;
_folders = folders;
_name = filePath;
Name = filePath;
this.CursorPosition = cursorPosition;
_sourceCodeKind = sourceCodeKind;
SourceCodeKind = sourceCodeKind;
this.IsLinkFile = isLinkFile;
_documentServiceProvider = documentServiceProvider;
_roles = roles.IsDefault ? s_defaultRoles : roles;
this.SelectedSpans = new List<TextSpan>();
if (spans.ContainsKey(string.Empty))
{
this.SelectedSpans = spans[string.Empty];
}
this.AnnotatedSpans = new Dictionary<string, ImmutableArray<TextSpan>>();
foreach (var namedSpanList in spans.Where(s => s.Key != string.Empty))
{
this.AnnotatedSpans.Add(namedSpanList);
}
Loader = new TestDocumentLoader(this);
Loader = new TestDocumentLoader(this, _initialText);
if (textBuffer != null)
{
_textBuffer = textBuffer;
_initialTextSnapshot = textBuffer.CurrentSnapshot;
}
}
public TestHostDocument(
string text = "", string displayName = "",
SourceCodeKind sourceCodeKind = SourceCodeKind.Regular,
DocumentId id = null, string filePath = null,
IReadOnlyList<string> folders = null)
DocumentId? id = null, string? filePath = null,
IReadOnlyList<string>? folders = null)
{
_exportProvider = TestExportProvider.ExportProviderWithCSharpAndVisualBasic;
_id = id;
_initialText = new Lazy<string>(() => text);
_name = displayName;
_sourceCodeKind = sourceCodeKind;
Loader = new TestDocumentLoader(this);
_filePath = filePath;
_initialText = text;
Name = displayName;
SourceCodeKind = sourceCodeKind;
Loader = new TestDocumentLoader(this, text);
FilePath = filePath;
_folders = folders;
_roles = s_defaultRoles;
}
......@@ -167,7 +159,7 @@ internal void SetProject(TestHostProject project)
{
_project = project;
if (this.Id == null)
if (_id == null)
{
_id = DocumentId.CreateNewId(project.Id, this.Name);
}
......@@ -180,31 +172,22 @@ internal void SetProject(TestHostProject project)
{
_languageServiceProvider = project.LanguageServiceProvider;
}
if (this.TextBuffer == null)
{
var contentTypeService = _languageServiceProvider.GetService<IContentTypeLanguageService>();
var contentType = contentTypeService.GetDefaultContentType();
this.TextBuffer = _exportProvider.GetExportedValue<ITextBufferFactoryService>().CreateTextBuffer(_initialText.Value, contentType);
this.InitialTextSnapshot = this.TextBuffer.CurrentSnapshot;
}
}
private class TestDocumentLoader : TextLoader
{
private readonly TestHostDocument _hostDocument;
private readonly string _text;
internal TestDocumentLoader(TestHostDocument hostDocument)
internal TestDocumentLoader(TestHostDocument hostDocument, string text)
{
_hostDocument = hostDocument;
_text = text;
}
public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
// Create a simple SourceText so that way we're not backing "closed" files by editors to best reflect
// what closed files look like in reality.
var text = SourceText.From(_hostDocument.GetTextBuffer().CurrentSnapshot.GetText());
return Task.FromResult(TextAndVersion.Create(text, VersionStamp.Create(), _hostDocument.FilePath));
return Task.FromResult(TextAndVersion.Create(SourceText.From(_text), VersionStamp.Create(), _hostDocument.FilePath));
}
}
......@@ -221,7 +204,7 @@ public IWpfTextView GetTextView()
// difficult to satisfy in our unit tests. Since we don't directly
// depend on it, just disable it
var roles = factory.CreateTextViewRoleSet(_roles);
_textView = factory.CreateTextView(this.TextBuffer, roles);
_textView = factory.CreateTextView(this.GetTextBuffer(), roles);
if (this.CursorPosition.HasValue)
{
_textView.Caret.MoveTo(new SnapshotPoint(_textView.TextSnapshot, CursorPosition.Value));
......@@ -238,9 +221,41 @@ public IWpfTextView GetTextView()
public ITextBuffer GetTextBuffer()
{
return this.TextBuffer;
var workspace = (TestWorkspace?)_languageServiceProvider?.WorkspaceServices.Workspace;
if (_textBuffer == null)
{
Contract.ThrowIfNull(_languageServiceProvider, $"To get a text buffer for a {nameof(TestHostDocument)}, it must have been parented in a project.");
var contentType = _languageServiceProvider.GetRequiredService<IContentTypeLanguageService>().GetDefaultContentType();
_textBuffer = workspace!.GetOrCreateBufferForPath(FilePath, contentType, _languageServiceProvider.Language, _initialText);
_initialTextSnapshot = _textBuffer.CurrentSnapshot;
}
if (workspace != null)
{
// Open (or reopen) any files that were closed in this call. We do this for all linked copies at once.
foreach (var linkedId in workspace.CurrentSolution.GetDocumentIdsWithFilePath(FilePath).Concat(this.Id))
{
var testDocument = workspace.GetTestDocument(linkedId);
if (testDocument != null)
{
if (!workspace.IsDocumentOpen(linkedId))
{
// If there is a linked file, we'll start the non-linked one as being the primary context, which some tests depend on.
workspace.OnDocumentOpened(linkedId, _textBuffer.AsTextContainer(), isCurrentContext: !testDocument.IsLinkFile);
}
};
}
}
return _textBuffer;
}
// TODO: delete this and move all callers to it
public ITextBuffer TextBuffer => GetTextBuffer();
public SourceTextContainer GetOpenTextContainer()
{
return this.GetTextBuffer().AsTextContainer();
......@@ -254,6 +269,16 @@ public IReadOnlyList<string> Folders
}
}
// TODO: delete this
public ITextSnapshot InitialTextSnapshot
{
get
{
Contract.ThrowIfNull(_initialTextSnapshot);
return _initialTextSnapshot;
}
}
internal void Update(SourceText newText)
{
var buffer = GetTextBuffer();
......
......@@ -7,8 +7,6 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Test.EditorUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
......@@ -40,12 +44,14 @@ public partial class TestWorkspace : Workspace
private readonly BackgroundParser _backgroundParser;
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService;
private readonly Dictionary<string, ITextBuffer> _createdTextBuffers = new Dictionary<string, ITextBuffer>();
public TestWorkspace()
: this(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, WorkspaceKind.Test)
{
}
public TestWorkspace(ExportProvider exportProvider, string workspaceKind = null, bool disablePartialSolutions = true)
public TestWorkspace(ExportProvider exportProvider, string? workspaceKind = null, bool disablePartialSolutions = true)
: base(VisualStudioMefHostServices.Create(exportProvider), workspaceKind ?? WorkspaceKind.Test)
{
this.TestHookPartialSolutionsDisabled = disablePartialSolutions;
......@@ -133,17 +139,6 @@ protected override void Dispose(bool finalize)
base.Dispose(finalize);
}
private static IList<Exception> Flatten(ICollection<Exception> exceptions)
{
var aggregate = new AggregateException(exceptions);
return aggregate.Flatten().InnerExceptions
.Select(UnwrapException)
.ToList();
}
private static Exception UnwrapException(Exception ex)
=> ex is TargetInvocationException targetEx ? (targetEx.InnerException ?? targetEx) : ex;
internal void AddTestSolution(TestHostSolution solution)
{
this.OnSolutionAdded(SolutionInfo.Create(solution.Id, solution.Version, solution.FilePath, projects: solution.Projects.Select(p => p.ToProjectInfo())));
......@@ -214,7 +209,7 @@ public new void OnDocumentSourceCodeKindChanged(DocumentId documentId, SourceCod
base.OnDocumentSourceCodeKindChanged(documentId, sourceCodeKind);
}
public DocumentId GetDocumentId(TestHostDocument hostDocument)
public DocumentId? GetDocumentId(TestHostDocument hostDocument)
{
if (!Documents.Contains(hostDocument) &&
!AdditionalDocuments.Contains(hostDocument) &&
......@@ -410,10 +405,9 @@ internal override void SetDocumentContext(DocumentId documentId)
public TestHostDocument CreateProjectionBufferDocument(
string markup,
IList<TestHostDocument> baseDocuments,
string languageName,
string path = "projectionbufferdocumentpath",
ProjectionBufferOptions options = ProjectionBufferOptions.None,
IProjectionEditResolver editResolver = null)
IProjectionEditResolver? editResolver = null)
{
GetSpansAndCaretFromSurfaceBufferMarkup(markup, baseDocuments,
out var projectionBufferSpans, out var mappedSpans, out var mappedCaretLocation);
......@@ -429,7 +423,7 @@ internal override void SetDocumentContext(DocumentId documentId)
: ImmutableArray<TextSpan>.Empty;
foreach (var span in document.SelectedSpans)
{
var snapshotSpan = span.ToSnapshotSpan(document.TextBuffer.CurrentSnapshot);
var snapshotSpan = span.ToSnapshotSpan(document.GetTextBuffer().CurrentSnapshot);
var mappedSpan = projectionBuffer.CurrentSnapshot.MapFromSourceSnapshot(snapshotSpan).Single();
mappedSpans[string.Empty] = mappedSpans[string.Empty].Add(mappedSpan.ToTextSpan());
}
......@@ -446,7 +440,7 @@ internal override void SetDocumentContext(DocumentId documentId)
foreach (var span in kvp.Value)
{
var snapshotSpan = span.ToSnapshotSpan(document.TextBuffer.CurrentSnapshot);
var snapshotSpan = span.ToSnapshotSpan(document.GetTextBuffer().CurrentSnapshot);
var mappedSpan = projectionBuffer.CurrentSnapshot.MapFromSourceSnapshot(snapshotSpan).Cast<Span?>().SingleOrDefault();
if (mappedSpan == null)
{
......@@ -460,15 +454,14 @@ internal override void SetDocumentContext(DocumentId documentId)
}
}
var languageServices = this.Services.GetLanguageServices(languageName);
var projectionDocument = new TestHostDocument(
ExportProvider,
languageServices,
projectionBuffer,
languageServiceProvider: null,
projectionBuffer.CurrentSnapshot.GetText(),
path,
mappedCaretLocation,
mappedSpans);
mappedSpans,
textBuffer: projectionBuffer);
this.ProjectionDocuments.Add(projectionDocument);
return projectionDocument;
......@@ -533,7 +526,7 @@ internal override void SetDocumentContext(DocumentId documentId)
var matchingSpan = documentWithSpan.AnnotatedSpans[spanName].Single();
var span = new Span(matchingSpan.Start, matchingSpan.Length);
var trackingSpan = documentWithSpan.TextBuffer.CurrentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive);
var trackingSpan = documentWithSpan.GetTextBuffer().CurrentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive);
projectionBufferSpans.Add(trackingSpan);
projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer);
......@@ -576,11 +569,11 @@ internal override void SetDocumentContext(DocumentId documentId)
out Dictionary<string, ImmutableArray<TextSpan>> mappedMarkupSpans,
IList<object> projectionBufferSpans, IList<int> projectionBufferSpanStartingPositions)
{
var tempMappedMarkupSpans = new Dictionary<string, ArrayBuilder<TextSpan>>();
var tempMappedMarkupSpans = new Dictionary<string, PooledObjects.ArrayBuilder<TextSpan>>();
foreach (var key in markupSpans.Keys)
{
tempMappedMarkupSpans[key] = ArrayBuilder<TextSpan>.GetInstance();
tempMappedMarkupSpans[key] = PooledObjects.ArrayBuilder<TextSpan>.GetInstance();
foreach (var markupSpan in markupSpans[key])
{
var positionInMarkup = 0;
......@@ -616,7 +609,7 @@ internal override void SetDocumentContext(DocumentId documentId)
spanIndex++;
}
tempMappedMarkupSpans[key].Add(new TextSpan(spanStartLocation.Value, spanEndLocationExclusive.Value - spanStartLocation.Value));
tempMappedMarkupSpans[key].Add(new TextSpan(spanStartLocation!.Value, spanEndLocationExclusive!.Value - spanStartLocation.Value));
}
}
......@@ -626,8 +619,8 @@ internal override void SetDocumentContext(DocumentId documentId)
public override void OpenDocument(DocumentId documentId, bool activate = true)
{
var testDocument = this.GetTestDocument(documentId);
OnDocumentOpened(documentId, testDocument.GetOpenTextContainer());
// Fetching the open SourceTextContanier implicitly opens the document.
GetTestDocument(documentId).GetOpenTextContainer();
}
public override void CloseDocument(DocumentId documentId)
......@@ -683,5 +676,30 @@ public void ChangeSolution(Solution solution)
public override bool CanApplyParseOptionChange(ParseOptions oldOptions, ParseOptions newOptions, Project project)
=> true;
internal ITextBuffer GetOrCreateBufferForPath(string? filePath, IContentType contentType, string languageName, string initialText)
{
// If we don't have a file path we'll just make something up for the purpose of this dictionary so all
// buffers are still held onto. This isn't a file name used in the workspace itself so it's unobservable.
if (RoslynString.IsNullOrEmpty(filePath))
{
filePath = Guid.NewGuid().ToString();
}
return _createdTextBuffers.GetOrAdd(filePath, _ =>
{
var textBuffer = EditorFactory.CreateBuffer(ExportProvider, contentType, initialText);
// Ensure that the editor options on the text buffer matches that of the options that can be directly set in the workspace
var editorOptions = ExportProvider.GetExportedValue<IEditorOptionsFactoryService>().GetOptions(textBuffer);
var workspaceOptions = this.Options;
editorOptions.SetOptionValue(DefaultOptions.ConvertTabsToSpacesOptionId, !workspaceOptions.GetOption(FormattingOptions.UseTabs, languageName));
editorOptions.SetOptionValue(DefaultOptions.TabSizeOptionId, workspaceOptions.GetOption(FormattingOptions.TabSize, languageName));
editorOptions.SetOptionValue(DefaultOptions.IndentSizeOptionId, workspaceOptions.GetOption(FormattingOptions.IndentationSize, languageName));
return textBuffer;
});
}
}
}
......@@ -8,6 +8,8 @@
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
......@@ -142,7 +144,7 @@ internal static string GetDefaultTestSourceDocumentName(int index, string extens
string workspaceKind = null,
string extension = null,
bool commonReferences = true,
bool openDocuments = true)
bool openDocuments = false)
{
var documentElements = new List<XElement>();
var index = 0;
......@@ -220,7 +222,7 @@ internal static string GetDefaultTestSourceDocumentName(int index, string extens
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null,
bool openDocuments = true)
bool openDocuments = false)
{
return CreateCSharp(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences, openDocuments);
}
......@@ -231,7 +233,7 @@ internal static string GetDefaultTestSourceDocumentName(int index, string extens
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null,
bool openDocuments = true)
bool openDocuments = false)
{
return Create(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider, metadataReferences, openDocuments: openDocuments);
}
......@@ -255,7 +257,7 @@ internal static string GetDefaultTestSourceDocumentName(int index, string extens
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null,
bool openDocuments = true)
bool openDocuments = false)
{
return CreateVisualBasic(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences, openDocuments);
}
......@@ -266,7 +268,7 @@ internal static string GetDefaultTestSourceDocumentName(int index, string extens
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null,
bool openDocuments = true)
bool openDocuments = false)
{
return Create(LanguageNames.VisualBasic, compilationOptions, parseOptions, files, exportProvider, metadataReferences, openDocuments: openDocuments);
}
......
......@@ -57,7 +57,7 @@ public override int GetHashCode()
}
}
public static TestWorkspace Create(string xmlDefinition, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null)
public static TestWorkspace Create(string xmlDefinition, bool completed = true, bool openDocuments = false, ExportProvider exportProvider = null)
{
return Create(XElement.Parse(xmlDefinition), completed, openDocuments, exportProvider);
}
......@@ -118,6 +118,8 @@ public static TestWorkspace Create(string xmlDefinition, bool completed = true,
foreach (var document in project.Documents)
{
Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath));
workspace.Documents.Add(document);
}
}
......@@ -126,6 +128,7 @@ public static TestWorkspace Create(string xmlDefinition, bool completed = true,
foreach (var submission in submissions)
{
projectNameToTestHostProject.Add(submission.Name, submission);
workspace.Documents.Add(submission.Documents.Single());
}
var solution = new TestHostSolution(projectNameToTestHostProject.Values.ToArray());
......@@ -170,10 +173,9 @@ public static TestWorkspace Create(string xmlDefinition, bool completed = true,
{
if (openDocuments)
{
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile);
// This implicitly opens the document in the workspace by fetching the container.
document.GetOpenTextContainer();
}
workspace.Documents.Add(document);
}
}
......@@ -200,14 +202,10 @@ public static TestWorkspace Create(string xmlDefinition, bool completed = true,
out var code, out var cursorPosition, out IDictionary<string, ImmutableArray<TextSpan>> spans);
var languageServices = workspace.Services.GetLanguageServices(languageName);
var contentTypeLanguageService = languageServices.GetService<IContentTypeLanguageService>();
var contentType = contentTypeLanguageService.GetDefaultContentType();
var textBuffer = EditorFactory.CreateBuffer(exportProvider, contentType, code);
// The project
var document = new TestHostDocument(exportProvider, languageServices, textBuffer, submissionName, cursorPosition, spans, SourceCodeKind.Script);
var document = new TestHostDocument(exportProvider, languageServices, code, submissionName, cursorPosition, spans, SourceCodeKind.Script);
var documents = new List<TestHostDocument> { document };
if (languageName == NoCompilationConstants.LanguageName)
......@@ -745,13 +743,6 @@ private static CompilationOptions CreateCompilationOptions(TestWorkspace workspa
MarkupTestFile.GetPositionAndSpans(markupCode,
out var code, out var cursorPosition, out IDictionary<string, ImmutableArray<TextSpan>> spans);
// For linked files, use the same ITextBuffer for all linked documents
if (!filePathToTextBufferMap.TryGetValue(filePath, out var textBuffer))
{
textBuffer = EditorFactory.CreateBuffer(exportProvider, contentType, code);
filePathToTextBufferMap.Add(filePath, textBuffer);
}
var testDocumentServiceProvider = GetDocumentServiceProvider(documentElement);
if (documentServiceProvider == null)
......@@ -764,7 +755,7 @@ private static CompilationOptions CreateCompilationOptions(TestWorkspace workspa
}
return new TestHostDocument(
exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile, documentServiceProvider);
exportProvider, languageServiceProvider, code, filePath, cursorPosition, spans, codeKind, folders, isLinkFile, documentServiceProvider);
}
internal static TestHostDocument CreateDocument(
......@@ -791,12 +782,9 @@ private static CompilationOptions CreateCompilationOptions(TestWorkspace workspa
out var code, out var cursorPosition, out IDictionary<string, ImmutableArray<TextSpan>> spans);
var documentServiceProvider = GetDocumentServiceProvider(documentElement);
var contentTypeLanguageService = languageServiceProvider.GetService<IContentTypeLanguageService>();
var contentType = contentTypeLanguageService.GetDefaultContentType();
var textBuffer = EditorFactory.CreateBuffer(exportProvider, contentType, code);
return new TestHostDocument(
exportProvider, languageServiceProvider, textBuffer, filePath: string.Empty, cursorPosition, spans, codeKind, folders, isLinkFile: false, documentServiceProvider, roles: roles);
exportProvider, languageServiceProvider, code, filePath: string.Empty, cursorPosition, spans, codeKind, folders, isLinkFile: false, documentServiceProvider, roles: roles);
}
#nullable enable
......
......@@ -75,9 +75,9 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
extraExportedTypes As List(Of Type),
includeFormatCommandHandler As Boolean,
workspaceKind As String,
Optional cursorDocumentElement As XElement = Nothing,
Optional makeSeparateBufferForCursor As Boolean = False,
Optional roles As ImmutableArray(Of String) = Nothing)
MyBase.New(workspaceElement, GetExportProvider(excludedTypes, extraExportedTypes, includeFormatCommandHandler), workspaceKind:=workspaceKind, cursorDocumentElement, roles)
MyBase.New(workspaceElement, GetExportProvider(excludedTypes, extraExportedTypes, includeFormatCommandHandler), workspaceKind:=workspaceKind, makeSeparateBufferForCursor, roles)
' The current default timeout defined in the Editor may not work on slow virtual test machines.
' Need to use a safe timeout there to follow real code paths.
......
......@@ -351,17 +351,17 @@ End Class</code>.Value
Dim document = workspace.Documents.Single()
Dim buffer = document.TextBuffer
Dim snapshot = buffer.CurrentSnapshot
Dim initialTextSnapshot = buffer.CurrentSnapshot
Dim caretPosition = snapshot.CreateTrackingPoint(document.CursorPosition.Value,
PointTrackingMode.Positive,
TrackingFidelityMode.Backward)
Dim caretPosition = initialTextSnapshot.CreateTrackingPoint(document.CursorPosition.Value,
PointTrackingMode.Positive,
TrackingFidelityMode.Backward)
Dim corrector = New AutomaticEndConstructCorrector(buffer, New TestWaitIndicator())
corrector.Connect()
If removeOriginalContent Then
Dim spanToRemove = document.SelectedSpans.Single(Function(s) s.Contains(caretPosition.GetPosition(snapshot)))
Dim spanToRemove = document.SelectedSpans.Single(Function(s) s.Contains(caretPosition.GetPosition(initialTextSnapshot)))
buffer.Replace(spanToRemove.ToSpan(), "")
End If
......@@ -371,14 +371,14 @@ End Class</code>.Value
Dim insertedString = type.Substring(0, i + 1)
For Each span In document.SelectedSpans.Skip(1)
Dim trackingSpan = New LetterOnlyTrackingSpan(span.ToSnapshotSpan(document.InitialTextSnapshot))
Dim trackingSpan = New LetterOnlyTrackingSpan(span.ToSnapshotSpan(initialTextSnapshot))
Assert.Equal(expectedStringGetter(insertedString), trackingSpan.GetText(document.TextBuffer.CurrentSnapshot))
Next
Next
If split IsNot Nothing Then
Dim beginSpan = document.SelectedSpans.First()
Dim trackingSpan = New LetterOnlyTrackingSpan(beginSpan.ToSnapshotSpan(document.InitialTextSnapshot))
Dim trackingSpan = New LetterOnlyTrackingSpan(beginSpan.ToSnapshotSpan(initialTextSnapshot))
buffer.Insert(trackingSpan.GetEndPoint(buffer.CurrentSnapshot).Position - type.Trim().Length, " ")
......
......@@ -2995,7 +2995,7 @@ end class"
expectedIndentation As Integer)
Using workspace = TestWorkspace.CreateVisualBasic(markup)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument(s_htmlMarkup, workspace.Documents, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument(s_htmlMarkup, workspace.Documents)
Dim factory = TryCast(workspace.Services.GetService(Of IHostDependentFormattingRuleFactoryService)(),
TestFormattingRuleFactoryServiceFactory.Factory)
......
......@@ -95,11 +95,13 @@ End Module
</Project>
</Workspace>)
Dim initialTextSnapshot = testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot
testData.EditorOperations.InsertText(" ")
testData.EditorOperations.MoveLineUp(extendSelection:=False)
' The text should snap back to what it originally was
Dim originalText = testData.Workspace.Documents.Single().InitialTextSnapshot.GetLineFromLineNumber(5).GetText()
Dim originalText = initialTextSnapshot.GetLineFromLineNumber(5).GetText()
Assert.Equal(originalText, testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(5).GetText())
End Using
End Sub
......@@ -326,6 +328,8 @@ End Module
</Project>
</Workspace>)
Dim initialTextSnapshot = testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot
testData.EditorOperations.Backspace()
testData.EditorOperations.Backspace()
testData.EditorOperations.Backspace()
......@@ -336,7 +340,7 @@ End Module
testData.EditorOperations.MoveLineUp(extendSelection:=False)
testData.AssertHadCommit(True)
Assert.Equal(testData.Workspace.Documents.Single().InitialTextSnapshot.GetText(), testData.Workspace.Documents.Single().TextBuffer.CurrentSnapshot.GetText())
Assert.Equal(initialTextSnapshot.GetText(), testData.Workspace.Documents.Single().TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
......
......@@ -188,6 +188,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.TodoComment
Dim worker = DirectCast(provider.CreateIncrementalAnalyzer(workspace), TodoCommentIncrementalAnalyzer)
Dim document = workspace.Documents.First()
Dim initialTextSnapshot = document.GetTextBuffer().CurrentSnapshot
Dim documentId = document.Id
Await worker.AnalyzeSyntaxAsync(workspace.CurrentSolution.GetDocument(documentId), InvocationReasons.Empty, CancellationToken.None)
......@@ -199,7 +200,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.TodoComment
Dim todo = todoLists(i)
Dim span = list(i)
Dim line = document.InitialTextSnapshot.GetLineFromPosition(span.Start)
Dim line = initialTextSnapshot.GetLineFromPosition(span.Start)
Assert.Equal(todo.MappedLine, line.LineNumber)
Assert.Equal(todo.MappedColumn, span.Start - line.Start.Position)
......
......@@ -23,7 +23,7 @@ internal sealed class EventHookupTestState : AbstractCommandHandlerTestState
private readonly Mutex _testSessionHookupMutex;
public EventHookupTestState(XElement workspaceElement, IDictionary<OptionKey, object> options)
: base(workspaceElement, excludedTypes: null, GetExtraParts())
: base(workspaceElement, GetExtraParts())
{
_commandHandler = new EventHookupCommandHandler(
Workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
......
......@@ -39,7 +39,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests
<span>@{|S2:|}</span>
{|S3:|}
<h2>Default</h2>
]]></text>.Value.Replace(vbLf, vbCrLf), {doc}, LanguageNames.CSharp)
]]></text>.Value.Replace(vbLf, vbCrLf), {doc})
Dim matchingSpan = projected.SelectedSpans.Single()
TestSpan(workspace, projected, projected.CursorPosition.Value, matchingSpan.End)
......
......@@ -639,7 +639,8 @@ $$</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True, <Document>123123123123123123123123123 + $$</Document>)
Using state = TestState.CreateCSharpTestState(text, True)
state.TextView.TextBuffer.Insert(0, "123123123123123123123123123 + ")
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("123123123123123123123123123 + arg", state.GetCurrentViewLineText())
......
......@@ -22,8 +22,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
Private Shared ReadOnly s_roles As ImmutableArray(Of String) = ImmutableArray.Create(PredefinedTextViewRoles.Editable, "DEBUGVIEW", PredefinedTextViewRoles.Interactive)
Private Sub New(workspaceElement As XElement,
isImmediateWindow As Boolean,
Optional cursorDocumentElement As XElement = Nothing)
isImmediateWindow As Boolean)
MyBase.New(
workspaceElement,
......@@ -32,7 +31,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
extraExportedTypes:=Nothing,
workspaceKind:=WorkspaceKind.Debugger,
includeFormatCommandHandler:=False,
cursorDocumentElement:=If(cursorDocumentElement, <Document>$$</Document>),
makeSeparateBufferForCursor:=True,
roles:=s_roles)
Dim languageServices = Workspace.CurrentSolution.Projects.First().LanguageServices
......@@ -78,18 +77,16 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
Public Shared Function CreateVisualBasicTestState(
workspaceElement As XElement,
isImmediateWindow As Boolean,
Optional cursorDocumentElement As XElement = Nothing) As TestState
isImmediateWindow As Boolean) As TestState
Return New TestState(workspaceElement, isImmediateWindow, cursorDocumentElement)
Return New TestState(workspaceElement, isImmediateWindow)
End Function
Public Shared Function CreateCSharpTestState(
workspaceElement As XElement,
isImmediateWindow As Boolean,
Optional cursorDocumentElement As XElement = Nothing) As TestState
isImmediateWindow As Boolean) As TestState
Return New TestState(workspaceElement, isImmediateWindow, cursorDocumentElement)
Return New TestState(workspaceElement, isImmediateWindow)
End Function
Public Function GetCurrentViewLineText() As String
......
......@@ -26,7 +26,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics
Dim code = <code>
class 123 { }
</code>
Using workspace = TestWorkspace.CreateCSharp(code.Value)
Using workspace = TestWorkspace.CreateCSharp(code.Value, openDocuments:=True)
Dim diagnosticService = DirectCast(workspace.ExportProvider.GetExportedValue(Of IDiagnosticService), DiagnosticService)
Dim miscService = New DefaultDiagnosticAnalyzerService(New TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()), diagnosticService)
......@@ -53,7 +53,7 @@ class 123 { }
Dim snapshot = buffer.CurrentSnapshot
Dim spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray()
Assert.True(spans.Count() > 0)
Assert.NotEmpty(spans)
Assert.True(spans.All(Function(s) s.Span.Length > 0))
End Using
End Using
......@@ -71,7 +71,7 @@ class A
}
</code>
Using workspace = TestWorkspace.CreateCSharp(code.Value)
Using workspace = TestWorkspace.CreateCSharp(code.Value, openDocuments:=True)
Dim diagnosticService = DirectCast(workspace.ExportProvider.GetExportedValue(Of IDiagnosticService), DiagnosticService)
Dim miscService = New DefaultDiagnosticAnalyzerService(New TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()), diagnosticService)
......@@ -88,8 +88,8 @@ class A
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)
Await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).CreateExpeditedWaitTask()
Assert.True(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None).Count() = 1)
Assert.Single(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None))
End Using
End Function
......@@ -105,7 +105,7 @@ class A
}
</code>
Using workspace = TestWorkspace.CreateCSharp(code.Value)
Using workspace = TestWorkspace.CreateCSharp(code.Value, openDocuments:=True)
Dim diagnosticService = DirectCast(workspace.ExportProvider.GetExportedValue(Of IDiagnosticService), DiagnosticService)
Dim miscService = New DefaultDiagnosticAnalyzerService(New TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()), diagnosticService)
......@@ -121,8 +121,8 @@ class A
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)
Await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).CreateExpeditedWaitTask()
Assert.True(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None).Count() = 1)
Assert.Single(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None))
End Using
End Function
......@@ -138,7 +138,7 @@ class A
}
</code>
Using workspace = TestWorkspace.CreateCSharp(code.Value)
Using workspace = TestWorkspace.CreateCSharp(code.Value, openDocuments:=True)
Dim diagnosticService = DirectCast(workspace.ExportProvider.GetExportedValue(Of IDiagnosticService), DiagnosticService)
Dim miscService = New DefaultDiagnosticAnalyzerService(New TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()), diagnosticService)
......@@ -154,8 +154,8 @@ class A
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)
Await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).CreateExpeditedWaitTask()
Assert.True(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None).Count() = 2)
Assert.Equal(2,
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None).Count())
End Using
End Function
......@@ -171,7 +171,7 @@ class A
}
</code>
Using workspace = TestWorkspace.CreateCSharp(code.Value)
Using workspace = TestWorkspace.CreateCSharp(code.Value, openDocuments:=True)
Dim diagnosticService = DirectCast(workspace.ExportProvider.GetExportedValue(Of IDiagnosticService), DiagnosticService)
Dim miscService = New DefaultDiagnosticAnalyzerService(New TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()), diagnosticService)
......@@ -189,8 +189,8 @@ class A
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)
Await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).CreateExpeditedWaitTask()
Assert.True(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None).Count() = 0)
Assert.Empty(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None))
End Using
End Function
......@@ -199,7 +199,7 @@ class A
Dim code = <code>
class 123 { }
</code>
Using workspace = TestWorkspace.CreateCSharp(code.Value)
Using workspace = TestWorkspace.CreateCSharp(code.Value, openDocuments:=True)
Dim miscService = New DefaultDiagnosticAnalyzerService(New TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()), New MockDiagnosticUpdateSourceRegistrationService())
DiagnosticProvider.Enable(workspace, DiagnosticProvider.Options.Syntax)
......@@ -224,7 +224,7 @@ class 123 { }
Class 123
End Class
</code>
Using workspace = TestWorkspace.CreateVisualBasic(code.Value)
Using workspace = TestWorkspace.CreateVisualBasic(code.Value, openDocuments:=True)
Dim miscService = New DefaultDiagnosticAnalyzerService(New TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()), New MockDiagnosticUpdateSourceRegistrationService())
DiagnosticProvider.Enable(workspace, DiagnosticProvider.Options.Syntax)
......@@ -258,7 +258,7 @@ End Class
Dim analyzerMap = ImmutableDictionary(Of String, ImmutableArray(Of DiagnosticAnalyzer)).Empty.Add(
NoCompilationConstants.LanguageName, ImmutableArray.Create(Of DiagnosticAnalyzer)(New DiagnosticAnalyzerWithSemanticError()))
Using workspace = TestWorkspace.CreateWorkspace(test)
Using workspace = TestWorkspace.CreateWorkspace(test, openDocuments:=True)
Dim diagnosticService = DirectCast(workspace.ExportProvider.GetExportedValue(Of IDiagnosticService), DiagnosticService)
Dim miscService = New DefaultDiagnosticAnalyzerService(New TestDiagnosticAnalyzerService(analyzerMap), diagnosticService)
......@@ -275,8 +275,8 @@ End Class
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)
Await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).CreateExpeditedWaitTask()
Assert.True(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None).Count() = 1)
Assert.Single(
diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, Nothing, False, CancellationToken.None))
End Using
End Function
......
......@@ -263,24 +263,15 @@ using G= H.I;
TestProjectionFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfFact, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_TabSize_3()
TestFormattingWithTabSize(3)
End Sub
<WpfFact, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_TabSize_4()
TestFormattingWithTabSize(4)
End Sub
<WpfFact, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<WpfTheory, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_TabSize_5()
TestFormattingWithTabSize(5)
End Sub
<InlineData(3)>
<InlineData(4)>
<InlineData(5)>
Public Sub TestFormattingWithTabSize(tabSize As Integer)
Dim workspaceXml =
<Workspace>
......@@ -307,7 +298,7 @@ using G= H.I;
}
}</Test>
Using workspace = TestWorkspace.Create(workspaceXml)
Using workspace = TestWorkspace.Create(workspaceXml, openDocuments:=False)
Dim document = workspace.Documents.Single()
workspace.Options = workspace.Options _
......@@ -333,7 +324,6 @@ using G= H.I;
Dim surfaceBufferDocument = workspace.CreateProjectionBufferDocument(
surfaceBufferDocumentXml.NormalizedValue,
{subjectBufferDocument},
LanguageNames.VisualBasic,
options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim snippetExpansionClient = New SnippetExpansionClient(
......
......@@ -313,24 +313,11 @@ Next
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfFact, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<WpfTheory, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_TabSize_3()
TestFormattingWithTabSize(3)
End Sub
<WpfFact, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_TabSize_4()
TestFormattingWithTabSize(4)
End Sub
<WpfFact, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_TabSize_5()
TestFormattingWithTabSize(5)
End Sub
<InlineData(3)>
<InlineData(4)>
<InlineData(5)>
Public Sub TestFormattingWithTabSize(tabSize As Integer)
Dim workspaceXml =
<Workspace>
......@@ -353,7 +340,7 @@ End Class</Document>
End Sub
End Class</Test>
Using workspace = TestWorkspace.Create(workspaceXml)
Using workspace = TestWorkspace.Create(workspaceXml, openDocuments:=False)
Dim document = workspace.Documents.Single()
workspace.Options = workspace.Options _
......@@ -426,7 +413,6 @@ End Class</Test>
Dim surfaceBufferDocument = workspace.CreateProjectionBufferDocument(
surfaceBufferDocumentXml.NormalizedValue,
{subjectBufferDocument},
LanguageNames.VisualBasic,
options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim snippetExpansionClient = New SnippetExpansionClient(
......
......@@ -29,7 +29,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
</Workspace>, exportProvider:=TestExportProvider.ExportProviderWithCSharpAndVisualBasic)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument}, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument})
Dim service = New ContainedDocument.DocumentServiceProvider(projectedDocument.TextBuffer)
Dim spanMapper = service.GetService(Of ISpanMappingService)
......@@ -53,7 +53,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
</Workspace>, exportProvider:=TestExportProvider.ExportProviderWithCSharpAndVisualBasic)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument}, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument})
Dim service = New ContainedDocument.DocumentServiceProvider(projectedDocument.TextBuffer)
Dim spanMapper = service.GetService(Of ISpanMappingService)
......@@ -85,7 +85,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
</Workspace>, exportProvider:=TestExportProvider.ExportProviderWithCSharpAndVisualBasic)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument}, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument})
Dim service = New ContainedDocument.DocumentServiceProvider(projectedDocument.TextBuffer)
Dim documentOperations = service.GetService(Of IDocumentOperationService)
......@@ -111,7 +111,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
</Workspace>, exportProvider:=TestExportProvider.ExportProviderWithCSharpAndVisualBasic)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument}, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument})
Dim service = New ContainedDocument.DocumentServiceProvider(projectedDocument.TextBuffer)
Dim excerptService = service.GetService(Of IDocumentExcerptService)
......@@ -149,7 +149,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
</Workspace>, exportProvider:=TestExportProvider.ExportProviderWithCSharpAndVisualBasic)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument}, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument("class projected { {|Document:|} }", {subjectDocument})
Dim service = New ContainedDocument.DocumentServiceProvider(projectedDocument.TextBuffer)
Dim excerptService = service.GetService(Of IDocumentExcerptService)
......@@ -197,7 +197,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
}|}|}</Code>
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument(projectedContent.NormalizedValue(), {subjectDocument}, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument(projectedContent.NormalizedValue(), {subjectDocument})
Dim service = New ContainedDocument.DocumentServiceProvider(projectedDocument.TextBuffer)
Dim excerptService = service.GetService(Of IDocumentExcerptService)
......@@ -250,7 +250,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
}</Code>
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument(projectedContent.NormalizedValue(), {subjectDocument}, LanguageNames.CSharp)
Dim projectedDocument = workspace.CreateProjectionBufferDocument(projectedContent.NormalizedValue(), {subjectDocument})
Dim service = New ContainedDocument.DocumentServiceProvider(projectedDocument.TextBuffer)
Dim excerptService = service.GetService(Of IDocumentExcerptService)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册