Ejemplo n.º 1
0
 public MockTextSnapshot(MockTextBuffer buffer, string text, MockTextSnapshot prevVersion, params ITextChange[] changes)
 {
     _text    = text;
     _buffer  = buffer;
     _version = new MockTextVersion(prevVersion.Version.VersionNumber + 1, this);
     ((MockTextVersion)prevVersion.Version).SetNext(_version, changes);
 }
Ejemplo n.º 2
0
        private void DataTipTest(string input, string selectionRegex, string expectedDataTip)
        {
            var buffer = new MockTextBuffer(input, @"C:\fob.js", "Node.js");
            var view   = new MockTextView(buffer);

            var classifierProvider = new NodejsClassifierProvider(new MockContentTypeRegistryService(NodejsConstants.Nodejs));

            classifierProvider._classificationRegistry = new MockClassificationTypeRegistryService();
            classifierProvider.GetClassifier(buffer);

            var analyzer = new VsProjectAnalyzer(AnalysisLevel.NodeLsHigh, true);

            buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
            analyzer.AddBuffer(buffer);
            analyzer.WaitForCompleteAnalysis();

            var m = Regex.Match(input, selectionRegex);

            Assert.IsTrue(m.Success);

            var startPos      = m.Index;
            var startLine     = buffer.CurrentSnapshot.GetLineFromPosition(startPos);
            var endPos        = m.Index + m.Length;
            var endLine       = buffer.CurrentSnapshot.GetLineFromPosition(endPos);
            var selectionSpan = new TextSpan {
                iStartLine  = startLine.LineNumber,
                iStartIndex = startPos - startLine.Start.Position,
                iEndLine    = endLine.LineNumber,
                iEndIndex   = endPos - endLine.Start.Position
            };

            var dataTipSpan = DataTipTextViewFilter.GetDataTipSpan(view, selectionSpan);

            if (expectedDataTip == null)
            {
                Assert.IsNull(dataTipSpan);
                return;
            }

            Assert.IsNotNull(dataTipSpan);
            var actualSpan = dataTipSpan.Value;

            startPos = input.IndexOf(expectedDataTip);
            Assert.AreNotEqual(-1, startPos);
            startLine = buffer.CurrentSnapshot.GetLineFromPosition(startPos);
            endPos    = startPos + expectedDataTip.Length;
            endLine   = buffer.CurrentSnapshot.GetLineFromPosition(endPos);
            var expectedSpan = new TextSpan {
                iStartLine  = startLine.LineNumber,
                iStartIndex = startPos - startLine.Start.Position,
                iEndLine    = endLine.LineNumber,
                iEndIndex   = endPos - endLine.Start.Position
            };

            // TextSpan doesn't override ToString, so test output is unusable in case of failure when comparing
            // two spans directly - use an anonymous type instead to produce pretty output.
            Assert.AreEqual(
                new { expectedSpan.iStartLine, expectedSpan.iStartIndex, expectedSpan.iEndLine, expectedSpan.iEndIndex },
                new { actualSpan.iStartLine, actualSpan.iStartIndex, actualSpan.iEndLine, actualSpan.iEndIndex });
        }
Ejemplo n.º 3
0
        public void CanGetTextFromTextBufferTextProperty()
        {
            string         expectedText = "abc";
            MockTextBuffer textBuffer   = new MockTextBuffer(expectedText);

            Assert.AreEqual(expectedText, textBuffer.Text);
        }
