Example #1
0
        public void TestCodeFormattingSelection() {
            var input = @"print('Hello World')

class SimpleTest(object):
    def test_simple_addition(self):
        pass

    def test_complex(self):
        pass

class Oar(object):
    def say_hello(self):
        method_end";

            string selection = "def say_hello .. method_end";

            string expected = @"print('Hello World')

class SimpleTest(object):
    def test_simple_addition(self):
        pass

    def test_complex(self):
        pass

class Oar(object):
    def say_hello( self ):
        method_end";

            var options = new CodeFormattingOptions() { 
                SpaceBeforeClassDeclarationParen = true, 
                SpaceWithinFunctionDeclarationParens = true 
            };

            CodeFormattingTest(input, selection, expected, "    def say_hello .. method_end", options);
        }
Example #2
0
        public void TestReflowComment2() {
            foreach (var optionValue in new bool?[] { true, false, null }) {
                var options = new CodeFormattingOptions() {
                    SpaceWithinClassDeclarationParens = optionValue,
                    SpaceWithinEmptyBaseClassList = optionValue,
                    SpaceWithinFunctionDeclarationParens = optionValue,
                    SpaceWithinEmptyParameterList = optionValue,
                    SpaceAroundDefaultValueEquals = optionValue,
                    SpaceBeforeCallParen = optionValue,
                    SpaceWithinEmptyCallArgumentList = optionValue,
                    SpaceWithinCallParens = optionValue,
                    SpacesWithinParenthesisExpression = optionValue,
                    SpaceWithinEmptyTupleExpression = optionValue,
                    SpacesWithinParenthesisedTupleExpression = optionValue,
                    SpacesWithinEmptyListExpression = optionValue,
                    SpacesWithinListExpression = optionValue,
                    SpaceBeforeIndexBracket = optionValue,
                    SpaceWithinIndexBrackets = optionValue,
                    SpacesAroundBinaryOperators = optionValue,
                    SpacesAroundAssignmentOperator = optionValue,
                };

                foreach (var testCase in _commentInsertionSnippets) {
                    Console.WriteLine(testCase);

                    var parser = Parser.CreateParser(
                        new StringReader(testCase.Replace("[INSERT]", "# comment here")), 
                        PythonLanguageVersion.V27, 
                        new ParserOptions() { Verbatim = true }
                    );
                    var ast = parser.ParseFile();
                    var newCode = ast.ToCodeString(ast, options);
                    Console.WriteLine(newCode);
                    Assert.IsTrue(newCode.IndexOf("# comment here") != -1);
                }
            }
        }
Example #3
0
        internal static void TestOneString(PythonLanguageVersion version, string originalText, CodeFormattingOptions format = null, string expected = null, bool recurse = true) {
            bool hadExpected = true;
            if (expected == null) {
                expected = originalText;
                hadExpected = false;
            }
            var parser = Parser.CreateParser(new StringReader(originalText), version, new ParserOptions() { Verbatim = true });
            var ast = parser.ParseFile();

            string output;
            try {
                if (format == null) {
                    output = ast.ToCodeString(ast);
                } else {
                    output = ast.ToCodeString(ast, format);
                }
            } catch(Exception e) {
                Console.WriteLine("Failed to convert to code: {0}\r\n{1}", originalText, e);
                Assert.Fail();
                return;
            }

            const int contextSize = 50;
            for (int i = 0; i < expected.Length && i < output.Length; i++) {
                if (expected[i] != output[i]) {
                    // output some context
                    StringBuilder x = new StringBuilder();
                    StringBuilder y = new StringBuilder();
                    StringBuilder z = new StringBuilder();
                    for (int j = Math.Max(0, i - contextSize); j < Math.Min(Math.Max(expected.Length, output.Length), i + contextSize); j++) {
                        if (j < expected.Length) {
                            x.AppendRepr(expected[j]);
                        }
                        if (j < output.Length) {
                            y.AppendRepr(output[j]);
                        }
                        if (j == i) {
                            z.Append("^");
                        } else {
                            z.Append(" ");
                        }
                    }

                    Console.WriteLine("Mismatch context at {0}:", i);
                    Console.WriteLine("Expected: {0}", x.ToString());
                    Console.WriteLine("Got     : {0}", y.ToString());
                    Console.WriteLine("Differs : {0}", z.ToString());

                    if (recurse) {
                        // Try and automatically get a minimal repro if we can...
                        if (!hadExpected) {
                            try {
                                for (int j = i; j >= 0; j--) {
                                    TestOneString(version, originalText.Substring(j), format, null, false);
                                }
                            } catch {
                            }
                        }
                    } else {
                        Console.WriteLine("-----");
                        Console.WriteLine(expected);
                        Console.WriteLine("-----");
                    }

                    Assert.AreEqual(expected[i], output[i], String.Format("Characters differ at {0}, got {1}, expected {2}", i, output[i], expected[i]));
                }
            }

            if (expected.Length != output.Length) {
                Console.WriteLine("Original: {0}", expected.ToString());
                Console.WriteLine("New     : {0}", output.ToString());
            }
            Assert.AreEqual(expected.Length, output.Length);
        }        
