Exemplo n.º 1
0
 def testB20127686(self):
   code = textwrap.dedent("""\
       def f():
         if True:
           return ((m.fffff(
               m.rrr('xxxxxxxxxxxxxxxx',
                     'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'),
               mmmmmmmm)
                    | m.wwwwww(m.rrrr(self.tttttttttt, self.mmmmmmmmmmmmmmmmmmmmm))
                    | m.ggggggg(self.gggggggg, m.sss()), m.fffff('aaaaaaaaaaaaaaaa')
                    | m.wwwwww(m.ddddd(self.tttttttttt, self.mmmmmmmmmmmmmmmmmmmmm))
                    | m.ggggggg(self.gggggggg))
                   | m.jjjj()
                   | m.ppppp(m.VAL[0] / m.VAL[1]))
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(code)
   self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Exemplo n.º 2
0
  def testB18256666(self):
    code = textwrap.dedent("""\
        class Foo(object):

          def Bar(self):
            aaaaa.bbbbbbb(
                ccc='ddddddddddddddd',
                eeee='ffffffffffffffffffffff-%s-%s' % (gggg, int(time.time())),
                hhhhhh={
                    'iiiiiiiiiii': iiiiiiiiiii,
                    'jjjj': jjjj.jjjjj(),
                    'kkkkkkkkkkkk': kkkkkkkkkkkk,
                },
                llllllllll=mmmmmm.nnnnnnnnnnnnnnnn)
        """)
    uwlines = yapf_test_helper.ParseAndUnwrap(code)
    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Exemplo n.º 3
0
 def testSpacesAroundDefaultOrNamedAssign(self):
   try:
     style.SetGlobalStyle(
         style.CreateStyleFromConfig(
             '{based_on_style: pep8, '
             'SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN: True}'))
     unformatted_code = textwrap.dedent("""\
         f(a=5)
         """)
     expected_formatted_code = textwrap.dedent("""\
         f(a = 5)
         """)
     uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))
   finally:
     style.SetGlobalStyle(style.CreatePEP8Style())
Exemplo n.º 4
0
    def testParamListIndentationCollision3(self):
        code = textwrap.dedent("""\
        def func1(
            arg1,
            arg2,
        ) -> None:
            pass


        def func2(
            arg1,
            arg2,
        ):
            pass
        """)
        uwlines = yapf_test_helper.ParseAndUnwrap(code)
        self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Exemplo n.º 5
0
  def testB26034238(self):
    unformatted_code = textwrap.dedent("""\
        class Thing:

          def Function(self):
            thing.Scrape('/aaaaaaaaa/bbbbbbbbbb/ccccc/dddd/eeeeeeeeeeeeee/ffffffffffffff').AndReturn(42)
        """)
    expected_formatted_code = textwrap.dedent("""\
        class Thing:

          def Function(self):
            thing.Scrape(
                '/aaaaaaaaa/bbbbbbbbbb/ccccc/dddd/eeeeeeeeeeeeee/ffffffffffffff'
            ).AndReturn(42)
        """)
    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Exemplo n.º 6
0
 def testKeepTypesIntact(self):
   if sys.version_info[1] < 5:
     return
   unformatted_code = textwrap.dedent("""\
       def _ReduceAbstractContainers(
           self, *args: Optional[automation_converter.PyiCollectionAbc]) -> List[
               automation_converter.PyiCollectionAbc]:
           pass
       """)
   expected_formatted_code = textwrap.dedent("""\
       def _ReduceAbstractContainers(
               self, *args: Optional[automation_converter.PyiCollectionAbc]
       ) -> List[automation_converter.PyiCollectionAbc]:
           pass
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
 def testSubscriptColon(self):
     code = textwrap.dedent("""\
     x[0:42:1]
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(code)
     self._CheckFormatTokenSubtypes(uwlines, [
         [
             ('x', [format_token.Subtype.NONE]),
             ('[', {format_token.Subtype.SUBSCRIPT_BRACKET}),
             ('0', [format_token.Subtype.NONE]),
             (':', {format_token.Subtype.SUBSCRIPT_COLON}),
             ('42', [format_token.Subtype.NONE]),
             (':', {format_token.Subtype.SUBSCRIPT_COLON}),
             ('1', [format_token.Subtype.NONE]),
             (']', {format_token.Subtype.SUBSCRIPT_BRACKET}),
         ],
     ])
 def testFuncCallWithDefaultAssign(self):
     code = textwrap.dedent(r"""
     foo(x, a='hello world')
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(code)
     self._CheckFormatTokenSubtypes(uwlines, [
         [('foo', [format_token.Subtype.NONE]),
          ('(', [format_token.Subtype.NONE]),
          ('x', {format_token.Subtype.NONE,
                 format_token.Subtype.DEFAULT_OR_NAMED_ASSIGN_ARG_LIST}),
          (',', {format_token.Subtype.NONE}),
          ('a', {format_token.Subtype.NONE,
                 format_token.Subtype.DEFAULT_OR_NAMED_ASSIGN_ARG_LIST}),
          ('=', {format_token.Subtype.DEFAULT_OR_NAMED_ASSIGN}),
          ("'hello world'", {format_token.Subtype.NONE}),
          (')', [format_token.Subtype.NONE])],
     ])  # yapf: disable
Exemplo n.º 9
0
 def testDefault(self):
     style.SetGlobalStyle(style.CreatePEP8Style())
     expected_formatted_code = textwrap.dedent("""\
   a = list1[:]
   b = list2[slice_start:]
   c = list3[slice_start:slice_end]
   d = list4[slice_start:slice_end:]
   e = list5[slice_start:slice_end:slice_step]
   a1 = list1[:]
   b1 = list2[1:]
   c1 = list3[1:20]
   d1 = list4[1:20:]
   e1 = list5[1:20:3]
 """)
     llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(llines))
 def testNoSpacesAroundPowerOperator(self):
     try:
         style.SetGlobalStyle(
             style.CreateStyleFromConfig(
                 '{based_on_style: pep8, SPACES_AROUND_POWER_OPERATOR: True}'
             ))
         unformatted_code = textwrap.dedent("""\
       a**b
       """)
         expected_formatted_code = textwrap.dedent("""\
       a ** b
       """)
         uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
         self.assertCodeEqual(expected_formatted_code,
                              reformatter.Reformat(uwlines))
     finally:
         style.SetGlobalStyle(style.CreatePEP8Style())
Exemplo n.º 11
0
 def testContinuationIndentWithAsync(self):
   if sys.version_info[1] < 5:
     return
   unformatted_code = textwrap.dedent("""\
       async def start_websocket():
           async with session.ws_connect(
               r"ws://a_really_long_long_long_long_long_long_url") as ws:
               pass
       """)
   expected_formatted_code = textwrap.dedent("""\
       async def start_websocket():
           async with session.ws_connect(
                   r"ws://a_really_long_long_long_long_long_long_url") as ws:
               pass
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Exemplo n.º 12
0
 def testSplittingSemicolonStatements(self):
   unformatted_code = textwrap.dedent("""\
       def f():
         x = y + 42 ; z = n * 42
         if True: a += 1 ; b += 1; c += 1
       """)
   expected_formatted_code = textwrap.dedent("""\
       def f():
           x = y + 42
           z = n * 42
           if True:
               a += 1
               b += 1
               c += 1
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
    def testSimpleFunctionDefWithSplitting(self):
        code = textwrap.dedent(r"""
      def f(a, b):
        pass
      """)
        uwlines = yapf_test_helper.ParseAndUnwrap(code)
        uwline = unwrapped_line.UnwrappedLine(0, _FilterLine(uwlines[0]))
        uwline.CalculateFormattingInformation()

        # Add: 'f'
        state = format_decision_state.FormatDecisionState(uwline, 0)
        self.assertEqual('f', state.next_token.value)
        self.assertFalse(state.CanSplit())

        # Add: '('
        state.AddTokenToState(True, True)
        self.assertEqual('(', state.next_token.value)
        self.assertFalse(state.CanSplit())

        # Add: 'a'
        state.AddTokenToState(True, True)
        self.assertEqual('a', state.next_token.value)
        self.assertTrue(state.CanSplit())

        # Add: ','
        state.AddTokenToState(True, True)
        self.assertEqual(',', state.next_token.value)
        self.assertFalse(state.CanSplit())

        # Add: 'b'
        state.AddTokenToState(True, True)
        self.assertEqual('b', state.next_token.value)
        self.assertTrue(state.CanSplit())

        # Add: ')'
        state.AddTokenToState(True, True)
        self.assertEqual(')', state.next_token.value)
        self.assertTrue(state.CanSplit())

        # Add: ':'
        state.AddTokenToState(True, True)
        self.assertEqual(':', state.next_token.value)
        self.assertFalse(state.CanSplit())

        clone = state.Clone()
        self.assertEqual(repr(state), repr(clone))
Exemplo n.º 14
0
    def testCodeAfterFunctionsAndClasses(self):
        unformatted_code = textwrap.dedent("""\
        def foo():
          pass
        top_level_code = True
        class moo(object):
          def method_1(self):
            pass
          ivar_a = 42
          ivar_b = 13
          def method_2(self):
            pass
        try:
          raise Error
        except Error as error:
          pass
        """)
        expected_formatted_code = textwrap.dedent("""\
        def foo():
          pass


        top_level_code = True


        class moo(object):

          def method_1(self):
            pass

          ivar_a = 42
          ivar_b = 13

          def method_2(self):
            pass


        try:
          raise Error
        except Error as error:
          pass
        """)
        uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_formatted_code,
                             reformatter.Reformat(uwlines))
Exemplo n.º 15
0
    def testSplitAroundNamedAssigns(self):
        unformatted_code = textwrap.dedent("""\
        class a():

            def a(): return a(
             aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)
        """)
        expected_formatted_code = textwrap.dedent("""\
        class a():

            def a():
                return a(
                    aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                )
        """)
        llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_formatted_code,
                             reformatter.Reformat(llines))
