Exemple #1
0
        public async Task completions_show_custom_DataFrame_members()
        {
            using var kernel = await CreateKernelAndGenerateType();

            var markupCode = "frame.Where(s => s.$$)";

            MarkupTestFile.GetPosition(markupCode, out var code, out var position);

            var events = await kernel.SendAsync(new RequestCompletions(code, new LinePosition(0, position.Value)));

            events
            .KernelEvents
            .ToSubscribedList()
            .Should()
            .ContainSingle <CompletionsProduced>()
            .Which
            .Completions
            .Select(c => c.DisplayText)
            .Should()
            .Contain(new[] { "name", "is_available", "price_in_credits" });
        }
        protected void SetUpEditor(string markupCode)
        {
            MarkupTestFile.GetPosition(markupCode, out var code, out int caretPosition);

            VisualStudio.Editor.DismissCompletionSessions();
            VisualStudio.Editor.DismissLightBulbSession();

            var originalValue = VisualStudio.Workspace.IsPrettyListingOn(LanguageName);

            VisualStudio.Workspace.SetPrettyListing(LanguageName, false);
            try
            {
                VisualStudio.Editor.SetText(code);
                VisualStudio.Editor.MoveCaret(caretPosition);
                VisualStudio.Editor.Activate();
            }
            finally
            {
                VisualStudio.Workspace.SetPrettyListing(LanguageName, originalValue);
            }
        }
Exemple #3
0
        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);

            CompletionHelper completionRules = GetCompletionHelper(document, service);

            if (commitChar.HasValue && !completionRules.IsCommitCharacter(completionItem, commitChar.Value, string.Empty))
            {
                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.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);
        }
Exemple #4
0
        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();
            }
        }
Exemple #5
0
        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
                        )
                    );
            }
        }
        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));
            }
        }
Exemple #7
0
        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);
        }
Exemple #8
0
        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));
            }
        }
        protected static void AssertFormatWithPasteOrReturn(string expectedWithMarker, string codeWithMarker, bool allowDocumentChanges, bool isPaste = true)
        {
            using (var workspace = TestWorkspace.CreateCSharp(codeWithMarker))
            {
                workspace.CanApplyChangeDocument = allowDocumentChanges;

                // set up caret position
                var testDocument = workspace.Documents.Single();
                var view         = testDocument.GetTextView();
                view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));

                // get original buffer
                var buffer = workspace.Documents.First().GetTextBuffer();

                if (isPaste)
                {
                    var commandHandler = workspace.GetService <FormatCommandHandler>();
                    var commandArgs    = new PasteCommandArgs(view, view.TextBuffer);
                    commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create());
                }
                else
                {
                    // Return Key Command
                    var commandHandler = workspace.GetService <FormatCommandHandler>();
                    var commandArgs    = new ReturnKeyCommandArgs(view, view.TextBuffer);
                    commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create());
                }

                MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition);

                Assert.Equal(expected, 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));
            }
        }
Exemple #10
0
        public TestWorkspace GetWorkspace(string markup, ExportProvider exportProvider = null, string workspaceKind = null)
        {
            // If it looks like XML, we'll treat it as XML; any parse error would be rejected and will throw.
            // We'll do a case insensitive search here so if somebody has a lowercase W it'll be tried (and
            // rejected by the XML parser) rather than treated as regular text.
            if (markup.TrimStart().StartsWith("<Workspace>", StringComparison.OrdinalIgnoreCase))
            {
                CloseTextView();
                _workspace?.Dispose();

                _workspace       = TestWorkspace.CreateWorkspace(XElement.Parse(markup), exportProvider: exportProvider, workspaceKind: workspaceKind);
                _currentDocument = _workspace.Documents.First(d => d.CursorPosition.HasValue);
                Position         = _currentDocument.CursorPosition.Value;
                Code             = _currentDocument.GetTextBuffer().CurrentSnapshot.GetText();
                return(_workspace);
            }
            else
            {
                MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out Code, out Position);
                var workspace = GetWorkspace(exportProvider);
                _currentDocument = workspace.Documents.Single();
                return(workspace);
            }
        }
        protected static void AssertFormatWithView(string expectedWithMarker, string codeWithMarker, bool debugMode = false)
        {
            var editorOperations = new Mock <IEditorOperations>(MockBehavior.Strict);
            var editorOperationsFactoryService = new Mock <IEditorOperationsFactoryService>(MockBehavior.Strict);

            editorOperations.Setup(o => o.AddAfterTextBufferChangePrimitive());
            editorOperations.Setup(o => o.AddBeforeTextBufferChangePrimitive());

            editorOperationsFactoryService.Setup(s => s.GetEditorOperations(It.IsAny <ITextView>())).Returns(editorOperations.Object);

            using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(codeWithMarker))
            {
                // set up caret position
                var testDocument = workspace.Documents.Single();
                var view         = testDocument.GetTextView();
                view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));

                // get original buffer
                var buffer = workspace.Documents.First().GetTextBuffer();

                var commandHandler = new FormatCommandHandler(TestWaitIndicator.Default, workspace.GetService <ITextUndoHistoryRegistry>(), editorOperationsFactoryService.Object);

                var commandArgs = new FormatDocumentCommandArgs(view, view.TextBuffer);
                commandHandler.ExecuteCommand(commandArgs, () => { });

                string expected;
                int    expectedPosition;
                MarkupTestFile.GetPosition(expectedWithMarker, out expected, out expectedPosition);

                Assert.Equal(expected, 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));
            }
        }