Ejemplo n.º 4
0
        public void BufferSync_Issue3570()
        {
            // https://github.com/Microsoft/PTVS/issues/3570

            var buffer = new MockTextBuffer("line");
            var bi     = PythonTextBufferInfo.ForBuffer(null, buffer);

            bi.AddSentSnapshot(buffer.CurrentSnapshot);

            Assert.AreEqual(new SourceLocation(1, 5), bi.LocationTracker.GetSourceLocation(4, 0));

            using (var e = buffer.CreateEdit()) {
                e.Insert(e.Snapshot.Length, "\r\n");
                e.Apply();
            }

            using (var e = buffer.CreateEdit()) {
                e.Insert(e.Snapshot.Length, "    c");
                e.Apply();
            }

            using (var e = buffer.CreateEdit()) {
                e.Insert(e.Snapshot.Length, "o");
                e.Apply();
            }

            var updates    = BufferParser.GetUpdatesForSnapshot(bi, buffer.CurrentSnapshot).ToArray();
            var changeInfo = string.Join(", ", updates
                                         .Select(u => string.Join(", ", u.changes.Select(c => $"({c.startLine},{c.startColumn},'{c.newText}')")))
                                         .Select(u => $"[{u}]"));

            Assert.AreEqual("[(1,5,'\r\n')], [(2,1,'    c')], [(2,6,'o')]", changeInfo);
        }
Ejemplo n.º 5
0
        private static void CodeFormattingTest(string input, object selection, string expected, object expectedSelection, CodeFormattingOptions options, bool selectResult = true)
        {
            var fact     = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
            var services = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = new VsProjectAnalyzer(services, fact)) {
                var buffer = new MockTextBuffer(input, PythonCoreConstants.ContentType, "C:\\fob.py");
                buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                var view = new MockTextView(buffer);
                analyzer.MonitorTextBufferAsync(buffer).Wait();
                var selectionSpan = new SnapshotSpan(
                    buffer.CurrentSnapshot,
                    ExtractMethodTests.GetSelectionSpan(input, selection)
                    );
                view.Selection.Select(selectionSpan, false);

                analyzer.FormatCodeAsync(
                    selectionSpan,
                    view,
                    options,
                    selectResult
                    ).Wait();

                Assert.AreEqual(expected, view.TextBuffer.CurrentSnapshot.GetText());
                if (expectedSelection != null)
                {
                    Assert.AreEqual(
                        ExtractMethodTests.GetSelectionSpan(expected, expectedSelection),
                        view.Selection.StreamSelectionSpan.SnapshotSpan.Span
                        );
                }
            }
        }
Ejemplo n.º 6
0
        public void UnresolvedImportSquiggle()
        {
            var buffer    = new MockTextBuffer("import fob, oar\r\nfrom baz import *\r\nfrom .spam import eggs", PythonCoreConstants.ContentType, filename: "C:\\name.py");
            var squiggles = AnalyzeTextBuffer(buffer).Select(FormatErrorTag).ToArray();

            Console.WriteLine(" Squiggles found:");
            foreach (var actual in squiggles)
            {
                Console.WriteLine(actual);
            }
            Console.WriteLine(" Found {0} squiggle(s)", squiggles.Length);

            int i = 0;

            foreach (var expected in new[] {
                // Ensure that the warning includes the module name
                @".*warning:.*fob.*\(7-10\)",
                @".*warning:.*oar.*\(12-15\)",
                @".*warning:.*baz.*\(22-25\)",
                @".*warning:.*\.spam.*\(41-46\)"
            })
            {
                Assert.IsTrue(i < squiggles.Length, "Not enough squiggles");
                AssertUtil.AreEqual(new Regex(expected, RegexOptions.IgnoreCase | RegexOptions.Singleline), squiggles[i]);
                i += 1;
            }
        }