Exemplo n.º 16
0
  def testB17489866(self):
    unformatted_code = textwrap.dedent("""\
        def f():
          if True:
            if True:
              return aaaa.bbbbbbbbb(ccccccc=dddddddddddddd({('eeee', \
'ffffffff'): str(j)}))
        """)
    expected_formatted_code = textwrap.dedent("""\
        def f():
          if True:
            if True:
              return aaaa.bbbbbbbbb(ccccccc=dddddddddddddd({
                  ('eeee', 'ffffffff'): str(j)
              }))
        """)
    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Exemplo n.º 17
0
 def testFunctionCallWithStarExpression(self):
     code = textwrap.dedent("""\
     [a, *b]
     """)
     llines = yapf_test_helper.ParseAndUnwrap(code)
     self._CheckFormatTokenSubtypes(llines, [
         [
             ('[', {subtypes.NONE}),
             ('a', {subtypes.NONE}),
             (',', {subtypes.NONE}),
             ('*', {
                 subtypes.UNARY_OPERATOR,
                 subtypes.VARARGS_STAR,
             }),
             ('b', {subtypes.NONE}),
             (']', {subtypes.NONE}),
         ],
     ])
Exemplo n.º 18
0
 def testNestedCompoundTwoLevel(self):
     code = textwrap.dedent(r"""
    if x:
      x = 1 # c1
      while t:
        # c2
        j = 1
      k = 1
   """)
     llines = yapf_test_helper.ParseAndUnwrap(code)
     self._CheckLogicalLines(llines, [
         (0, ['if', 'x', ':']),
         (1, ['x', '=', '1', '# c1']),
         (1, ['while', 't', ':']),
         (2, ['# c2']),
         (2, ['j', '=', '1']),
         (1, ['k', '=', '1']),
     ])
    def testB18256826(self):
        code = textwrap.dedent("""\
        if True:
          pass
        # A multiline comment.
        # Line two.
        elif False:
          pass

        if True:
          pass
          # A multiline comment.
          # Line two.
        elif False:
          pass
        """)
        uwlines = yapf_test_helper.ParseAndUnwrap(code)
        self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Exemplo n.º 20