Exemple #12
0
        private static Buffer EntrypointCode(string mainContent = @"Console.WriteLine(Sample.Method());$$")
        {
            var input = $@"
using System;
using System.Linq;

namespace Example
{{
    public class Program
    {{
        public static void Main()
        {{
            {mainContent}
        }}       
    }}
}}".EnforceLF();

            MarkupTestFile.GetPosition(input, out var output, out var position);

            return(new Buffer(
                       "Program.cs",
                       output,
                       position ?? 0));
        }
        public void FixAllOccurrencesIgnoresGeneratedCode(FixAllScope scope)
        {
            var markup                  = @"
using System;
using $$System.Threading;

class C
{
    public IntPtr X1 { get; set; }
}";
            var expectedText            = @"
using System;

class C
{
    public IntPtr X1 { get; set; }
}";
            var generatedSourceMarkup   = @"// <auto-generated/>
using System;
using $$System.Threading;

class D
{
    public IntPtr X1 { get; set; }
}";
            var expectedGeneratedSource = @"// <auto-generated/>
using System;

class D
{
    public IntPtr X1 { get; set; }
}";

            MarkupTestFile.GetPosition(generatedSourceMarkup, out var generatedSource, out int generatedSourcePosition);

            VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), "D.cs", generatedSource, open: false);

            // Switch to the main document we'll be editing
            VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");

            // Verify that applying a Fix All operation does not change generated files.
            // This is a regression test for correctness with respect to the design.
            SetUpEditor(markup);
            VisualStudio.WaitForApplicationIdle(CancellationToken.None);
            VisualStudio.Editor.InvokeCodeActionList();
            VisualStudio.Editor.Verify.CodeAction(
                "Remove Unnecessary Usings",
                applyFix: true,
                fixAllScope: scope);

            Assert.Equal(expectedText, VisualStudio.Editor.GetText());

            VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "D.cs");
            Assert.Equal(generatedSource, VisualStudio.Editor.GetText());

            // Verify that a Fix All in Document in the generated file still does nothing.
            // ⚠ This is a statement of the current behavior, and not a claim regarding correctness of the design.
            // The current behavior is observable; any change to this behavior should be part of an intentional design
            // change.
            VisualStudio.Editor.MoveCaret(generatedSourcePosition);
            VisualStudio.Editor.InvokeCodeActionList();
            VisualStudio.Editor.Verify.CodeAction(
                "Remove Unnecessary Usings",
                applyFix: true,
                fixAllScope: FixAllScope.Document);

            Assert.Equal(generatedSource, VisualStudio.Editor.GetText());

            // Verify that the code action can still be applied manually from within the generated file.
            // This is a regression test for correctness with respect to the design.
            VisualStudio.Editor.MoveCaret(generatedSourcePosition);
            VisualStudio.Editor.InvokeCodeActionList();
            VisualStudio.Editor.Verify.CodeAction(
                "Remove Unnecessary Usings",
                applyFix: true,
                fixAllScope: null);

            Assert.Equal(expectedGeneratedSource, VisualStudio.Editor.GetText());
        }
        private void Verify(
            string initialMarkup,
            string expectedMarkup,
            bool useTabs,
            bool autoGenerateXmlDocComments,
            Action <TestWorkspace, IWpfTextView, IEditorOperationsFactoryService> execute,
            Action <TestWorkspace> setOptionsOpt = null,
            string newLine = "\r\n"
            )
        {
            using (var workspace = CreateTestWorkspace(initialMarkup))
            {
                var testDocument = workspace.Documents.Single();

                var options = workspace.Options;

                options = options.WithChangedOption(
                    FormattingOptions.UseTabs,
                    testDocument.Project.Language,
                    useTabs
                    );
                options = options.WithChangedOption(
                    DocumentationCommentOptions.AutoXmlDocCommentGeneration,
                    testDocument.Project.Language,
                    autoGenerateXmlDocComments
                    );
                options = options.WithChangedOption(
                    FormattingOptions.NewLine,
                    testDocument.Project.Language,
                    newLine
                    );

                workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));

                setOptionsOpt?.Invoke(workspace);

                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)
                    );

                execute(workspace, view, workspace.GetService <IEditorOperationsFactoryService>());
                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
                        )
                    );
            }
        }
