Esempio n. 1
0
 def testNoVerify(self):
   unformatted_code = textwrap.dedent("""\
       class ABC(metaclass=type):
         pass
       """)
   expected_formatted_code = textwrap.dedent("""\
       class ABC(metaclass=type):
           pass
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code,
                        reformatter.Reformat(uwlines, verify=False))
 def testIndent4(self):
     unformatted_code = textwrap.dedent("""\
     if a+b:
       pass
     """)
     expected_formatted_code = textwrap.dedent("""\
     if a + b:
         pass
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))
Esempio n. 3
0
 def testSpaceBetweenEndingCommandAndClosingBracket(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))
Esempio n. 4
0
 def testSingleWhiteBeforeTrailingComment(self):
     unformatted_code = textwrap.dedent("""\
     if a+b: # comment
       pass
     """)
     expected_formatted_code = textwrap.dedent("""\
     if a + b:  # comment
         pass
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))
Esempio n. 5
0
 def testIndentSizeChanging(self):
   unformatted_code = textwrap.dedent("""\
       if True:
         runtime_mins = (program_end_time - program_start_time).total_seconds() / 60.0
       """)
   expected_formatted_code = textwrap.dedent("""\
       if True:
           runtime_mins = (
               program_end_time - program_start_time).total_seconds() / 60.0
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 6
0
 def testSplittingExpressionsInsideSubscripts(self):
   unformatted_code = textwrap.dedent("""\
       def foo():
           df = df[(df['campaign_status'] == 'LIVE') & (df['action_status'] == 'LIVE')]
       """)
   expected_formatted_code = textwrap.dedent("""\
       def foo():
           df = df[(df['campaign_status'] == 'LIVE') &
                   (df['action_status'] == 'LIVE')]
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 7
0
 def testTypedNameWithLongNamedArg(self):
   unformatted_code = textwrap.dedent("""\
       def func(arg=long_function_call_that_pushes_the_line_over_eighty_characters()) -> ReturnType:
         pass
       """)
   expected_formatted_code = textwrap.dedent("""\
       def func(arg=long_function_call_that_pushes_the_line_over_eighty_characters()
                ) -> ReturnType:
           pass
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 8
0
 def testForElseInAsyncNotMixedWithAsyncFor(self):
   if sys.version_info[1] < 5:
     return
   code = textwrap.dedent("""\
   async def fn():
       for i in range(10):
           pass
       else:
           pass
   """)
   uwlines = yapf_test_helper.ParseAndUnwrap(code)
   self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Esempio n. 9
0
  def testMultilineFormatString(self):
    if sys.version_info[1] < 6:
      return
    code = """\
# yapf: disable
(f'''
  ''')
# yapf: enable
"""
    # https://github.com/google/yapf/issues/513
    uwlines = yapf_test_helper.ParseAndUnwrap(code)
    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Esempio n. 10
0
    def testCommentsBeforeClassDefs(self):
        code = textwrap.dedent('''\
        """Test."""

        # Comment


        class Foo(object):
          pass
        ''')
        uwlines = yapf_test_helper.ParseAndUnwrap(code)
        self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Esempio n. 11
0
def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False):
  """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    style_config, lines, print_diff: see comment at the top of this module.

  Returns:
    The code reformatted to conform to the desired formatting style.
  """
  style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
  tree = pytree_utils.ParseCodeToTree(unformatted_source.rstrip() + '\n')

  # Run passes on the tree, modifying it in place.
  comment_splicer.SpliceComments(tree)
  subtype_assigner.AssignSubtypes(tree)
  split_penalty.ComputeSplitPenalties(tree)
  blank_line_calculator.CalculateBlankLines(tree)

  uwlines = pytree_unwrapper.UnwrapPyTree(tree)
  if not uwlines:
    return ''
  for uwl in uwlines:
    uwl.CalculateFormattingInformation()

  if lines is not None:
    reformatted_source = _FormatLineSnippets(unformatted_source, uwlines, lines)
  else:
    lines = _LinesToFormat(uwlines)
    if lines:
      reformatted_source = _FormatLineSnippets(unformatted_source, uwlines,
                                               lines)
    else:
      reformatted_source = reformatter.Reformat(uwlines)

  if unformatted_source == reformatted_source:
    return '' if print_diff else reformatted_source

  code_diff = _GetUnifiedDiff(unformatted_source, reformatted_source,
                              filename=filename)

  if print_diff:
    return code_diff

  return reformatted_source
Esempio n. 12
0
 def testB30442148(self):
   unformatted_code = textwrap.dedent("""\
       def lulz():
         return (some_long_module_name.SomeLongClassName.
                 some_long_attribute_name.some_long_method_name())
       """)
   expected_formatted_code = textwrap.dedent("""\
       def lulz():
         return (some_long_module_name.SomeLongClassName.some_long_attribute_name.
                 some_long_method_name())
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 13
0
 def testB14468247(self):
   unformatted_code = textwrap.dedent("""\
       call(a=1,
           b=2,
       )
       """)
   expected_formatted_code = textwrap.dedent("""\
       call(
           a=1,
           b=2,)
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 14
0
 def testB30760569(self):
   unformatted_code = textwrap.dedent("""\
       {'1234567890123456789012345678901234567890123456789012345678901234567890':
            '1234567890123456789012345678901234567890'}
       """)
   expected_formatted_code = textwrap.dedent("""\
       {
           '1234567890123456789012345678901234567890123456789012345678901234567890':
               '1234567890123456789012345678901234567890'
       }
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 15
0
 def testMustSplitDedenting(self):
     code = textwrap.dedent("""\
     class _():
         def _():
             effect_line = FrontInput(
                 effect_line_offset, line_content,
                 LineSource(
                     'localhost', xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                 )
             )
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(code)
     self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Esempio n. 16
0
 def testB17534869(self):
   unformatted_code = textwrap.dedent("""\
       if True:
         self.assertLess(abs(time.time()-aaaa.bbbbbbbbbbb(
                             datetime.datetime.now())), 1)
       """)
   expected_formatted_code = textwrap.dedent("""\
       if True:
         self.assertLess(
             abs(time.time() - aaaa.bbbbbbbbbbb(datetime.datetime.now())), 1)
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 17
0
 def testB27266946(self):
   unformatted_code = textwrap.dedent("""\
       def _():
         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = (self.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.cccccccccccccccccccccccccccccccccccc)
       """)
   expected_formatted_code = textwrap.dedent("""\
       def _():
         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = (
             self.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.
             cccccccccccccccccccccccccccccccccccc)
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
 def testSimpleDedenting(self):
   unformatted_code = textwrap.dedent("""\
       if True:
           self.assertEqual(result.reason_not_added, "current preflight is still running")
       """)
   expected_formatted_code = textwrap.dedent("""\
       if True:
           self.assertEqual(
               result.reason_not_added, "current preflight is still running"
           )
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 19
0
    def testStableInlinedDictionaryFormatting(self):
        unformatted_code = textwrap.dedent("""\
        def _():
            url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
                value, urllib.urlencode({'action': 'update', 'parameter': value}))
        """)
        expected_formatted_code = textwrap.dedent("""\
        def _():
            url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
                value, urllib.urlencode({
                    'action': 'update',
                    'parameter': value
                }))
        """)

        uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        reformatted_code = reformatter.Reformat(uwlines)
        self.assertCodeEqual(expected_formatted_code, reformatted_code)

        uwlines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
        reformatted_code = reformatter.Reformat(uwlines)
        self.assertCodeEqual(expected_formatted_code, reformatted_code)
Esempio n. 20
0
    def testListSplitting(self):
        unformatted_code = """\
foo([(1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
     (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
     (1,10), (1,11), (1, 10), (1,11), (10,11)])
"""
        expected_code = """\
foo([(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1),
     (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 10), (1, 11), (1, 10),
     (1, 11), (10, 11)])
"""
        uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_code, reformatter.Reformat(uwlines))
 def testDedentIfConditional(self):
   code = textwrap.dedent("""\
       class _():
           def _():
               if True:
                   if not self.frobbies and (
                       self.foobars.counters['db.cheeses'] != 1 or
                       self.foobars.counters['db.marshmellow_skins'] != 1
                   ):
                       pass
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(code)
   self.assertCodeEqual(code, reformatter.Reformat(uwlines))
 def testNoNeedForLineBreaks(self):
     unformatted_code = textwrap.dedent("""\
     def overly_long_function_name(
       just_one_arg, **kwargs):
       pass
     """)
     expected_formatted_code = textwrap.dedent("""\
     def overly_long_function_name(just_one_arg, **kwargs):
         pass
     """)
     llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(llines))
 def testB19547210(self):
     code = textwrap.dedent("""\
     while True:
       if True:
         if True:
           if True:
             if xxxxxxxxxxxx.yyyyyyy(aa).zzzzzzz() not in (
                 xxxxxxxxxxxx.yyyyyyyyyyyyyy.zzzzzzzz,
                 xxxxxxxxxxxx.yyyyyyyyyyyyyy.zzzzzzzz):
               continue
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(code)
     self.assertCodeEqual(code, reformatter.Reformat(uwlines))
    def testB14406499(self):
        unformatted_code = textwrap.dedent("""\
        def foo1(parameter_1, parameter_2, parameter_3, parameter_4, \
parameter_5, parameter_6): pass
        """)
        expected_formatted_code = textwrap.dedent("""\
        def foo1(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5,
                 parameter_6):
          pass
        """)
        uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_formatted_code,
                             reformatter.Reformat(uwlines))
Esempio n. 25
0
    def testAlignClosingBracketWithVisualIndentation(self):
        unformatted_code = textwrap.dedent("""\
        TEST_LIST = ('foo', 'bar',  # first comment
                     'baz'  # second comment
                    )
        """)
        expected_formatted_code = textwrap.dedent("""\
        TEST_LIST = (
            'foo',
            'bar',  # first comment
            'baz'  # second comment
        )
        """)
        llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_formatted_code,
                             reformatter.Reformat(llines))

        unformatted_code = textwrap.dedent("""\
        def f():

          def g():
            while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa' and
                   xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'
                  ):
              pass
        """)  # noqa
        expected_formatted_code = textwrap.dedent("""\
        def f():

            def g():
                while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa'
                       and xxxxxxxxxxxxxxxxxxxx(
                           yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'):
                    pass
        """)  # noqa
        llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_formatted_code,
                             reformatter.Reformat(llines))
Esempio n. 26
0
def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False,
               verify=True):
    """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    remaining arguments: see comment at the top of this module.

  Returns:
    Tuple of (reformatted_source, changed). reformatted_source conforms to the
    desired formatting style. changed is True if the source changed.
  """
    _CheckPythonVersion()
    style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
    if not unformatted_source.endswith('\n'):
        unformatted_source += '\n'
    tree = pytree_utils.ParseCodeToTree(unformatted_source)

    # Run passes on the tree, modifying it in place.
    comment_splicer.SpliceComments(tree)
    continuation_splicer.SpliceContinuations(tree)
    subtype_assigner.AssignSubtypes(tree)
    split_penalty.ComputeSplitPenalties(tree)
    blank_line_calculator.CalculateBlankLines(tree)

    uwlines = pytree_unwrapper.UnwrapPyTree(tree)
    for uwl in uwlines:
        uwl.CalculateFormattingInformation()

    _MarkLinesToFormat(uwlines, lines)
    reformatted_source = reformatter.Reformat(uwlines, verify)

    if unformatted_source == reformatted_source:
        return '' if print_diff else reformatted_source, False

    code_diff = _GetUnifiedDiff(unformatted_source,
                                reformatted_source,
                                filename=filename)

    if print_diff:
        return code_diff, code_diff != ''

    return reformatted_source, True
Esempio n. 27
0
 def testTypedNames(self):
   unformatted_code = textwrap.dedent("""\
       def x(aaaaaaaaaaaaaaa:int,bbbbbbbbbbbbbbbb:str,ccccccccccccccc:dict,eeeeeeeeeeeeee:set={1, 2, 3})->bool:
         pass
       """)
   expected_formatted_code = textwrap.dedent("""\
       def x(aaaaaaaaaaaaaaa: int,
             bbbbbbbbbbbbbbbb: str,
             ccccccccccccccc: dict,
             eeeeeeeeeeeeee: set={1, 2, 3}) -> bool:
           pass
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Esempio n. 28
0
 def testTwoWordComparisonOperators(self):
     unformatted_code = textwrap.dedent("""\
     _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl is not ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj)
     _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl not in {ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj})
     """)
     expected_formatted_code = textwrap.dedent("""\
     _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl
          is not ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj)
     _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl
          not in {ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj})
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))
  def testIfStmtClosingBracket(self):
    unformatted_code = """\
if (isinstance(value  , (StopIteration  , StopAsyncIteration  )) and exc.__cause__ is value_asdfasdfasdfasdfsafsafsafdasfasdfs):
    return False
"""
    expected_formatted_code = """\
if (
    isinstance(value, (StopIteration, StopAsyncIteration)) and
    exc.__cause__ is value_asdfasdfasdfasdfsafsafsafdasfasdfs
):
    return False
"""
    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
  def testDecorators(self):
    unformatted_code = textwrap.dedent("""\
        @bork()

        def foo():
          pass
        """)
    expected_formatted_code = textwrap.dedent("""\
        @bork()
        def foo():
          pass
        """)
    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))