public async Task language_service_methods_run_deferred_commands(Language language, string deferredCode, string markupCode, string expectedMimeType, string expectedContentEnd) { // declare a variable in deferred code using var kernel = CreateKernel(language); var languageKernel = kernel.FindKernel(language.LanguageName()); languageKernel.DeferCommand(new SubmitCode(deferredCode)); // send the actual language service request that depends on the deferred code MarkupTestFile.GetLineAndColumn(markupCode, out var code, out var line, out var character); var commandResult = await SendHoverRequest(kernel, code, line, character); commandResult .KernelEvents .ToSubscribedList() .Should() .ContainSingle <HoverTextProduced>() .Which .Content .Should() .Contain(f => f.MimeType == expectedMimeType && f.Value.EndsWith(expectedContentEnd)); }
public async Task NoUrlFoundReturnsNull() { var source = @" public class C { public event System.EventHandler [|E|] { add { } remove { } } }"; await RunTestAsync(async path => { MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); var(project, symbol) = await CompileAndFindSymbolAsync(path, Location.OnDisk, Location.OnDisk, metadataSource, c => c.GetMember("C.E")); // Move the source file to a path that only our fake debugger service knows about var sourceFilePath = Path.Combine(path, "SourceLink.cs"); File.Move(GetSourceFilePath(path), sourceFilePath); var sourceLinkService = new Lazy <ISourceLinkService>(() => new TestSourceLinkService(sourceFilePath: sourceFilePath)); var service = new PdbSourceDocumentLoaderService(sourceLinkService, logger: null); var sourceDocument = new SourceDocument("goo.cs", Text.SourceHashAlgorithm.None, default, null, SourceLinkUrl: null);
public void VerifyAttributeRenameWhileRenameAttributeClass() { var markup = @" using System; [stom] class Bar { } class [|$$stom|]Attribute : Attribute { } "; SetUpEditor(markup); InlineRenameDialog.Invoke(); MarkupTestFile.GetSpans(markup, out _, out ImmutableArray <TextSpan> _); _ = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag); VisualStudio.Editor.SendKeys("Custom"); VisualStudio.Editor.Verify.TextContains( @" using System; [Custom] class Bar { } class Custom$$Attribute : Attribute { } ", true ); }
public void SimpleExtractMethod() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("Console", charsOffset: -1); VisualStudio.Editor.PlaceCaret("World", charsOffset: 4, extendSelection: true); VisualStudio.ExecuteCommand(WellKnownCommandNames.Refactor_ExtractMethod); var expectedMarkup = @" using System; public class Program { public int Method() { [|NewMethod|](); int a; int b; a = 5; b = 10; int result = a * b; return result; } private static void [|NewMethod|]() { Console.WriteLine(""Hello World""); } }"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray <TextSpan> spans); VisualStudio.Editor.Verify.TextContains(expectedText); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Rename); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); VisualStudio.Editor.SendKeys("SayHello", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"private static void SayHello() { Console.WriteLine(""Hello World""); }"); }
public void Outlining() { var input = @" using [|System; using System.Collections.Generic; using System.Text;|] namespace ConsoleApplication1[| { public class Program[| { public static void Main(string[] args)[| { Console.WriteLine(""Hello World""); }|] }|] }|]"; MarkupTestFile.GetSpans(input, out var text, out ImmutableArray <TextSpan> spans); VisualStudio.Editor.SetText(text); Assert.Equal(spans.OrderBy(s => s.Start), VisualStudio.Editor.GetOutliningSpans()); }
public async Task CorruptPdb_NullResult() { var source = @" public class C { public event System.EventHandler [|E|] { add { } remove { } } }"; await RunTestAsync(async path => { MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); var(project, symbol) = await CompileAndFindSymbolAsync(path, Location.OnDisk, Location.OnDisk, metadataSource, c => c.GetMember("C.E")); // The first four bytes of this are BSJB so it is identified as a portable PDB. // The next two bytes are unimportant, they're just not valid PDB data. var corruptPdb = new byte[] { 66, 83, 74, 66, 68, 87 }; File.WriteAllBytes(GetPdbPath(path), corruptPdb); await GenerateFileAndVerifyAsync(project, symbol, source, expectedSpan, expectNullResult: true); }); }
public void VerifyLocalVariableRenameWithStringsUpdated() { var markup = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim [|x|]$$ As Integer = 0 [|x|] = 5 Dim s = ""[|x|] xx [|x|]"" End Sub End Module"; SetUpEditor(markup); InlineRenameDialog.Invoke(); InlineRenameDialog.ToggleIncludeStrings(); MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray <TextSpan> renameSpans); var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag); AssertEx.SetEqual(renameSpans, tags); VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim y As Integer = 0 y = 5 Dim s = ""y xx y"" End Sub End Module"); }
public async Task Completions_are_available_for_symbols_members(Language language) { var declaration = language switch { Language.CSharp => new SubmitCode("var fileInfo = new System.IO.FileInfo(\"temp.file\");"), Language.FSharp => new SubmitCode("let fileInfo = new System.IO.FileInfo(\"temp.file\")") }; var kernel = CreateKernel(language); await kernel.SendAsync(declaration); MarkupTestFile.GetLineAndColumn("fileInfo.$$", out var useInput, out var line, out var column); await kernel.SendAsync(new RequestCompletions(useInput, new LinePosition(line, column))); KernelEvents .Should() .ContainSingle <CompletionsProduced>() .Which .Completions .Should() .Contain(item => item.DisplayText == "AppendText"); }
private async Task VerifyWorkerAsync(string markup, bool isBuilder) { MarkupTestFile.GetPosition(markup, out var code, out int position); using var workspaceFixture = new CSharpTestWorkspaceFixture(); try { workspaceFixture.GetWorkspace(ExportProvider); var document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular); await CheckResultsAsync(document1, position, isBuilder); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate: false); await CheckResultsAsync(document2, position, isBuilder); } } finally { workspaceFixture.DisposeAfterTest(); } }
public async Task completion_commands_and_events_have_offsets_normalized_when_switching_languages() { // switch to PowerShell from an F# kernel/cell using var kernel = CreateCompositeKernel(Language.FSharp); var fullMarkupCode = string.Join("\r\n", new[] { "let x = 1", "#!pwsh", "Get-$$" }); MarkupTestFile.GetLineAndColumn(fullMarkupCode, out var code, out var line, out var character); await kernel.SendAsync(new RequestCompletions(code, new LinePosition(line, character))); KernelEvents .Should() .ContainSingle <CompletionsProduced>() .Which .LinePositionSpan .Should() .Be(new LinePositionSpan(new LinePosition(line, 0), new LinePosition(line, 4))); }
public async Task csharp_completions_can_read_doc_comments_from_nuget_packages_after_forcing_the_assembly_to_load() { using var kernel = CreateKernel(Language.CSharp); await SubmitCode(kernel, "#r \"nuget: Newtonsoft.Json, 12.0.3\""); // The following line forces the assembly and the doc comments to be loaded await SubmitCode(kernel, "var _unused = Newtonsoft.Json.JsonConvert.Null;"); var markupCode = "Newtonsoft.Json.JsonConvert.Nu$$"; MarkupTestFile.GetLineAndColumn(markupCode, out var code, out var line, out var character); await kernel.SendAsync(new RequestCompletions(code, new LinePosition(line, character))); KernelEvents .Should() .ContainSingle <CompletionsProduced>() .Which .Completions .Should() .ContainSingle(ci => !string.IsNullOrEmpty(ci.Documentation) && ci.Documentation.Contains("Represents JavaScript's null as a string. This field is read-only.")); }
public async Task When_Run_is_called_with_instrumentation_and_no_regions_lines_are_not_mapped() { var markedUpCode = @" using System; namespace ConsoleProgram { public class Program { public static void Main(string[] args) { {|line:Console.WriteLine(""test"");|} {|line:var a = 10;|} } } }"; MarkupTestFile.GetNamedSpans(markedUpCode, out var code, out var spans); var linePositionSpans = ToLinePositionSpan(spans, code); var(server, build) = await GetRunnerAndWorkspaceBuild(); var workspace = new Workspace( workspaceType: build.Name, buffers: new[] { new Buffer("Program.cs", code) }, includeInstrumentation: true); var result = await server.Run(new WorkspaceRequest(workspace)); var filePositions = result.Features[nameof(ProgramStateAtPositionArray)].As <ProgramStateAtPositionArray>() .ProgramStates .Where(state => state.FilePosition != null) .Select(state => state.FilePosition.Line); var expectedLines = linePositionSpans["line"].Select(loc => loc.Start.Line); filePositions.Should().BeEquivalentTo(expectedLines); }
public async Task Net6SdkLayout_PacksInPath() { var source = @" public class C { // A change public event System.EventHandler [|E|] { add { } remove { } } }"; await RunTestAsync(async path => { MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); path = Path.Combine(path, "packs", "installed", "here"); var packDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "ref", "net6.0")).FullName; var dataDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "data")).FullName; var sharedDir = Directory.CreateDirectory(Path.Combine(path, "shared", "MyPack", "1.0")).FullName; // Compile reference assembly var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8); var(project, symbol) = await CompileAndFindSymbolAsync(packDir, Location.Embedded, Location.Embedded, sourceText, c => c.GetMember("C.E"), buildReferenceAssembly: true); // Compile implementation assembly CompileTestSource(sharedDir, sourceText, project, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); // Create FrameworkList.xml File.WriteAllText(Path.Combine(dataDir, "FrameworkList.xml"), "" " <FileList FrameworkName=" MyPack "> </FileList> " ""); var workspace = (TestWorkspace)project.Solution.Workspace; var service = workspace.GetService <IImplementationAssemblyLookupService>(); Assert.True(service.TryFindImplementationAssemblyPath(GetDllPath(packDir), out var implementationDll)); Assert.Equal(GetDllPath(sharedDir), implementationDll); }); }
private static PatternMatch?TestNonFuzzyMatch(string candidate, string pattern) { MarkupTestFile.GetSpans(candidate, out candidate, out ImmutableArray <TextSpan> spans); var match = new PatternMatcher(pattern).GetFirstMatch(candidate, includeMatchSpans: true); if (match?.Kind == PatternMatchKind.Fuzzy) { match = null; } if (match == null) { Assert.True(spans.Length == 0); } else { Assert.Equal <TextSpan>(match.Value.MatchedSpans, spans); } return(match); }
protected void Test( string initialMarkup, string expectedMarkup, ParseOptions parseOptions, CompilationOptions compilationOptions, int index = 0, bool compareTokens = true, bool isLine = true, IDictionary <OptionKey, object> options = null, bool isAddedDocument = false, string fixAllActionEquivalenceKey = null) { string expected; IDictionary <string, IList <TextSpan> > spanMap; MarkupTestFile.GetSpans(expectedMarkup.NormalizeLineEndings(), out expected, out spanMap); var conflictSpans = spanMap.GetOrAdd("Conflict", _ => new List <TextSpan>()); var renameSpans = spanMap.GetOrAdd("Rename", _ => new List <TextSpan>()); var warningSpans = spanMap.GetOrAdd("Warning", _ => new List <TextSpan>()); using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup)) { if (options != null) { ApplyOptionsToWorkspace(options, workspace); } var diagnosticAndFixes = GetDiagnosticAndFix(workspace, fixAllActionEquivalenceKey); Assert.NotNull(diagnosticAndFixes); TestActions( workspace, expected, index, diagnosticAndFixes.Item2.Fixes.Select(f => f.Action).ToList(), conflictSpans, renameSpans, warningSpans, compareTokens: compareTokens, isAddedDocument: isAddedDocument); } }
private void Verify(string initialMarkup, string expectedMarkup, Action <IWpfTextView, TestWorkspace> execute, Action <TestWorkspace> setOptionsOpt = null, string newLine = "\r\n") { using (var workspace = CreateTestWorkspace(initialMarkup)) { var testDocument = workspace.Documents.Single(); Assert.True(testDocument.CursorPosition.HasValue, "No caret position set!"); var startCaretPosition = testDocument.CursorPosition.Value; var view = testDocument.GetTextView(); if (testDocument.SelectedSpans.Any()) { var selectedSpan = testDocument.SelectedSpans[0]; var isReversed = selectedSpan.Start == startCaretPosition ? true : false; view.Selection.Select(new SnapshotSpan(view.TextSnapshot, selectedSpan.Start, selectedSpan.Length), isReversed); } view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); setOptionsOpt?.Invoke(workspace); execute(view, workspace); MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var endCaretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == endCaretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, endCaretPosition)); } }
protected async Task TestAsync( string code, string allCode, TestHost testHost, ParseOptions?parseOptions, params FormattedClassification[] expected) { TextSpan span; if (code != allCode) { var start = allCode.IndexOf(code, StringComparison.Ordinal); var length = code.Length; span = new TextSpan(start, length); } else { MarkupTestFile.GetSpans(allCode, out var rewrittenCode, out ImmutableArray <TextSpan> spans); Assert.True(spans.Length < 2); if (spans.Length == 1) { allCode = rewrittenCode; span = spans.Single(); } else { span = new TextSpan(0, allCode.Length); } } var actual = await GetClassificationSpansAsync(allCode, span, parseOptions, testHost); var actualOrdered = actual.OrderBy((t1, t2) => t1.TextSpan.Start - t2.TextSpan.Start); var actualFormatted = actualOrdered.Select(a => new FormattedClassification(allCode.Substring(a.TextSpan.Start, a.TextSpan.Length), a.ClassificationType)); AssertEx.Equal(expected, actualFormatted); }
protected async Task TestBraceHighlightingAsync( string markup, ParseOptions options = null, bool swapAnglesWithBrackets = false) { MarkupTestFile.GetPositionAndSpans(markup, out var text, out int cursorPosition, out var expectedSpans); // needed because markup test file can't support [|[|] to indicate selecting // just an open bracket. if (swapAnglesWithBrackets) { text = text.Replace("<", "[").Replace(">", "]"); } using (var workspace = CreateWorkspace(text, options)) { WpfTestRunner.RequireWpfFact($"{nameof(AbstractBraceHighlightingTests)}.{nameof(TestBraceHighlightingAsync)} creates asynchronous taggers"); var provider = new BraceHighlightingViewTaggerProvider( workspace.GetService <IThreadingContext>(), GetBraceMatchingService(workspace), workspace.GetService <IGlobalOptionService>(), visibilityTracker: null, AsynchronousOperationListenerProvider.NullProvider); var testDocument = workspace.Documents.First(); var buffer = testDocument.GetTextBuffer(); var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(); var context = new TaggerContext <BraceHighlightTag>( document, buffer.CurrentSnapshot, new SnapshotPoint(buffer.CurrentSnapshot, cursorPosition)); await provider.GetTestAccessor().ProduceTagsAsync(context); var expectedHighlights = expectedSpans.Select(ts => ts.ToSpan()).OrderBy(s => s.Start).ToList(); var actualHighlights = context.tagSpans.Select(ts => ts.Span.Span).OrderBy(s => s.Start).ToList(); Assert.Equal(expectedHighlights, actualHighlights); } }
public async Task csharp_hover_text_is_returned_for_shadowing_variables(Language language) { SubmitCode declaration = null; SubmitCode shadowingDeclaration = null; using var kernel = CreateKernel(language); switch (language) { case Language.CSharp: declaration = new SubmitCode("var identifier = 1234;"); shadowingDeclaration = new SubmitCode("var identifier = \"one-two-three-four\";"); break; case Language.FSharp: declaration = new SubmitCode("let identifier = 1234"); shadowingDeclaration = new SubmitCode("let identifier = \"one-two-three-four\""); break; } await kernel.SendAsync(declaration); await kernel.SendAsync(shadowingDeclaration); var markupCode = "ident$$ifier"; MarkupTestFile.GetLineAndColumn(markupCode, out var code, out var line, out var column); var commandResult = await SendHoverRequest(kernel, code, line, column); commandResult .KernelEvents .ToSubscribedList() .Should() .ContainSingle <HoverTextProduced>() .Which .Content .Should() .ContainSingle(fv => fv.Value == "(field) string identifier"); }
public void ServiceTest1() { var service = GetSyntaxTriviaService(); var markupCode = @"class A { /* test */ [|public|] void Test(int i, int b, int c) { } }"; MarkupTestFile.GetSpan(markupCode, out var code, out var span); var root = SyntaxFactory.ParseCompilationUnit(code); var result = service.SaveTriviaAroundSelection(root, span); var rootWithAnnotation = result.Root; // find token to replace var publicToken = rootWithAnnotation.DescendantTokens().First(t => t.Kind() == SyntaxKind.PublicKeyword); // replace the token with new one var newRoot = rootWithAnnotation.ReplaceToken(publicToken, SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); // restore trivia around it var rootWithTriviaRestored = result.RestoreTrivia(newRoot); var expected = @"class A { /* test */ private void Test(int i, int b, int c) { } }"; Assert.Equal(expected, rootWithTriviaRestored.ToFullString()); }
internal async Task VerifyCustomCommitWorkerAsync( CompletionServiceWithProviders service, Document document, CompletionItem completionItem, string codeBeforeCommit, string expectedCodeAfterCommit, char?commitChar = null) { int expectedCaretPosition; string actualExpectedCode = null; MarkupTestFile.GetPosition(expectedCodeAfterCommit, out actualExpectedCode, out expectedCaretPosition); if (commitChar.HasValue && !Controller.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value, commitChar.Value.ToString())) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } var commit = await service.GetChangeAsync(document, completionItem, commitChar, CancellationToken.None); var text = await document.GetTextAsync(); var newText = text.WithChanges(commit.TextChange); var newDoc = document.WithText(newText); document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution); var textBuffer = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().TextBuffer; var textView = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().GetTextView(); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = commit.NewPosition != null ? commit.NewPosition.Value : textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); }
internal virtual async Task VerifyCustomCommitWorkerAsync( Document document, CompletionItem completionItem, string codeBeforeCommit, string expectedCodeAfterCommit, char?commitChar = null) { int expectedCaretPosition; string actualExpectedCode = null; MarkupTestFile.GetPosition(expectedCodeAfterCommit, out actualExpectedCode, out expectedCaretPosition); CompletionHelper completionRules = GetCompletionHelper(document); if (commitChar.HasValue && !completionRules.IsCommitCharacter(completionItem, commitChar.Value, string.Empty)) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } var service = CompletionService.GetService(document); var commit = service.GetChangeAsync(document, completionItem, commitChar).Result; var text = document.GetTextAsync().Result; var newText = text.WithChanges(commit.TextChanges); var newDoc = document.WithText(newText); document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution); var textBuffer = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().TextBuffer; var textView = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().GetTextView(); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = commit.NewPosition != null ? commit.NewPosition.Value : textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); }
public void VBPropertyTest() { var markup = @"Class C Default Public Property G(x As Integer) As Integer Get $$ End Get Set(value As Integer) End Set End Property End Class"; int position; string code; MarkupTestFile.GetPosition(markup, out code, out position); var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code); var property = root.FindToken(position).Parent.FirstAncestorOrSelf <Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>(); var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property); Assert.Equal(0, memberId); }
public async Task requested_diagnostics_are_remapped_to_the_appropriate_span(Language language, string languageSpecificCode) { var kernel = CreateKernel(language); var fullCode = $@" #!time $${languageSpecificCode} "; MarkupTestFile.GetLineAndColumn(fullCode, out var code, out var line, out var _column); await kernel.SendAsync(new RequestDiagnostics(code)); KernelEvents .Should() .ContainSingle <DiagnosticsProduced>(d => d.Diagnostics.Count == 1) .Which .Diagnostics .Should() .ContainSingle(diag => diag.LinePositionSpan.Start.Line == line); }
public void Verify(string initialMarkup, string expectedMarkup, char typeChar) { using (var workspace = CreateTestWorkspace(initialMarkup)) { var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); var commandHandler = CreateCommandHandler(workspace); var args = new TypeCharCommandArgs(view, view.TextBuffer, typeChar); var nextHandler = CreateInsertTextHandler(view, typeChar.ToString()); commandHandler.ExecuteCommand(args, nextHandler, TestCommandExecutionContext.Create()); MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } }
protected void Verify(string initialMarkup, string expectedMarkup) { using (var workspace = CreateTestWorkspace(initialMarkup)) { var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); var commandHandler = CreateCommandHandler(workspace.GetService <ITextUndoHistoryRegistry>(), workspace.GetService <IEditorOperationsFactoryService>()); var args = new ReturnKeyCommandArgs(view, view.TextBuffer); var nextHandler = CreateInsertTextHandler(view, "\r\n"); commandHandler.ExecuteCommand(args, nextHandler); MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } }
public void RequestDiagnostics_can_be_split_into_separate_commands() { var markupCode = @" #!time$$ // language-specific code"; MarkupTestFile.GetLineAndColumn(markupCode, out var code, out var startLineOfCode, out var _column); var sourceText = SourceText.From(code); var command = new RequestDiagnostics(code); var commands = new CSharpKernel().UseDefaultMagicCommands().SubmissionParser.SplitSubmission(command); commands .Should() .ContainSingle <RequestDiagnostics>() .Which .Code .Should() .NotContain("#!time"); }
public void VerifyResult(MetadataAsSourceFile file, string expected, bool compareTokens = true) { var actual = File.ReadAllText(file.FilePath).Trim(); var actualSpan = file.IdentifierLocation.SourceSpan; if (compareTokens) { // Compare tokens and verify location relative to the generated tokens expected = GetSpaceSeparatedTokens(expected); actual = GetSpaceSeparatedTokens(actual.Insert(actualSpan.Start, "[|").Insert(actualSpan.End + 2, "|]")); } else { // Compare exact texts and verify that the location returned is exactly that // indicated by expected TextSpan expectedSpan; MarkupTestFile.GetSpan(expected.TrimStart().TrimEnd(), out expected, out expectedSpan); Assert.Equal(expectedSpan.Start, actualSpan.Start); Assert.Equal(expectedSpan.End, actualSpan.End); } Assert.Equal(expected, actual); }
private void TestWorker( string inputMarkup, string expectedOutputMarkup, Action callback) { using (var workspace = TestWorkspace.CreateCSharp(inputMarkup)) { var document = workspace.Documents.Single(); var view = document.GetTextView(); var snapshot = view.TextBuffer.CurrentSnapshot; view.SetSelection(document.SelectedSpans.Single().ToSnapshotSpan(snapshot)); var commandHandler = new SplitStringLiteralCommandHandler(); commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), callback); if (expectedOutputMarkup != null) { MarkupTestFile.GetSpans(expectedOutputMarkup, out var expectedOutput, out IList <TextSpan> expectedSpans); Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString()); Assert.Equal(expectedSpans.Single().Start, view.Caret.Position.BufferPosition.Position); } } }
private static void VerifyRange( string codeWithMarker, string language = LanguageNames.CSharp ) { MarkupTestFile.GetSpans( codeWithMarker, out var codeWithoutMarker, out IDictionary <string, ImmutableArray <TextSpan> > namedSpans ); var expectedResult = namedSpans.ContainsKey("r") ? namedSpans["r"] as IEnumerable <TextSpan> : SpecializedCollections.EmptyEnumerable <TextSpan>(); VerifyRange( codeWithoutMarker, ImmutableArray <ICodeCleanupProvider> .Empty, namedSpans["b"], ref expectedResult, language ); }