0
    def testDedentTestListGexp(self):
        code = textwrap.dedent("""\
        try:
            pass
        except (
            IOError, OSError, LookupError, RuntimeError, OverflowError
        ) as exception:
            pass

        try:
            pass
        except (
            IOError, OSError, LookupError, RuntimeError, OverflowError,
        ) as exception:
            pass
        """)
        uwlines = yapf_test_helper.ParseAndUnwrap(code)
        self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Exemplo n.º 21
0
    def testTwoFuncDefs(self):
        code = textwrap.dedent(r"""
      def foo(x): # c1
        # c2
        return x

      def bar(): # c3
        # c4
        return x
      """)
        llines = yapf_test_helper.ParseAndUnwrap(code)
        self._CheckLogicalLines(llines, [
            (0, ['def', 'foo', '(', 'x', ')', ':', '# c1']),
            (1, ['# c2']),
            (1, ['return', 'x']),
            (0, ['def', 'bar', '(', ')', ':', '# c3']),
            (1, ['# c4']),
            (1, ['return', 'x']),
        ])
Exemplo n.º 22
0
  def testTypeHint(self):
    unformatted_code = textwrap.dedent("""\
        def foo(x: int=42):
            pass


        def foo2(x: 'int' =42):
            pass
        """)
    expected_formatted_code = textwrap.dedent("""\
        def foo(x: int=42):
            pass


        def foo2(x: 'int'=42):
            pass
        """)
    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
    def testContinuationLineShouldBeDistinguished(self):
        unformatted_code = textwrap.dedent("""\
        class Foo(object):

            def bar(self):
                if self.solo_generator_that_is_long is None and len(
                        self.generators + self.next_batch) == 1:
                    pass
        """)
        expected_formatted_code = textwrap.dedent("""\
        class Foo(object):
            def bar(self):
                if self.solo_generator_that_is_long is None and len(
                        self.generators + self.next_batch) == 1:
                    pass
        """)
        uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_formatted_code,
                             reformatter.Reformat(uwlines, verify=False))