Ejemplo n.º 7
0
        public void FindEndOfCodeCellWithComment()
        {
            var code = new MockTextBuffer(@"
# Preceding comment
#
# and whitespace

#%% cell here
x

# Next preceding comment

#%% cell here
x
");

            AssertCellEnd(code, 0, 6);
            AssertCellEnd(code, 1, 6);
            AssertCellEnd(code, 4, 6);
            AssertCellEnd(code, 4, 7, withWhitespace: true);
            AssertCellEnd(code, 6, 6);
            AssertCellEnd(code, 7, 11);
            AssertCellEnd(code, 11, 11);
            AssertCellEnd(code, 11, 12, withWhitespace: true);
            AssertCellEnd(code, 12, 11);
        }
Ejemplo n.º 8
0
 private static IEnumerable <TrackingTagSpan <ErrorTag> > AnalyzeTextBuffer(
     MockTextBuffer buffer,
     PythonLanguageVersion version = PythonLanguageVersion.V27
     )
 {
     return(AnalyzeTextBufferAsync(buffer, version).GetAwaiter().GetResult());
 }
Ejemplo n.º 9
0
        private void ExtractMethodTest(string input, Func <Span> extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters)
        {
            var fact            = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version ?? new Version(2, 7));
            var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();

            using (var analyzer = new VsProjectAnalyzer(serviceProvider, fact, new[] { fact })) {
                var buffer = new MockTextBuffer(input, "Python", "C:\\fob.py");
                var view   = new MockTextView(buffer);
                buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                var extractInput = new ExtractMethodTestInput(true, scopeName, targetName, parameters ?? new string[0]);

                view.Selection.Select(
                    new SnapshotSpan(view.TextBuffer.CurrentSnapshot, extract()),
                    false
                    );

                new MethodExtractor(serviceProvider, view).ExtractMethod(extractInput);

                if (expected.IsError)
                {
                    Assert.AreEqual(expected.Text, extractInput.FailureReason);
                    Assert.AreEqual(input, view.TextBuffer.CurrentSnapshot.GetText());
                }
                else
                {
                    Assert.AreEqual(null, extractInput.FailureReason);
                    Assert.AreEqual(expected.Text, view.TextBuffer.CurrentSnapshot.GetText());
                }
            }
        }
Ejemplo n.º 10
0
        public void CanGetTextFromReaderReturnedFromTextBufferCreateReader()
        {
            string         expectedText = "abc";
            MockTextBuffer textBuffer   = new MockTextBuffer("abc");

            StringBuilder text = new StringBuilder();

            using (TextReader reader = textBuffer.CreateReader()) {
                Assert.AreEqual(expectedText, reader.ReadToEnd());
            }
        }
Ejemplo n.º 11
0
        public void SmartTags2()
        {
            var buffer  = new MockTextBuffer("executable", PythonContentType);
            var session = GetSmartTagSession(buffer, 1);

            Assert.AreEqual(1, session.ActionSets.Count);
            AssertUtil.ContainsExactly(
                session.ActionSets.SelectMany(s => s.Actions).Select(s => s.DisplayText),
                "from sys import executable"
                );
        }
Ejemplo n.º 12
0
        private static void FormatDocumentTest(string input, string expected, FormattingOptions options = null)
        {
            string pathToFile = "fob.py";
            var    buffer     = new MockTextBuffer(input, pathToFile, "Node.js");
            var    edits      = Formatter.GetEditsForDocument(
                buffer.CurrentSnapshot.GetText(),
                options ?? new FormattingOptions()
                );

            EditFilter.ApplyEdits(buffer, edits);
            Assert.AreEqual(expected, buffer.CurrentSnapshot.GetText());
        }
Ejemplo n.º 13
0
        private static void AssertIndent(string code, int lineNumber, int expected, int tabSize = 4, int indentSize = 4)
        {
            var buffer = new MockTextBuffer(code, PythonContentType);
            var view   = new MockTextView(buffer);

            view.Options.SetOptionValue(DefaultOptions.IndentSizeOptionId, indentSize);
            view.Options.SetOptionValue(DefaultOptions.TabSizeOptionId, tabSize);

            var line   = buffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber - 1);
            var actual = AutoIndent.GetLineIndentation(PythonTextBufferInfo.ForBuffer(null, buffer), line, view);

            Assert.AreEqual(expected, actual, line.GetText());
        }
