HELLO·Android
系统源代码
IT资讯
技术文章
我的收藏
注册
登录
-
我收藏的文章
创建代码块
我的代码块
我的账号
Android 10
|
10.0.0_r6
下载
查看原文件
收藏
根目录
external
yapf
yapftests
reformatter_basic_test.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Basic tests for yapf.reformatter.""" import textwrap import unittest from yapf.yapflib import reformatter from yapf.yapflib import style from yapftests import yapf_test_helper class BasicReformatterTest(yapf_test_helper.YAPFTest): @classmethod def setUpClass(cls): style.SetGlobalStyle(style.CreateChromiumStyle()) def testSplittingAllArgs(self): style.SetGlobalStyle( style.CreateStyleFromConfig( '{split_all_comma_separated_values: true, column_limit: 40}')) unformatted_code = textwrap.dedent("""\ responseDict = {"timestamp": timestamp, "someValue": value, "whatever": 120} """) expected_formatted_code = textwrap.dedent("""\ responseDict = { "timestamp": timestamp, "someValue": value, "whatever": 120 } """) unformatted_code = textwrap.dedent("""\ def foo(long_arg, really_long_arg, really_really_long_arg, cant_keep_all_these_args): pass """) expected_formatted_code = textwrap.dedent("""\ def foo(long_arg, really_long_arg, really_really_long_arg, cant_keep_all_these_args): pass """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) unformatted_code = textwrap.dedent("""\ foo_tuple = [long_arg, really_long_arg, really_really_long_arg, cant_keep_all_these_args] """) expected_formatted_code = textwrap.dedent("""\ foo_tuple = [ long_arg, really_long_arg, really_really_long_arg, cant_keep_all_these_args ] """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) unformatted_code = textwrap.dedent("""\ foo_tuple = [short, arg] """) expected_formatted_code = textwrap.dedent("""\ foo_tuple = [short, arg] """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testSimpleFunctionsWithTrailingComments(self): unformatted_code = textwrap.dedent("""\ def g(): # Trailing comment if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'): pass def f( # Intermediate comment ): if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'): pass """) expected_formatted_code = textwrap.dedent("""\ def g(): # Trailing comment if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'): pass def f( # Intermediate comment ): if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'): pass """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testBlankLinesAtEndOfFile(self): unformatted_code = textwrap.dedent("""\ def foobar(): # foo pass """) expected_formatted_code = textwrap.dedent("""\ def foobar(): # foo pass """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) unformatted_code = textwrap.dedent("""\ x = { 'a':37,'b':42, 'c':927} """) expected_formatted_code = textwrap.dedent("""\ x = {'a': 37, 'b': 42, 'c': 927} """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testMultipleUgliness(self): unformatted_code = textwrap.dedent("""\ x = { 'a':37,'b':42, 'c':927} y = 'hello ''world' z = 'hello '+'world' a = 'hello {}'.format('world') class foo ( object ): def f (self ): return 37*-+2 def g(self, x,y=42): return y def f ( a ) : return 37+-+a[42-x : y**3] """) expected_formatted_code = textwrap.dedent("""\ x = {'a': 37, 'b': 42, 'c': 927} y = 'hello ' 'world' z = 'hello ' + 'world' a = 'hello {}'.format('world') class foo(object): def f(self): return 37 * -+2 def g(self, x, y=42): return y def f(a): return 37 + -+a[42 - x:y**3] """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testComments(self): unformatted_code = textwrap.dedent("""\ class Foo(object): pass # Attached comment class Bar(object): pass global_assignment = 42 # Comment attached to class with decorator. # Comment attached to class with decorator. @noop @noop class Baz(object): pass # Intermediate comment class Qux(object): pass """) expected_formatted_code = textwrap.dedent("""\ class Foo(object): pass # Attached comment class Bar(object): pass global_assignment = 42 # Comment attached to class with decorator. # Comment attached to class with decorator. @noop @noop class Baz(object): pass # Intermediate comment class Qux(object): pass """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testSingleComment(self): code = textwrap.dedent("""\ # Thing 1 """) uwlines = yapf_test_helper.ParseAndUnwrap(code) self.assertCodeEqual(code, reformatter.Reformat(uwlines)) def testCommentsWithTrailingSpaces(self): unformatted_code = textwrap.dedent("""\ # Thing 1 # Thing 2 """) expected_formatted_code = textwrap.dedent("""\ # Thing 1 # Thing 2 """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testCommentsInDataLiteral(self): code = textwrap.dedent("""\ def f(): return collections.OrderedDict({ # First comment. 'fnord': 37, # Second comment. # Continuation of second comment. 'bork': 42, # Ending comment. }) """) uwlines = yapf_test_helper.ParseAndUnwrap(code) self.assertCodeEqual(code, reformatter.Reformat(uwlines)) def testEndingWhitespaceAfterSimpleStatement(self): code = textwrap.dedent("""\ import foo as bar # Thing 1 # Thing 2 """) uwlines = yapf_test_helper.ParseAndUnwrap(code) self.assertCodeEqual(code, reformatter.Reformat(uwlines)) def testDocstrings(self): unformatted_code = textwrap.dedent('''\ u"""Module-level docstring.""" import os class Foo(object): """Class-level docstring.""" # A comment for qux. def qux(self): """Function-level docstring. A multiline function docstring. """ print('hello {}'.format('world')) return 42 ''') expected_formatted_code = textwrap.dedent('''\ u"""Module-level docstring.""" import os class Foo(object): """Class-level docstring.""" # A comment for qux. def qux(self): """Function-level docstring. A multiline function docstring. """ print('hello {}'.format('world')) return 42 ''') uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testDocstringAndMultilineComment(self): unformatted_code = textwrap.dedent('''\ """Hello world""" # A multiline # comment class bar(object): """class docstring""" # class multiline # comment def foo(self): """Another docstring.""" # Another multiline # comment pass ''') expected_formatted_code = textwrap.dedent('''\ """Hello world""" # A multiline # comment class bar(object): """class docstring""" # class multiline # comment def foo(self): """Another docstring.""" # Another multiline # comment pass ''') uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testMultilineDocstringAndMultilineComment(self): unformatted_code = textwrap.dedent('''\ """Hello world RIP Dennis Richie. """ # A multiline # comment class bar(object): """class docstring A classy class. """ # class multiline # comment def foo(self): """Another docstring. A functional function. """ # Another multiline # comment pass ''') expected_formatted_code = textwrap.dedent('''\ """Hello world RIP Dennis Richie. """ # A multiline # comment class bar(object): """class docstring A classy class. """ # class multiline # comment def foo(self): """Another docstring. A functional function. """ # Another multiline # comment pass ''') uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testTupleCommaBeforeLastParen(self): unformatted_code = textwrap.dedent("""\ a = ( 1, ) """) expected_formatted_code = textwrap.dedent("""\ a = (1,) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testNoBreakOutsideOfBracket(self): # FIXME(morbo): How this is formatted is not correct. But it's syntactically # correct. unformatted_code = textwrap.dedent("""\ def f(): assert port >= minimum, \ 'Unexpected port %d when minimum was %d.' % (port, minimum) """) expected_formatted_code = textwrap.dedent("""\ def f(): assert port >= minimum, 'Unexpected port %d when minimum was %d.' % (port, minimum) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testBlankLinesBeforeDecorators(self): unformatted_code = textwrap.dedent("""\ @foo() class A(object): @bar() @baz() def x(self): pass """) expected_formatted_code = textwrap.dedent("""\ @foo() class A(object): @bar() @baz() def x(self): pass """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testCommentBetweenDecorators(self): unformatted_code = textwrap.dedent("""\ @foo() # frob @bar def x (self): pass """) expected_formatted_code = textwrap.dedent("""\ @foo() # frob @bar def x(self): pass """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testListComprehension(self): unformatted_code = textwrap.dedent("""\ def given(y): [k for k in () if k in y] """) expected_formatted_code = textwrap.dedent("""\ def given(y): [k for k in () if k in y] """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testListComprehensionPreferOneLine(self): unformatted_code = textwrap.dedent("""\ def given(y): long_variable_name = [ long_var_name + 1 for long_var_name in () if long_var_name == 2] """) expected_formatted_code = textwrap.dedent("""\ def given(y): long_variable_name = [ long_var_name + 1 for long_var_name in () if long_var_name == 2 ] """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testListComprehensionPreferOneLineOverArithmeticSplit(self): unformatted_code = textwrap.dedent("""\ def given(used_identifiers): return (sum(len(identifier) for identifier in used_identifiers) / len(used_identifiers)) """) expected_formatted_code = textwrap.dedent("""\ def given(used_identifiers): return (sum(len(identifier) for identifier in used_identifiers) / len(used_identifiers)) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testListComprehensionPreferThreeLinesForLineWrap(self): unformatted_code = textwrap.dedent("""\ def given(y): long_variable_name = [ long_var_name + 1 for long_var_name, number_two in () if long_var_name == 2 and number_two == 3] """) expected_formatted_code = textwrap.dedent("""\ def given(y): long_variable_name = [ long_var_name + 1 for long_var_name, number_two in () if long_var_name == 2 and number_two == 3 ] """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testListComprehensionPreferNoBreakForTrivialExpression(self): unformatted_code = textwrap.dedent("""\ def given(y): long_variable_name = [ long_var_name for long_var_name, number_two in () if long_var_name == 2 and number_two == 3] """) expected_formatted_code = textwrap.dedent("""\ def given(y): long_variable_name = [ long_var_name for long_var_name, number_two in () if long_var_name == 2 and number_two == 3 ] """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testOpeningAndClosingBrackets(self): unformatted_code = """\ foo( (1, ) ) foo( ( 1, 2, 3 ) ) foo( ( 1, 2, 3, ) ) """ expected_formatted_code = """\ foo((1,)) foo((1, 2, 3)) foo(( 1, 2, 3, )) """ uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testSingleLineFunctions(self): unformatted_code = textwrap.dedent("""\ def foo(): return 42 """) expected_formatted_code = textwrap.dedent("""\ def foo(): return 42 """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testNoQueueSeletionInMiddleOfLine(self): # If the queue isn't properly constructed, then a token in the middle of the # line may be selected as the one with least penalty. The tokens after that # one are then splatted at the end of the line with no formatting. unformatted_code = """\ find_symbol(node.type) + "< " + " ".join(find_pattern(n) for n in node.child) + " >" """ expected_formatted_code = """\ find_symbol(node.type) + "< " + " ".join( find_pattern(n) for n in node.child) + " >" """ uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testNoSpacesBetweenSubscriptsAndCalls(self): unformatted_code = textwrap.dedent("""\ aaaaaaaaaa = bbbbbbbb.ccccccccc() [42] (a, 2) """) expected_formatted_code = textwrap.dedent("""\ aaaaaaaaaa = bbbbbbbb.ccccccccc()[42](a, 2) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testNoSpacesBetweenOpeningBracketAndStartingOperator(self): # Unary operator. unformatted_code = textwrap.dedent("""\ aaaaaaaaaa = bbbbbbbb.ccccccccc[ -1 ]( -42 ) """) expected_formatted_code = textwrap.dedent("""\ aaaaaaaaaa = bbbbbbbb.ccccccccc[-1](-42) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) # Varargs and kwargs. unformatted_code = textwrap.dedent("""\ aaaaaaaaaa = bbbbbbbb.ccccccccc( *varargs ) aaaaaaaaaa = bbbbbbbb.ccccccccc( **kwargs ) """) expected_formatted_code = textwrap.dedent("""\ aaaaaaaaaa = bbbbbbbb.ccccccccc(*varargs) aaaaaaaaaa = bbbbbbbb.ccccccccc(**kwargs) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testMultilineCommentReformatted(self): unformatted_code = textwrap.dedent("""\ if True: # This is a multiline # comment. pass """) expected_formatted_code = textwrap.dedent("""\ if True: # This is a multiline # comment. pass """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testDictionaryMakerFormatting(self): unformatted_code = textwrap.dedent("""\ _PYTHON_STATEMENTS = frozenset({ lambda x, y: 'simple_stmt': 'small_stmt', 'expr_stmt': 'print_stmt', 'del_stmt': 'pass_stmt', lambda: 'break_stmt': 'continue_stmt', 'return_stmt': 'raise_stmt', 'yield_stmt': 'import_stmt', lambda: 'global_stmt': 'exec_stmt', 'assert_stmt': 'if_stmt', 'while_stmt': 'for_stmt', }) """) expected_formatted_code = textwrap.dedent("""\ _PYTHON_STATEMENTS = frozenset({ lambda x, y: 'simple_stmt': 'small_stmt', 'expr_stmt': 'print_stmt', 'del_stmt': 'pass_stmt', lambda: 'break_stmt': 'continue_stmt', 'return_stmt': 'raise_stmt', 'yield_stmt': 'import_stmt', lambda: 'global_stmt': 'exec_stmt', 'assert_stmt': 'if_stmt', 'while_stmt': 'for_stmt', }) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testSimpleMultilineCode(self): unformatted_code = textwrap.dedent("""\ if True: aaaaaaaaaaaaaa.bbbbbbbbbbbbbb.ccccccc(zzzzzzzzzzzz, \ xxxxxxxxxxx, yyyyyyyyyyyy, vvvvvvvvv) aaaaaaaaaaaaaa.bbbbbbbbbbbbbb.ccccccc(zzzzzzzzzzzz, \ xxxxxxxxxxx, yyyyyyyyyyyy, vvvvvvvvv) """) expected_formatted_code = textwrap.dedent("""\ if True: aaaaaaaaaaaaaa.bbbbbbbbbbbbbb.ccccccc(zzzzzzzzzzzz, xxxxxxxxxxx, yyyyyyyyyyyy, vvvvvvvvv) aaaaaaaaaaaaaa.bbbbbbbbbbbbbb.ccccccc(zzzzzzzzzzzz, xxxxxxxxxxx, yyyyyyyyyyyy, vvvvvvvvv) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) def testMultilineComment(self): code = textwrap.dedent("""\ if Foo: # Hello world # Yo man. # Yo man. # Yo man. # Yo man. a = 42 """) uwlines = yapf_test_helper.ParseAndUnwrap(code) self.assertCodeEqual(code, reformatter.Reformat(uwlines)) def testMultilineString(self): code = textwrap.dedent("""\ code = textwrap.dedent('''\ if Foo: # Hello world # Yo man. # Yo man. # Yo man. # Yo man. a = 42 ''') """) uwlines = yapf_test_helper.ParseAndUnwrap(code) self.assertCodeEqual(code, reformatter.Reformat(uwlines)) unformatted_code = textwrap.dedent('''\ def f(): email_text += """This is a really long docstring that goes over the column limit and is multi-line.
Czar:
"""+despot["Nicholas"]+"""
Minion:
"""+serf["Dmitri"]+"""
Residence:
"""+palace["Winter"]+"""