Exemple #15
0
 internal void AssertCodeIs(string expectedCode)
 {
     MarkupTestFile.GetPosition(expectedCode, out var massaged, out int caretPosition);
     Assert.Equal(massaged, TextView.TextSnapshot.GetText());
     Assert.Equal(caretPosition, TextView.Caret.Position.BufferPosition.Position);
 }
Exemple #16
0
 private (Document, int) ApplyChangesToFixture(string markup)
 {
     MarkupTestFile.GetPosition(markup, out var text, out int position);
     return(fixture.UpdateDocument(text, SourceCodeKind.Regular), position);
 }
Exemple #17
0
        public async Task FixAllOccurrencesIgnoresGeneratedCode(FixAllScope scope)
        {
            var markup                  = @"
using System;
using $$System.Threading;

class C
{
    public IntPtr X1 { get; set; }
}";
            var expectedText            = @"
using System;

class C
{
    public IntPtr X1 { get; set; }
}";
            var generatedSourceMarkup   = @"// <auto-generated/>
using System;
using $$System.Threading;

class D
{
    public IntPtr X1 { get; set; }
}";
            var expectedGeneratedSource = @"// <auto-generated/>
using System;

class D
{
    public IntPtr X1 { get; set; }
}";

            MarkupTestFile.GetPosition(generatedSourceMarkup, out var generatedSource, out int generatedSourcePosition);

            await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "D.cs", generatedSource, open : false, HangMitigatingCancellationToken);

            // Switch to the main document we'll be editing
            await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken);

            // Verify that applying a Fix All operation does not change generated files.
            // This is a regression test for correctness with respect to the design.
            await SetUpEditorAsync(markup, HangMitigatingCancellationToken);

            await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken);

            await TestServices.EditorVerifier.CodeActionAsync(
                "Remove Unnecessary Usings",
                applyFix : true,
                fixAllScope : scope,
                cancellationToken : HangMitigatingCancellationToken);

            AssertEx.EqualOrDiff(expectedText, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken));

            await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "D.cs", HangMitigatingCancellationToken);

            AssertEx.EqualOrDiff(generatedSource, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken));

            // Verify that a Fix All in Document in the generated file still does nothing.
            // ⚠ This is a statement of the current behavior, and not a claim regarding correctness of the design.
            // The current behavior is observable; any change to this behavior should be part of an intentional design
            // change.
            await TestServices.Editor.MoveCaretAsync(generatedSourcePosition, HangMitigatingCancellationToken);

            await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken);

            await TestServices.EditorVerifier.CodeActionAsync(
                "Remove Unnecessary Usings",
                applyFix : true,
                fixAllScope : FixAllScope.Document,
                cancellationToken : HangMitigatingCancellationToken);

            AssertEx.EqualOrDiff(generatedSource, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken));

            // Verify that the code action can still be applied manually from within the generated file.
            // This is a regression test for correctness with respect to the design.
            await TestServices.Editor.MoveCaretAsync(generatedSourcePosition, HangMitigatingCancellationToken);

            await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken);

            await TestServices.EditorVerifier.CodeActionAsync(
                "Remove Unnecessary Usings",
                applyFix : true,
                fixAllScope : null,
                cancellationToken : HangMitigatingCancellationToken);

            AssertEx.EqualOrDiff(expectedGeneratedSource, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken));
        }
Exemple #18
0
        public void FixAllOccurrencesTriggeredFromGeneratedCode(FixAllScope scope)
        {
            var markup =
                @"// <auto-generated/>
using System;
using $$System.Threading;

class C
{
    public IntPtr X1 { get; set; }
}";
            var secondFile =
                @"
using System;
using System.Threading;

class D
{
    public IntPtr X1 { get; set; }
}";
            var expectedSecondFile =
                @"
using System;

class D
{
    public IntPtr X1 { get; set; }
}";

            VisualStudio.SolutionExplorer.AddFile(
                new ProjectUtils.Project(ProjectName),
                "D.cs",
                secondFile,
                open: false
                );

            // Switch to the main document we'll be editing
            VisualStudio.SolutionExplorer.OpenFile(
                new ProjectUtils.Project(ProjectName),
                "Class1.cs"
                );

            // Verify that applying a Fix All operation does not change generated file, but does change other files.
            // ⚠ This is a statement of the current behavior, and not a claim regarding correctness of the design.
            // The current behavior is observable; any change to this behavior should be part of an intentional design
            // change.
            MarkupTestFile.GetPosition(markup, out var expectedText, out int _);
            SetUpEditor(markup);
            VisualStudio.WaitForApplicationIdle(CancellationToken.None);
            VisualStudio.Editor.InvokeCodeActionList();
            VisualStudio.Editor.Verify.CodeAction(
                "Remove Unnecessary Usings",
                applyFix: true,
                fixAllScope: scope
                );

            Assert.Equal(expectedText, VisualStudio.Editor.GetText());

            VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "D.cs");
            Assert.Equal(expectedSecondFile, VisualStudio.Editor.GetText());
        }