Ejemplo n.º 14
0
        private static void AssertExpression(string content, string expected, int index = -1, PythonLanguageVersion version = PythonLanguageVersion.V35)
        {
            var buffer = new MockTextBuffer(content);

            if (index < 0)
            {
                index += content.Length + 1;
            }
            var span   = new SnapshotSpan(buffer.CurrentSnapshot, index, 0);
            var actual = PythonTextBufferInfo.ForBuffer(null, buffer).GetExpressionAtPoint(span, GetExpressionOptions.Hover);

            Assert.AreEqual(expected, actual?.GetText(), content);
        }
Ejemplo n.º 15
0
 public void SmartTags1()
 {
     for (int i = 0; i < 4; ++i)
     {
         var buffer  = new MockTextBuffer("sys", PythonContentType);
         var session = GetSmartTagSession(buffer, i);
         Assert.AreEqual(1, session.ActionSets.Count);
         AssertUtil.ContainsExactly(
             session.ActionSets.SelectMany(s => s.Actions).Select(s => s.DisplayText),
             "import sys"
             );
     }
 }
Ejemplo n.º 16
0
        public void FindStartOfEmptyCodeCell()
        {
            var code = new MockTextBuffer(@"
#%% empty cell here

#%% cell after empty cell

");

            AssertCellStart(code, 1, 1);
            AssertCellStart(code, 2, 1);
            AssertCellStart(code, 3, 3);
            AssertCellStart(code, 4, 3);
        }
Ejemplo n.º 17
0
        public void FindEndOfEmptyCodeCell()
        {
            var code = new MockTextBuffer(@"
#%% empty cell here

#%% cell after empty cell

");

            AssertCellEnd(code, 1, 1);
            AssertCellEnd(code, 1, 2, withWhitespace: true);
            AssertCellEnd(code, 3, 3);
            AssertCellEnd(code, 3, 5, withWhitespace: true);
        }
Ejemplo n.º 18
0
        private void Run()
        {
            PerformanceLogger.DumpEvents += PerformanceLogger_DumpEvents;
            try {
                foreach (var file in _testFiles)
                {
                    var buffer   = new MockTextBuffer(File.ReadAllText(file));
                    var snapshot = buffer.CurrentSnapshot;

                    var behaviour = new LineBehavior {
                        VisibleEmpty      = true,
                        VisibleEmptyAtEnd = true,
                        VisibleAligned    = true,
                        VisibleAtTextEnd  = false,
                        ExtendInwardsOnly = true,
                        VisibleUnaligned  = true
                    };

                    foreach (var chunkSize in new[] { 5, 10, 30, 50, 100, 150, 200 })
                    {
                        var da = new DocumentAnalyzer(snapshot, behaviour, 4, 4, chunkSize);
                        var sw = Stopwatch.StartNew();
                        for (int repeats = 1000; repeats > 0; --repeats)
                        {
                            IndentGuidePackage.JoinableTaskFactory.Run(async delegate
                            {
                                await da.ResetAsync().ConfigureAwait(true);
                            });
                        }

                        for (int line = 0; line < da.Snapshot.LineCount; line += 30)
                        {
                            var lines = da.GetLines(line, line + 35).ToList();
                        }

                        sw.Stop();

                        Console.WriteLine("ChunkSize = {0}", chunkSize);
                        Console.WriteLine("Duration = {0}", sw.ElapsedTicks / 1000);
                        PrintEventSummary(1000);
                        Console.WriteLine();
                    }
                }
            } finally {
                PerformanceLogger.DumpEvents -= PerformanceLogger_DumpEvents;
            }
        }
Ejemplo n.º 19
0
        public void BufferSync_Issue3733()
        {
            // https://github.com/Microsoft/PTVS/issues/3733

            var bigString = string.Join("\n", Enumerable.Repeat("content", 1000));

            var buffer = new MockTextBuffer("");
            var bi     = PythonTextBufferInfo.ForBuffer(null, buffer);

            bi.AddSentSnapshot(buffer.CurrentSnapshot);
            bi.LocationTracker.UpdateBaseSnapshot(buffer.CurrentSnapshot);

            AssertLines(bi, 0);

            using (var e = buffer.CreateEdit())
            {
                e.Insert(e.Snapshot.Length, bigString);
                e.Apply();
            }
            bi.LocationTracker.UpdateBaseSnapshot(buffer.CurrentSnapshot);

            int beforeVersion = bi.Buffer.CurrentSnapshot.Version.VersionNumber;

            using (var e = buffer.CreateEdit())
            {
                e.Replace(0, e.Snapshot.Length, "z");
                e.Apply();
            }
            bi.LocationTracker.UpdateBaseSnapshot(buffer.CurrentSnapshot);

            using (var e = buffer.CreateEdit())
            {
                e.Insert(e.Snapshot.Length, bigString);
                e.Apply();
            }
            bi.LocationTracker.UpdateBaseSnapshot(buffer.CurrentSnapshot);

            var before = bi.LocationTracker.GetLineLocations(beforeVersion);
            var after  = bi.LocationTracker.GetLineLocations(bi.Buffer.CurrentSnapshot.Version.VersionNumber);

            foreach (var t in before.Zip(after, Tuple.Create))
            {
                Assert.AreEqual(t.Item1.EndIndex, t.Item2.EndIndex - 1);
            }
        }
Ejemplo n.º 20
0
        public void FindStartOfCodeCell()
        {
            var code = new MockTextBuffer(@"x
# ...
x
#%% cell here
x

#%% cell here
x
");

            AssertCellStart(code, 0, -1);
            AssertCellStart(code, 2, -1);
            AssertCellStart(code, 3, 3);
            AssertCellStart(code, 5, 3);
            AssertCellStart(code, 6, 6);
            AssertCellStart(code, 8, 6);
        }
Ejemplo n.º 21
0
        private static void AssertHasExpression(string content, bool expectExpression, int index = -1, PythonLanguageVersion version = PythonLanguageVersion.V35)
        {
            var buffer = new MockTextBuffer(content);

            if (index < 0)
            {
                index += content.Length + 1;
            }
            var pt     = new SnapshotPoint(buffer.CurrentSnapshot, index);
            var actual = PythonTextBufferInfo.ForBuffer(null, buffer).IsPossibleExpressionAtPoint(pt);

            if (expectExpression)
            {
                Assert.IsTrue(actual, content);
            }
            else
            {
                Assert.IsFalse(actual, content);
            }
        }
Ejemplo n.º 22
0
        public void FindEndOfCodeCell()
        {
            var code = new MockTextBuffer(@"x
# ...
x
#%% cell here
x

#%% cell here
x
");

            AssertCellEnd(code, 0, 0);
            AssertCellEnd(code, 2, 2);
            AssertCellEnd(code, 3, 4);
            AssertCellEnd(code, 5, 4);  // Start in whitespace finds previous cell
            AssertCellEnd(code, 5, 5, withWhitespace: true);
            AssertCellEnd(code, 6, 7);
            AssertCellEnd(code, 8, 7);  // Start in whitespace finds previous cell
            AssertCellEnd(code, 8, 8, withWhitespace: true);
        }
Ejemplo n.º 23
0
        private static async Task <IEnumerable <TrackingTagSpan <ErrorTag> > > AnalyzeTextBufferAsync(
            MockTextBuffer buffer,
            PythonLanguageVersion version = PythonLanguageVersion.V27
            )
        {
            var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());

            try {
                var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
                var errorProvider   = serviceProvider.ComponentModel.GetService <IErrorProviderFactory>();
                Assert.IsNotNull(errorProvider, "Error provider factory is not available");
                var analyzer = new VsProjectAnalyzer(serviceProvider, fact, new[] { fact });
                buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                var classifierProvider = new PythonClassifierProvider(new MockContentTypeRegistryService(PythonCoreConstants.ContentType), serviceProvider);
                classifierProvider._classificationRegistry = new MockClassificationTypeRegistryService();
                classifierProvider.GetClassifier(buffer);
                var squiggles       = errorProvider.GetErrorTagger(buffer);
                var textView        = new MockTextView(buffer);
                var monitoredBuffer = analyzer.MonitorTextBuffer(textView, buffer);

                var tcs = new TaskCompletionSource <object>();
                buffer.GetPythonProjectEntry().OnNewAnalysis += (s, e) => tcs.SetResult(null);
                await tcs.Task;

                var snapshot = buffer.CurrentSnapshot;

                // Ensure all tasks have been updated
                var taskProvider = (ErrorTaskProvider)serviceProvider.GetService(typeof(ErrorTaskProvider));
                var time         = await taskProvider.FlushAsync();

                Console.WriteLine("TaskProvider.FlushAsync took {0}ms", time.TotalMilliseconds);

                var spans = squiggles.GetTaggedSpans(new SnapshotSpan(snapshot, 0, snapshot.Length));

                analyzer.StopMonitoringTextBuffer(monitoredBuffer.BufferParser, textView);

                return(spans);
            } finally {
            }
        }
Ejemplo n.º 24
0
        private async Task ExtractMethodTest(string input, Func <Span> extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters)
        {
            var fact     = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version ?? new Version(2, 7));
            var services = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = await VsProjectAnalyzer.CreateForTestsAsync(services, fact)) {
                var buffer = new MockTextBuffer(input, PythonCoreConstants.ContentType, Path.Combine(TestData.GetTempPath(), "fob.py"));
                var view   = new MockTextView(buffer);
                buffer.Properties.AddProperty(typeof(VsProjectAnalyzer), analyzer);

                var bi = services.GetBufferInfo(buffer);
                bi.ParseImmediately = true;
                var entry = await analyzer.AnalyzeFileAsync(bi.DocumentUri);

                Assert.AreEqual(entry, bi.TrySetAnalysisEntry(entry, null));
                var bp = entry.GetOrCreateBufferParser(services);
                bp.AddBuffer(buffer);
                await bp.EnsureCodeSyncedAsync(bi.Buffer, true);

                var extractInput = new ExtractMethodTestInput(true, scopeName, targetName, parameters ?? new string[0]);

                view.Selection.Select(
                    new SnapshotSpan(view.TextBuffer.CurrentSnapshot, extract()),
                    false
                    );

                await new Microsoft.PythonTools.Refactoring.MethodExtractor(services, view).ExtractMethod(extractInput);

                if (expected.IsError)
                {
                    Assert.AreEqual(expected.Text, extractInput.FailureReason);
                    Assert.AreEqual(input, view.TextBuffer.CurrentSnapshot.GetText());
                }
                else
                {
                    Assert.AreEqual(null, extractInput.FailureReason);
                    Assert.AreEqual(expected.Text, view.TextBuffer.CurrentSnapshot.GetText());
                }
            }
        }
Ejemplo n.º 25
0
        public void HandledImportSquiggle()
        {
            var testCases = new List <Tuple <string, string[]> >();

            testCases.AddRange(
                new[] { "", " BaseException", " Exception", " ImportError", " (ValueError, ImportError)" }
                .Select(ex => Tuple.Create(
                            string.Format("try:\r\n    import spam\r\nexcept{0}:\r\n    pass\r\n", ex),
                            new string[0]
                            ))
                );

            testCases.Add(Tuple.Create(
                              "try:\r\n    import spam\r\nexcept ValueError:\r\n    pass\r\n",
                              new[] { @".*warning:.*spam.*\(17-21\)" }
                              ));

            foreach (var testCase in testCases)
            {
                var buffer    = new MockTextBuffer(testCase.Item1, PythonCoreConstants.ContentType);
                var squiggles = AnalyzeTextBuffer(buffer).Select(FormatErrorTag).ToArray();

                Console.WriteLine(testCase.Item1);
                Console.WriteLine(" Squiggles found:");
                foreach (var actual in squiggles)
                {
                    Console.WriteLine(actual);
                }
                Console.WriteLine(" Found {0} squiggle(s)", squiggles.Length);
                Console.WriteLine();

                int i = 0;
                foreach (var expected in testCase.Item2)
                {
                    Assert.IsTrue(i < squiggles.Length, "Not enough squiggles");
                    AssertUtil.AreEqual(new Regex(expected, RegexOptions.IgnoreCase | RegexOptions.Singleline), squiggles[i]);
                    i += 1;
                }
            }
        }
Ejemplo n.º 26
0
        private static async Task CodeFormattingTest(string input, object selection, string expected, object expectedSelection, CodeFormattingOptions options, bool selectResult = true)
        {
            var fact     = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
            var services = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = await VsProjectAnalyzer.CreateForTestsAsync(services, fact)) {
                var buffer = new MockTextBuffer(input, PythonCoreConstants.ContentType, Path.Combine(TestData.GetTempPath(), "fob.py"));
                buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                var view  = new MockTextView(buffer);
                var bi    = services.GetBufferInfo(buffer);
                var entry = await analyzer.AnalyzeFileAsync(bi.Filename);

                Assert.AreEqual(entry, bi.TrySetAnalysisEntry(entry, null), "Failed to set analysis entry");
                entry.GetOrCreateBufferParser(services).AddBuffer(buffer);

                var selectionSpan = new SnapshotSpan(
                    buffer.CurrentSnapshot,
                    ExtractMethodTests.GetSelectionSpan(input, selection)
                    );
                view.Selection.Select(selectionSpan, false);

                await analyzer.FormatCodeAsync(
                    selectionSpan,
                    view,
                    options,
                    selectResult
                    );

                Assert.AreEqual(expected, view.TextBuffer.CurrentSnapshot.GetText());
                if (expectedSelection != null)
                {
                    Assert.AreEqual(
                        ExtractMethodTests.GetSelectionSpan(expected, expectedSelection),
                        view.Selection.StreamSelectionSpan.SnapshotSpan.Span
                        );
                }
            }
        }