Exemplo n.º 24
0
    def testOperatorStyle(self):
        try:
            sympy_style = style.CreatePEP8Style()
            sympy_style['NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS'] = \
              style._StringSetConverter('*,/')
            style.SetGlobalStyle(sympy_style)
            unformatted_code = textwrap.dedent("""\
          a = 1+2 * 3 - 4 / 5
          """)
            expected_formatted_code = textwrap.dedent("""\
          a = 1 + 2*3 - 4/5
          """)

            uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
            self.assertCodeEqual(expected_formatted_code,
                                 reformatter.Reformat(uwlines))
        finally:
            style.SetGlobalStyle(style.CreatePEP8Style())
            style.DEFAULT_STYLE = self.current_style
Exemplo n.º 25
0
 def testParameterListIndentationConflicts(self):
     unformatted_code = textwrap.dedent("""\
     def raw_message(  # pylint: disable=too-many-arguments
                 self, text, user_id=1000, chat_type='private', forward_date=None, forward_from=None):
             pass
     """)
     expected_formatted_code = textwrap.dedent("""\
     def raw_message(  # pylint: disable=too-many-arguments
             self,
             text,
             user_id=1000,
             chat_type='private',
             forward_date=None,
             forward_from=None):
         pass
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))
 def testB20128830(self):
     code = textwrap.dedent("""\
     a = {
         'xxxxxxxxxxxxxxxxxxxx': {
             'aaaa':
                 'mmmmmmm',
             'bbbbb':
                 'mmmmmmmmmmmmmmmmmmmmm',
             'cccccccccc': [
                 'nnnnnnnnnnn',
                 'ooooooooooo',
                 'ppppppppppp',
                 'qqqqqqqqqqq',
             ],
         },
     }
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(code)
     self.assertCodeEqual(code, reformatter.Reformat(uwlines))
Exemplo n.º 27
0
 def testEnabled(self):
     style.SetGlobalStyle(
         style.CreateStyleFromConfig(
             '{spaces_around_subscript_colon: True}'))
     expected_formatted_code = textwrap.dedent("""\
   a = list1[:]
   b = list2[slice_start :]
   c = list3[slice_start : slice_end]
   d = list4[slice_start : slice_end :]
   e = list5[slice_start : slice_end : slice_step]
   a1 = list1[:]
   b1 = list2[1 :]
   c1 = list3[1 : 20]
   d1 = list4[1 : 20 :]
   e1 = list5[1 : 20 : 3]
 """)
     uwlines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))
Exemplo n.º 28
0
 def testB25136820(self):
   unformatted_code = textwrap.dedent("""\
       def foo():
         return collections.OrderedDict({
             # Preceding comment.
             'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa':
             '$bbbbbbbbbbbbbbbbbbbbbbbb',
         })
       """)
   expected_formatted_code = textwrap.dedent("""\
       def foo():
         return collections.OrderedDict({
             # Preceding comment.
             'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa':
                 '$bbbbbbbbbbbbbbbbbbbbbbbb',
         })
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Exemplo n.º 29
0
 def testB25131481(self):
   unformatted_code = textwrap.dedent("""\
       APPARENT_ACTIONS = ('command_type', {
           'materialize': lambda x: some_type_of_function('materialize ' + x.command_def),
           '#': lambda x: x  # do nothing
       })
       """)
   expected_formatted_code = textwrap.dedent("""\
       APPARENT_ACTIONS = (
           'command_type',
           {
               'materialize':
                   lambda x: some_type_of_function('materialize ' + x.command_def),
               '#':
                   lambda x: x  # do nothing
           })
       """)
   uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
   self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Exemplo n.º 30
0
  def testB23944849(self):
    unformatted_code = textwrap.dedent("""\
        class A(object):
          def xxxxxxxxx(self, aaaaaaa, bbbbbbb=ccccccccccc, dddddd=300, eeeeeeeeeeeeee=None, fffffffffffffff=0):
            pass
        """)
    expected_formatted_code = textwrap.dedent("""\
        class A(object):

          def xxxxxxxxx(self,
                        aaaaaaa,
                        bbbbbbb=ccccccccccc,
                        dddddd=300,
                        eeeeeeeeeeeeee=None,
                        fffffffffffffff=0):
            pass
        """)
    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))