Example #4
0
        private Response ExpressionForDataTip(AP.ExpressionForDataTipRequest request) {
            var pyEntry = _projectFiles[request.fileId] as IPythonProjectEntry;

            string dataTipExpression = null;
            var options = new CodeFormattingOptions() {
                UseVerbatimImage = false
            };

            if (pyEntry != null && pyEntry.Analysis != null) {
                var ast = pyEntry.Analysis.GetAstFromText(request.expr, new SourceLocation(request.index, request.line, request.column));
                var expr = Statement.GetExpression(ast.Body);

                if (ast != null) {
                    var walker = new DetectSideEffectsWalker();
                    ast.Walk(walker);
                    if (!walker.HasSideEffects) {
                        dataTipExpression = expr?.ToCodeString(ast, new CodeFormattingOptions() { UseVerbatimImage = false });
                    }
                }
            }

            return new AP.ExpressionForDataTipResponse() {
                expression = dataTipExpression
            };
        }
Example #5
0
        public void TestCodeFormattingEndOfFile() {
            var input = @"print('Hello World')

class SimpleTest(object):
    def test_simple_addition(self):
        pass

    def test_complex(self):
        pass

class Oar(object):
    def say_hello(self):
        method_end
";

            var options = new CodeFormattingOptions() {
                SpaceBeforeClassDeclarationParen = true,
                SpaceWithinFunctionDeclarationParens = true
            };

            CodeFormattingTest(input, new Span(input.Length, 0), input, null, options);
        }
Example #6
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 serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
            using (var analyzer = new VsProjectAnalyzer(serviceProvider, fact, new[] { fact })) {
                var buffer = new MockTextBuffer(input, PythonCoreConstants.ContentType, "C:\\fob.py");
                buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                var view = new MockTextView(buffer);
                var selectionSpan = new SnapshotSpan(
                    buffer.CurrentSnapshot,
                    ExtractMethodTests.GetSelectionSpan(input, selection)
                );
                view.Selection.Select(selectionSpan, false);

                new CodeFormatter(serviceProvider, view, options).FormatCode(
                    selectionSpan,
                    selectResult
                );

                Assert.AreEqual(expected, view.TextBuffer.CurrentSnapshot.GetText());
                if (expectedSelection != null) {
                    Assert.AreEqual(
                        ExtractMethodTests.GetSelectionSpan(expected, expectedSelection),
                        view.Selection.StreamSelectionSpan.SnapshotSpan.Span
                    );
                }
            }
        }
Example #7
0
        public void FormatDocument() {
            var input = @"fob('Hello World')";
            var expected = @"fob( 'Hello World' )";
            var options = new CodeFormattingOptions() { SpaceWithinCallParens = true };

            CodeFormattingTest(input, new Span(0, input.Length), expected, null, options, false);
        }
Example #8
0
 public CodeFormatter(IServiceProvider serviceProvider, ITextView view, CodeFormattingOptions format) {
     _view = view;
     _format = format;
     _serviceProvider = serviceProvider;
 }