Ejemplo n.º 27
0
        public void TypeScriptPortedTests()
        {
            dynamic testCases = _serializer.DeserializeObject("[" + File.ReadAllText("ruleFormattingTests.json") + "]");

            var options    = new FormattingOptions();
            int testCaseId = 0;

            foreach (var testCase in testCases)
            {
                string filename = "fob" + testCaseId++ + ".js";
                Console.WriteLine(testCase["input"]);
                var buffer = new MockTextBuffer(testCase["input"], "test.py", "Node.js");
                if (!ApplyEdits(filename, testCase, buffer))
                {
                    continue;
                }

                Assert.AreEqual(
                    ((string)testCase["expected"]).Replace("\r\n", "\n").Replace("\n", "\r\n"),
                    buffer.CurrentSnapshot.GetText().Replace("\r\n", "\n").Replace("\n", "\r\n")
                    );
            }
        }
Ejemplo n.º 28
0
        public void EmptyCodeCell()
        {
            var buffer = new MockTextBuffer(@"# comment here

# In[ ]:

#%% next cell
", PythonContentType);

            AssertCellStart(buffer, 0, 0);
            AssertCellStart(buffer, 1, 0);
            AssertCellStart(buffer, 2, 0);
            AssertCellStart(buffer, 3, 0);
            AssertCellStart(buffer, 4, 4);
            AssertCellStart(buffer, 5, 4);

            AssertCellEnd(buffer, 0, 2);
            AssertCellEnd(buffer, 1, 2);
            AssertCellEnd(buffer, 2, 2);
            AssertCellEnd(buffer, 3, 2);
            AssertCellEnd(buffer, 4, 4);
            AssertCellEnd(buffer, 5, 4);
        }
Ejemplo n.º 29
0
        private void ExtractMethodTest(string input, Func <Span> extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters)
        {
            var fact     = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version ?? new Version(2, 7));
            var services = PythonToolsTestUtilities.CreateMockServiceProvider(suppressTaskProvider: true).GetEditorServices();

            using (var analyzer = new VsProjectAnalyzer(services, fact)) {
                var buffer = new MockTextBuffer(input, "Python", "C:\\fob.py");
                var view   = new MockTextView(buffer);
                buffer.Properties.AddProperty(typeof(VsProjectAnalyzer), analyzer);

                var bi    = services.GetBufferInfo(buffer);
                var entry = analyzer.AnalyzeFileAsync(bi.Filename).WaitAndUnwrapExceptions();
                Assert.AreEqual(entry, bi.TrySetAnalysisEntry(entry, null));
                entry.GetOrCreateBufferParser(services).AddBuffer(buffer);

                var extractInput = new ExtractMethodTestInput(true, scopeName, targetName, parameters ?? new string[0]);

                view.Selection.Select(
                    new SnapshotSpan(view.TextBuffer.CurrentSnapshot, extract()),
                    false
                    );

                new MethodExtractor(services.Site, view).ExtractMethod(extractInput).Wait();

                if (expected.IsError)
                {
                    Assert.AreEqual(expected.Text, extractInput.FailureReason);
                    Assert.AreEqual(input, view.TextBuffer.CurrentSnapshot.GetText());
                }
                else
                {
                    Assert.AreEqual(null, extractInput.FailureReason);
                    Assert.AreEqual(expected.Text, view.TextBuffer.CurrentSnapshot.GetText());
                }
            }
        }
Ejemplo n.º 30
0
        public void FindStartOfCodeCellWithComment()
        {
            var code = new MockTextBuffer(@"
# Preceding comment
#
# and whitespace

#%% cell here
x

# Next preceding commint

#%% cell here
x
");

            AssertCellStart(code, 0, 1);
            AssertCellStart(code, 1, 1);
            AssertCellStart(code, 4, 1);
            AssertCellStart(code, 6, 1);
            AssertCellStart(code, 7, 8);
            AssertCellStart(code, 11, 8);
            AssertCellStart(code, 12, 8);
        }
 internal static DocumentAnalyzer MakeAnalyzer(
     string text,
     LineBehavior behavior,
     int indentSize,
     int tabSize,
     string contentType,
     int chunkSize
 )
 {
     var buffer = new MockTextBuffer(text);
     buffer.ContentType = new MockContentType(contentType, null);
     return MakeAnalyzer(buffer.CurrentSnapshot, behavior, indentSize, tabSize, chunkSize);
 }
        public void UpdateSnapshot()
        {
            var buffer = new MockTextBuffer("");

            var behavior = new LineBehavior();
            var da = MakeAnalyzer(buffer.CurrentSnapshot, behavior, 4, 4, 5);
            da.ResetAndWait();

            da.AssertLinesIncludeExactly();

            var prevSnapshot = da.Snapshot;

            {
                var edit = buffer.CreateEdit();
                edit.Insert(0, @"0
            1
            2
            3
            4");
                edit.Apply();
            }

            da.UpdateAndWait(null);
            Assert.AreNotSame(prevSnapshot, da.Snapshot);
            Assert.AreNotEqual(prevSnapshot.Version.VersionNumber, da.Snapshot.Version.VersionNumber);
            da.AssertLinesIncludeExactly(
                new LineSpan(1, 3, 0, LineSpanType.Normal),
                new LineSpan(2, 2, 4, LineSpanType.Normal)
            );

            prevSnapshot = da.Snapshot;
            {
                var edit = buffer.CreateEdit();
                edit.Delete(prevSnapshot.GetLineFromLineNumber(2).ExtentIncludingLineBreak.Span);
                edit.Apply();
            }

            da.UpdateAndWait(null);
            Assert.AreNotSame(prevSnapshot, da.Snapshot);
            Assert.AreNotEqual(prevSnapshot.Version.VersionNumber, da.Snapshot.Version.VersionNumber);
            da.AssertLinesIncludeExactly(
                new LineSpan(1, 2, 0, LineSpanType.Normal)
            );
        }