1# Copyright 2016 Google Inc. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Basic tests for yapf.reformatter."""
15
16import textwrap
17import unittest
18
19from yapf.yapflib import reformatter
20from yapf.yapflib import style
21
22from yapftests import yapf_test_helper
23
24
25class BasicReformatterTest(yapf_test_helper.YAPFTest):
26
27  @classmethod
28  def setUpClass(cls):
29    style.SetGlobalStyle(style.CreateChromiumStyle())
30
31  def testSplittingAllArgs(self):
32    style.SetGlobalStyle(
33        style.CreateStyleFromConfig(
34            '{split_all_comma_separated_values: true, column_limit: 40}'))
35    unformatted_code = textwrap.dedent("""\
36          responseDict = {"timestamp": timestamp, "someValue":   value, "whatever": 120}
37          """)
38    expected_formatted_code = textwrap.dedent("""\
39          responseDict = {
40              "timestamp": timestamp,
41              "someValue": value,
42              "whatever": 120
43          }
44          """)
45    unformatted_code = textwrap.dedent("""\
46          def foo(long_arg, really_long_arg, really_really_long_arg, cant_keep_all_these_args):
47                pass
48          """)
49    expected_formatted_code = textwrap.dedent("""\
50          def foo(long_arg,
51                  really_long_arg,
52                  really_really_long_arg,
53                  cant_keep_all_these_args):
54            pass
55          """)
56    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
57    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
58    unformatted_code = textwrap.dedent("""\
59          foo_tuple = [long_arg, really_long_arg, really_really_long_arg, cant_keep_all_these_args]
60          """)
61    expected_formatted_code = textwrap.dedent("""\
62          foo_tuple = [
63              long_arg,
64              really_long_arg,
65              really_really_long_arg,
66              cant_keep_all_these_args
67          ]
68          """)
69    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
70    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
71    unformatted_code = textwrap.dedent("""\
72          foo_tuple = [short, arg]
73          """)
74    expected_formatted_code = textwrap.dedent("""\
75          foo_tuple = [short, arg]
76          """)
77    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
78    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
79
80  def testSimpleFunctionsWithTrailingComments(self):
81    unformatted_code = textwrap.dedent("""\
82        def g():  # Trailing comment
83          if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
84              xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
85            pass
86
87        def f(  # Intermediate comment
88        ):
89          if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
90              xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
91            pass
92        """)
93    expected_formatted_code = textwrap.dedent("""\
94        def g():  # Trailing comment
95          if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
96              xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
97            pass
98
99
100        def f(  # Intermediate comment
101        ):
102          if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
103              xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
104            pass
105        """)
106    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
107    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
108
109  def testBlankLinesAtEndOfFile(self):
110    unformatted_code = textwrap.dedent("""\
111        def foobar(): # foo
112         pass
113
114
115
116        """)
117    expected_formatted_code = textwrap.dedent("""\
118        def foobar():  # foo
119          pass
120    """)
121    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
122    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
123
124    unformatted_code = textwrap.dedent("""\
125        x = {  'a':37,'b':42,
126
127        'c':927}
128
129        """)
130    expected_formatted_code = textwrap.dedent("""\
131        x = {'a': 37, 'b': 42, 'c': 927}
132    """)
133    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
134    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
135
136  def testMultipleUgliness(self):
137    unformatted_code = textwrap.dedent("""\
138        x = {  'a':37,'b':42,
139
140        'c':927}
141
142        y = 'hello ''world'
143        z = 'hello '+'world'
144        a = 'hello {}'.format('world')
145        class foo  (     object  ):
146          def f    (self   ):
147            return       37*-+2
148          def g(self, x,y=42):
149              return y
150        def f  (   a ) :
151          return      37+-+a[42-x :  y**3]
152        """)
153    expected_formatted_code = textwrap.dedent("""\
154        x = {'a': 37, 'b': 42, 'c': 927}
155
156        y = 'hello ' 'world'
157        z = 'hello ' + 'world'
158        a = 'hello {}'.format('world')
159
160
161        class foo(object):
162
163          def f(self):
164            return 37 * -+2
165
166          def g(self, x, y=42):
167            return y
168
169
170        def f(a):
171          return 37 + -+a[42 - x:y**3]
172        """)
173    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
174    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
175
176  def testComments(self):
177    unformatted_code = textwrap.dedent("""\
178        class Foo(object):
179          pass
180
181        # Attached comment
182        class Bar(object):
183          pass
184
185        global_assignment = 42
186
187        # Comment attached to class with decorator.
188        # Comment attached to class with decorator.
189        @noop
190        @noop
191        class Baz(object):
192          pass
193
194        # Intermediate comment
195
196        class Qux(object):
197          pass
198        """)
199    expected_formatted_code = textwrap.dedent("""\
200        class Foo(object):
201          pass
202
203
204        # Attached comment
205        class Bar(object):
206          pass
207
208
209        global_assignment = 42
210
211
212        # Comment attached to class with decorator.
213        # Comment attached to class with decorator.
214        @noop
215        @noop
216        class Baz(object):
217          pass
218
219
220        # Intermediate comment
221
222
223        class Qux(object):
224          pass
225        """)
226    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
227    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
228
229  def testSingleComment(self):
230    code = textwrap.dedent("""\
231        # Thing 1
232        """)
233    uwlines = yapf_test_helper.ParseAndUnwrap(code)
234    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
235
236  def testCommentsWithTrailingSpaces(self):
237    unformatted_code = textwrap.dedent("""\
238        # Thing 1
239        # Thing 2
240        """)
241    expected_formatted_code = textwrap.dedent("""\
242        # Thing 1
243        # Thing 2
244        """)
245    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
246    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
247
248  def testCommentsInDataLiteral(self):
249    code = textwrap.dedent("""\
250        def f():
251          return collections.OrderedDict({
252              # First comment.
253              'fnord': 37,
254
255              # Second comment.
256              # Continuation of second comment.
257              'bork': 42,
258
259              # Ending comment.
260          })
261        """)
262    uwlines = yapf_test_helper.ParseAndUnwrap(code)
263    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
264
265  def testEndingWhitespaceAfterSimpleStatement(self):
266    code = textwrap.dedent("""\
267        import foo as bar
268        # Thing 1
269        # Thing 2
270        """)
271    uwlines = yapf_test_helper.ParseAndUnwrap(code)
272    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
273
274  def testDocstrings(self):
275    unformatted_code = textwrap.dedent('''\
276        u"""Module-level docstring."""
277        import os
278        class Foo(object):
279
280          """Class-level docstring."""
281          # A comment for qux.
282          def qux(self):
283
284
285            """Function-level docstring.
286
287            A multiline function docstring.
288            """
289            print('hello {}'.format('world'))
290            return 42
291        ''')
292    expected_formatted_code = textwrap.dedent('''\
293        u"""Module-level docstring."""
294        import os
295
296
297        class Foo(object):
298          """Class-level docstring."""
299
300          # A comment for qux.
301          def qux(self):
302            """Function-level docstring.
303
304            A multiline function docstring.
305            """
306            print('hello {}'.format('world'))
307            return 42
308        ''')
309    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
310    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
311
312  def testDocstringAndMultilineComment(self):
313    unformatted_code = textwrap.dedent('''\
314        """Hello world"""
315        # A multiline
316        # comment
317        class bar(object):
318          """class docstring"""
319          # class multiline
320          # comment
321          def foo(self):
322            """Another docstring."""
323            # Another multiline
324            # comment
325            pass
326        ''')
327    expected_formatted_code = textwrap.dedent('''\
328        """Hello world"""
329
330
331        # A multiline
332        # comment
333        class bar(object):
334          """class docstring"""
335
336          # class multiline
337          # comment
338          def foo(self):
339            """Another docstring."""
340            # Another multiline
341            # comment
342            pass
343        ''')
344    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
345    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
346
347  def testMultilineDocstringAndMultilineComment(self):
348    unformatted_code = textwrap.dedent('''\
349        """Hello world
350
351        RIP Dennis Richie.
352        """
353        # A multiline
354        # comment
355        class bar(object):
356          """class docstring
357
358          A classy class.
359          """
360          # class multiline
361          # comment
362          def foo(self):
363            """Another docstring.
364
365            A functional function.
366            """
367            # Another multiline
368            # comment
369            pass
370        ''')
371    expected_formatted_code = textwrap.dedent('''\
372        """Hello world
373
374        RIP Dennis Richie.
375        """
376
377
378        # A multiline
379        # comment
380        class bar(object):
381          """class docstring
382
383          A classy class.
384          """
385
386          # class multiline
387          # comment
388          def foo(self):
389            """Another docstring.
390
391            A functional function.
392            """
393            # Another multiline
394            # comment
395            pass
396        ''')
397    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
398    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
399
400  def testTupleCommaBeforeLastParen(self):
401    unformatted_code = textwrap.dedent("""\
402        a = ( 1, )
403        """)
404    expected_formatted_code = textwrap.dedent("""\
405        a = (1,)
406        """)
407    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
408    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
409
410  def testNoBreakOutsideOfBracket(self):
411    # FIXME(morbo): How this is formatted is not correct. But it's syntactically
412    # correct.
413    unformatted_code = textwrap.dedent("""\
414        def f():
415          assert port >= minimum, \
416'Unexpected port %d when minimum was %d.' % (port, minimum)
417        """)
418    expected_formatted_code = textwrap.dedent("""\
419        def f():
420          assert port >= minimum, 'Unexpected port %d when minimum was %d.' % (port,
421                                                                               minimum)
422        """)
423    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
424    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
425
426  def testBlankLinesBeforeDecorators(self):
427    unformatted_code = textwrap.dedent("""\
428        @foo()
429        class A(object):
430          @bar()
431          @baz()
432          def x(self):
433            pass
434        """)
435    expected_formatted_code = textwrap.dedent("""\
436        @foo()
437        class A(object):
438
439          @bar()
440          @baz()
441          def x(self):
442            pass
443        """)
444    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
445    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
446
447  def testCommentBetweenDecorators(self):
448    unformatted_code = textwrap.dedent("""\
449        @foo()
450        # frob
451        @bar
452        def x  (self):
453            pass
454        """)
455    expected_formatted_code = textwrap.dedent("""\
456        @foo()
457        # frob
458        @bar
459        def x(self):
460          pass
461        """)
462    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
463    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
464
465  def testListComprehension(self):
466    unformatted_code = textwrap.dedent("""\
467        def given(y):
468            [k for k in ()
469              if k in y]
470        """)
471    expected_formatted_code = textwrap.dedent("""\
472        def given(y):
473          [k for k in () if k in y]
474        """)
475    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
476    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
477
478  def testListComprehensionPreferOneLine(self):
479    unformatted_code = textwrap.dedent("""\
480        def given(y):
481            long_variable_name = [
482                long_var_name + 1
483                for long_var_name in ()
484                if long_var_name == 2]
485        """)
486    expected_formatted_code = textwrap.dedent("""\
487        def given(y):
488          long_variable_name = [
489              long_var_name + 1 for long_var_name in () if long_var_name == 2
490          ]
491        """)
492    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
493    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
494
495  def testListComprehensionPreferOneLineOverArithmeticSplit(self):
496    unformatted_code = textwrap.dedent("""\
497        def given(used_identifiers):
498          return (sum(len(identifier)
499                      for identifier in used_identifiers) / len(used_identifiers))
500        """)
501    expected_formatted_code = textwrap.dedent("""\
502        def given(used_identifiers):
503          return (sum(len(identifier) for identifier in used_identifiers) /
504                  len(used_identifiers))
505        """)
506    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
507    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
508
509  def testListComprehensionPreferThreeLinesForLineWrap(self):
510    unformatted_code = textwrap.dedent("""\
511        def given(y):
512            long_variable_name = [
513                long_var_name + 1
514                for long_var_name, number_two in ()
515                if long_var_name == 2 and number_two == 3]
516        """)
517    expected_formatted_code = textwrap.dedent("""\
518        def given(y):
519          long_variable_name = [
520              long_var_name + 1
521              for long_var_name, number_two in ()
522              if long_var_name == 2 and number_two == 3
523          ]
524        """)
525    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
526    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
527
528  def testListComprehensionPreferNoBreakForTrivialExpression(self):
529    unformatted_code = textwrap.dedent("""\
530        def given(y):
531            long_variable_name = [
532                long_var_name
533                for long_var_name, number_two in ()
534                if long_var_name == 2 and number_two == 3]
535        """)
536    expected_formatted_code = textwrap.dedent("""\
537        def given(y):
538          long_variable_name = [
539              long_var_name for long_var_name, number_two in ()
540              if long_var_name == 2 and number_two == 3
541          ]
542        """)
543    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
544    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
545
546  def testOpeningAndClosingBrackets(self):
547    unformatted_code = """\
548foo( (1, ) )
549foo( ( 1, 2, 3  ) )
550foo( ( 1, 2, 3, ) )
551"""
552    expected_formatted_code = """\
553foo((1,))
554foo((1, 2, 3))
555foo((
556    1,
557    2,
558    3,
559))
560"""
561    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
562    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
563
564  def testSingleLineFunctions(self):
565    unformatted_code = textwrap.dedent("""\
566        def foo():  return 42
567        """)
568    expected_formatted_code = textwrap.dedent("""\
569        def foo():
570          return 42
571        """)
572    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
573    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
574
575  def testNoQueueSeletionInMiddleOfLine(self):
576    # If the queue isn't properly constructed, then a token in the middle of the
577    # line may be selected as the one with least penalty. The tokens after that
578    # one are then splatted at the end of the line with no formatting.
579    unformatted_code = """\
580find_symbol(node.type) + "< " + " ".join(find_pattern(n) for n in node.child) + " >"
581"""
582    expected_formatted_code = """\
583find_symbol(node.type) + "< " + " ".join(
584    find_pattern(n) for n in node.child) + " >"
585"""
586    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
587    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
588
589  def testNoSpacesBetweenSubscriptsAndCalls(self):
590    unformatted_code = textwrap.dedent("""\
591        aaaaaaaaaa = bbbbbbbb.ccccccccc() [42] (a, 2)
592        """)
593    expected_formatted_code = textwrap.dedent("""\
594        aaaaaaaaaa = bbbbbbbb.ccccccccc()[42](a, 2)
595        """)
596    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
597    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
598
599  def testNoSpacesBetweenOpeningBracketAndStartingOperator(self):
600    # Unary operator.
601    unformatted_code = textwrap.dedent("""\
602        aaaaaaaaaa = bbbbbbbb.ccccccccc[ -1 ]( -42 )
603        """)
604    expected_formatted_code = textwrap.dedent("""\
605        aaaaaaaaaa = bbbbbbbb.ccccccccc[-1](-42)
606        """)
607    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
608    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
609
610    # Varargs and kwargs.
611    unformatted_code = textwrap.dedent("""\
612        aaaaaaaaaa = bbbbbbbb.ccccccccc( *varargs )
613        aaaaaaaaaa = bbbbbbbb.ccccccccc( **kwargs )
614        """)
615    expected_formatted_code = textwrap.dedent("""\
616        aaaaaaaaaa = bbbbbbbb.ccccccccc(*varargs)
617        aaaaaaaaaa = bbbbbbbb.ccccccccc(**kwargs)
618        """)
619    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
620    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
621
622  def testMultilineCommentReformatted(self):
623    unformatted_code = textwrap.dedent("""\
624        if True:
625            # This is a multiline
626            # comment.
627            pass
628        """)
629    expected_formatted_code = textwrap.dedent("""\
630        if True:
631          # This is a multiline
632          # comment.
633          pass
634        """)
635    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
636    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
637
638  def testDictionaryMakerFormatting(self):
639    unformatted_code = textwrap.dedent("""\
640        _PYTHON_STATEMENTS = frozenset({
641            lambda x, y: 'simple_stmt': 'small_stmt', 'expr_stmt': 'print_stmt', 'del_stmt':
642            'pass_stmt', lambda: 'break_stmt': 'continue_stmt', 'return_stmt': 'raise_stmt',
643            'yield_stmt': 'import_stmt', lambda: 'global_stmt': 'exec_stmt', 'assert_stmt':
644            'if_stmt', 'while_stmt': 'for_stmt',
645        })
646        """)
647    expected_formatted_code = textwrap.dedent("""\
648        _PYTHON_STATEMENTS = frozenset({
649            lambda x, y: 'simple_stmt': 'small_stmt',
650            'expr_stmt': 'print_stmt',
651            'del_stmt': 'pass_stmt',
652            lambda: 'break_stmt': 'continue_stmt',
653            'return_stmt': 'raise_stmt',
654            'yield_stmt': 'import_stmt',
655            lambda: 'global_stmt': 'exec_stmt',
656            'assert_stmt': 'if_stmt',
657            'while_stmt': 'for_stmt',
658        })
659        """)
660    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
661    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
662
663  def testSimpleMultilineCode(self):
664    unformatted_code = textwrap.dedent("""\
665        if True:
666          aaaaaaaaaaaaaa.bbbbbbbbbbbbbb.ccccccc(zzzzzzzzzzzz, \
667xxxxxxxxxxx, yyyyyyyyyyyy, vvvvvvvvv)
668          aaaaaaaaaaaaaa.bbbbbbbbbbbbbb.ccccccc(zzzzzzzzzzzz, \
669xxxxxxxxxxx, yyyyyyyyyyyy, vvvvvvvvv)
670        """)
671    expected_formatted_code = textwrap.dedent("""\
672        if True:
673          aaaaaaaaaaaaaa.bbbbbbbbbbbbbb.ccccccc(zzzzzzzzzzzz, xxxxxxxxxxx, yyyyyyyyyyyy,
674                                                vvvvvvvvv)
675          aaaaaaaaaaaaaa.bbbbbbbbbbbbbb.ccccccc(zzzzzzzzzzzz, xxxxxxxxxxx, yyyyyyyyyyyy,
676                                                vvvvvvvvv)
677        """)
678    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
679    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
680
681  def testMultilineComment(self):
682    code = textwrap.dedent("""\
683        if Foo:
684          # Hello world
685          # Yo man.
686          # Yo man.
687          # Yo man.
688          # Yo man.
689          a = 42
690        """)
691    uwlines = yapf_test_helper.ParseAndUnwrap(code)
692    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
693
694  def testMultilineString(self):
695    code = textwrap.dedent("""\
696        code = textwrap.dedent('''\
697            if Foo:
698              # Hello world
699              # Yo man.
700              # Yo man.
701              # Yo man.
702              # Yo man.
703              a = 42
704            ''')
705        """)
706    uwlines = yapf_test_helper.ParseAndUnwrap(code)
707    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
708
709    unformatted_code = textwrap.dedent('''\
710        def f():
711            email_text += """<html>This is a really long docstring that goes over the column limit and is multi-line.<br><br>
712        <b>Czar: </b>"""+despot["Nicholas"]+"""<br>
713        <b>Minion: </b>"""+serf["Dmitri"]+"""<br>
714        <b>Residence: </b>"""+palace["Winter"]+"""<br>
715        </body>
716        </html>"""
717        ''')
718    expected_formatted_code = textwrap.dedent('''\
719        def f():
720          email_text += """<html>This is a really long docstring that goes over the column limit and is multi-line.<br><br>
721        <b>Czar: </b>""" + despot["Nicholas"] + """<br>
722        <b>Minion: </b>""" + serf["Dmitri"] + """<br>
723        <b>Residence: </b>""" + palace["Winter"] + """<br>
724        </body>
725        </html>"""
726        ''')
727    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
728    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
729
730  def testSimpleMultilineWithComments(self):
731    code = textwrap.dedent("""\
732        if (  # This is the first comment
733            a and  # This is the second comment
734            # This is the third comment
735            b):  # A trailing comment
736          # Whoa! A normal comment!!
737          pass  # Another trailing comment
738        """)
739    uwlines = yapf_test_helper.ParseAndUnwrap(code)
740    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
741
742  def testMatchingParenSplittingMatching(self):
743    unformatted_code = textwrap.dedent("""\
744        def f():
745          raise RuntimeError('unable to find insertion point for target node',
746                             (target,))
747        """)
748    expected_formatted_code = textwrap.dedent("""\
749        def f():
750          raise RuntimeError('unable to find insertion point for target node',
751                             (target,))
752        """)
753    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
754    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
755
756  def testContinuationIndent(self):
757    unformatted_code = textwrap.dedent('''\
758        class F:
759          def _ProcessArgLists(self, node):
760            """Common method for processing argument lists."""
761            for child in node.children:
762              if isinstance(child, pytree.Leaf):
763                self._SetTokenSubtype(
764                    child, subtype=_ARGLIST_TOKEN_TO_SUBTYPE.get(
765                        child.value, format_token.Subtype.NONE))
766        ''')
767    expected_formatted_code = textwrap.dedent('''\
768        class F:
769
770          def _ProcessArgLists(self, node):
771            """Common method for processing argument lists."""
772            for child in node.children:
773              if isinstance(child, pytree.Leaf):
774                self._SetTokenSubtype(
775                    child,
776                    subtype=_ARGLIST_TOKEN_TO_SUBTYPE.get(child.value,
777                                                          format_token.Subtype.NONE))
778        ''')
779    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
780    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
781
782  def testTrailingCommaAndBracket(self):
783    unformatted_code = textwrap.dedent('''\
784        a = { 42, }
785        b = ( 42, )
786        c = [ 42, ]
787        ''')
788    expected_formatted_code = textwrap.dedent('''\
789        a = {
790            42,
791        }
792        b = (42,)
793        c = [
794            42,
795        ]
796        ''')
797    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
798    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
799
800  def testI18n(self):
801    code = textwrap.dedent("""\
802        N_('Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.')  # A comment is here.
803        """)
804    uwlines = yapf_test_helper.ParseAndUnwrap(code)
805    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
806
807    code = textwrap.dedent("""\
808        foo('Fake function call')  #. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.
809        """)
810    uwlines = yapf_test_helper.ParseAndUnwrap(code)
811    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
812
813  def testI18nCommentsInDataLiteral(self):
814    code = textwrap.dedent("""\
815        def f():
816          return collections.OrderedDict({
817              #. First i18n comment.
818              'bork': 'foo',
819
820              #. Second i18n comment.
821              'snork': 'bar#.*=\\\\0',
822          })
823        """)
824    uwlines = yapf_test_helper.ParseAndUnwrap(code)
825    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
826
827  def testClosingBracketIndent(self):
828    code = textwrap.dedent('''\
829        def f():
830
831          def g():
832            while (xxxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa' and
833                   xxxxxxxxxxxxxxxxxxxxx(
834                       yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'):
835              pass
836        ''')
837    uwlines = yapf_test_helper.ParseAndUnwrap(code)
838    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
839
840  def testClosingBracketsInlinedInCall(self):
841    unformatted_code = textwrap.dedent("""\
842        class Foo(object):
843
844          def bar(self):
845            self.aaaaaaaa = xxxxxxxxxxxxxxxxxxx.yyyyyyyyyyyyy(
846                self.cccccc.ddddddddd.eeeeeeee,
847                options={
848                    "forkforkfork": 1,
849                    "borkborkbork": 2,
850                    "corkcorkcork": 3,
851                    "horkhorkhork": 4,
852                    "porkporkpork": 5,
853                    })
854        """)
855    expected_formatted_code = textwrap.dedent("""\
856        class Foo(object):
857
858          def bar(self):
859            self.aaaaaaaa = xxxxxxxxxxxxxxxxxxx.yyyyyyyyyyyyy(
860                self.cccccc.ddddddddd.eeeeeeee,
861                options={
862                    "forkforkfork": 1,
863                    "borkborkbork": 2,
864                    "corkcorkcork": 3,
865                    "horkhorkhork": 4,
866                    "porkporkpork": 5,
867                })
868        """)
869    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
870    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
871
872  def testLineWrapInForExpression(self):
873    code = textwrap.dedent("""\
874        class A:
875
876          def x(self, node, name, n=1):
877            for i, child in enumerate(
878                itertools.ifilter(lambda c: pytree_utils.NodeName(c) == name,
879                                  node.pre_order())):
880              pass
881        """)
882    uwlines = yapf_test_helper.ParseAndUnwrap(code)
883    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
884
885  def testFunctionCallContinuationLine(self):
886    code = """\
887class foo:
888
889  def bar(self, node, name, n=1):
890    if True:
891      if True:
892        return [(aaaaaaaaaa,
893                 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(
894                     cccc, ddddddddddddddddddddddddddddddddddddd))]
895"""
896    uwlines = yapf_test_helper.ParseAndUnwrap(code)
897    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
898
899  def testI18nNonFormatting(self):
900    code = textwrap.dedent("""\
901        class F(object):
902
903          def __init__(self, fieldname,
904                       #. Error message indicating an invalid e-mail address.
905                       message=N_('Please check your email address.'), **kwargs):
906            pass
907        """)
908    uwlines = yapf_test_helper.ParseAndUnwrap(code)
909    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
910
911  def testNoSpaceBetweenUnaryOpAndOpeningParen(self):
912    code = textwrap.dedent("""\
913        if ~(a or b):
914          pass
915        """)
916    uwlines = yapf_test_helper.ParseAndUnwrap(code)
917    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
918
919  def testCommentBeforeFuncDef(self):
920    code = textwrap.dedent("""\
921        class Foo(object):
922
923          a = 42
924
925          # This is a comment.
926          def __init__(self,
927                       xxxxxxx,
928                       yyyyy=0,
929                       zzzzzzz=None,
930                       aaaaaaaaaaaaaaaaaa=False,
931                       bbbbbbbbbbbbbbb=False):
932            pass
933        """)
934    uwlines = yapf_test_helper.ParseAndUnwrap(code)
935    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
936
937  def testExcessLineCountWithDefaultKeywords(self):
938    unformatted_code = textwrap.dedent("""\
939        class Fnord(object):
940          def Moo(self):
941            aaaaaaaaaaaaaaaa = self._bbbbbbbbbbbbbbbbbbbbbbb(
942                ccccccccccccc=ccccccccccccc, ddddddd=ddddddd, eeee=eeee,
943                fffff=fffff, ggggggg=ggggggg, hhhhhhhhhhhhh=hhhhhhhhhhhhh,
944                iiiiiii=iiiiiiiiiiiiii)
945        """)
946    expected_formatted_code = textwrap.dedent("""\
947        class Fnord(object):
948
949          def Moo(self):
950            aaaaaaaaaaaaaaaa = self._bbbbbbbbbbbbbbbbbbbbbbb(
951                ccccccccccccc=ccccccccccccc,
952                ddddddd=ddddddd,
953                eeee=eeee,
954                fffff=fffff,
955                ggggggg=ggggggg,
956                hhhhhhhhhhhhh=hhhhhhhhhhhhh,
957                iiiiiii=iiiiiiiiiiiiii)
958        """)
959    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
960    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
961
962  def testSpaceAfterNotOperator(self):
963    code = textwrap.dedent("""\
964        if not (this and that):
965          pass
966        """)
967    uwlines = yapf_test_helper.ParseAndUnwrap(code)
968    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
969
970  def testNoPenaltySplitting(self):
971    code = textwrap.dedent("""\
972        def f():
973          if True:
974            if True:
975              python_files.extend(
976                  os.path.join(filename, f)
977                  for f in os.listdir(filename)
978                  if IsPythonFile(os.path.join(filename, f)))
979        """)
980    uwlines = yapf_test_helper.ParseAndUnwrap(code)
981    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
982
983  def testExpressionPenalties(self):
984    code = textwrap.dedent("""\
985      def f():
986        if ((left.value == '(' and right.value == ')') or
987            (left.value == '[' and right.value == ']') or
988            (left.value == '{' and right.value == '}')):
989          return False
990        """)
991    uwlines = yapf_test_helper.ParseAndUnwrap(code)
992    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
993
994  def testLineDepthOfSingleLineStatement(self):
995    unformatted_code = textwrap.dedent("""\
996        while True: continue
997        for x in range(3): continue
998        try: a = 42
999        except: b = 42
1000        with open(a) as fd: a = fd.read()
1001        """)
1002    expected_formatted_code = textwrap.dedent("""\
1003        while True:
1004          continue
1005        for x in range(3):
1006          continue
1007        try:
1008          a = 42
1009        except:
1010          b = 42
1011        with open(a) as fd:
1012          a = fd.read()
1013        """)
1014    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1015    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1016
1017  def testSplitListWithTerminatingComma(self):
1018    unformatted_code = textwrap.dedent("""\
1019        FOO = ['bar', 'baz', 'mux', 'qux', 'quux', 'quuux', 'quuuux',
1020          'quuuuux', 'quuuuuux', 'quuuuuuux', lambda a, b: 37,]
1021        """)
1022    expected_formatted_code = textwrap.dedent("""\
1023        FOO = [
1024            'bar',
1025            'baz',
1026            'mux',
1027            'qux',
1028            'quux',
1029            'quuux',
1030            'quuuux',
1031            'quuuuux',
1032            'quuuuuux',
1033            'quuuuuuux',
1034            lambda a, b: 37,
1035        ]
1036        """)
1037    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1038    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1039
1040  def testSplitListWithInterspersedComments(self):
1041    code = textwrap.dedent("""\
1042        FOO = [
1043            'bar',  # bar
1044            'baz',  # baz
1045            'mux',  # mux
1046            'qux',  # qux
1047            'quux',  # quux
1048            'quuux',  # quuux
1049            'quuuux',  # quuuux
1050            'quuuuux',  # quuuuux
1051            'quuuuuux',  # quuuuuux
1052            'quuuuuuux',  # quuuuuuux
1053            lambda a, b: 37  # lambda
1054        ]
1055        """)
1056    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1057    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1058
1059  def testRelativeImportStatements(self):
1060    code = textwrap.dedent("""\
1061        from ... import bork
1062        """)
1063    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1064    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1065
1066  def testSingleLineList(self):
1067    # A list on a single line should prefer to remain contiguous.
1068    unformatted_code = textwrap.dedent("""\
1069        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = aaaaaaaaaaa(
1070            ("...", "."), "..",
1071            ".............................................."
1072        )
1073        """)
1074    expected_formatted_code = textwrap.dedent("""\
1075        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = aaaaaaaaaaa(
1076            ("...", "."), "..", "..............................................")
1077        """)
1078    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1079    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1080
1081  def testBlankLinesBeforeFunctionsNotInColumnZero(self):
1082    unformatted_code = textwrap.dedent("""\
1083        import signal
1084
1085
1086        try:
1087          signal.SIGALRM
1088          # ..................................................................
1089          # ...............................................................
1090
1091
1092          def timeout(seconds=1):
1093            pass
1094        except:
1095          pass
1096        """)
1097    expected_formatted_code = textwrap.dedent("""\
1098        import signal
1099
1100        try:
1101          signal.SIGALRM
1102
1103          # ..................................................................
1104          # ...............................................................
1105
1106
1107          def timeout(seconds=1):
1108            pass
1109        except:
1110          pass
1111        """)
1112    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1113    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1114
1115  def testNoKeywordArgumentBreakage(self):
1116    code = textwrap.dedent("""\
1117        class A(object):
1118
1119          def b(self):
1120            if self.aaaaaaaaaaaaaaaaaaaa not in self.bbbbbbbbbb(
1121                cccccccccccccccccccc=True):
1122              pass
1123        """)
1124    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1125    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1126
1127  def testTrailerOnSingleLine(self):
1128    code = """\
1129urlpatterns = patterns('', url(r'^$', 'homepage_view'),
1130                       url(r'^/login/$', 'login_view'),
1131                       url(r'^/login/$', 'logout_view'),
1132                       url(r'^/user/(?P<username>\\w+)/$', 'profile_view'))
1133"""
1134    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1135    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1136
1137  def testIfConditionalParens(self):
1138    code = textwrap.dedent("""\
1139        class Foo:
1140
1141          def bar():
1142            if True:
1143              if (child.type == grammar_token.NAME and
1144                  child.value in substatement_names):
1145                pass
1146        """)
1147    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1148    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1149
1150  def testContinuationMarkers(self):
1151    code = textwrap.dedent("""\
1152        text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. "\\
1153               "Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur "\\
1154               "ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis "\\
1155               "sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. "\\
1156               "Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet"
1157        """)
1158    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1159    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1160
1161    code = textwrap.dedent("""\
1162        from __future__ import nested_scopes, generators, division, absolute_import, with_statement, \\
1163            print_function, unicode_literals
1164        """)
1165    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1166    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1167
1168    code = textwrap.dedent("""\
1169        if aaaaaaaaa == 42 and bbbbbbbbbbbbbb == 42 and \\
1170           cccccccc == 42:
1171          pass
1172        """)
1173    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1174    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1175
1176  def testCommentsWithContinuationMarkers(self):
1177    code = textwrap.dedent("""\
1178        def fn(arg):
1179          v = fn2(key1=True,
1180                  #c1
1181                  key2=arg)\\
1182                        .fn3()
1183        """)
1184    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1185    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1186
1187  def testMultipleContinuationMarkers(self):
1188    code = textwrap.dedent("""\
1189        xyz = \\
1190            \\
1191            some_thing()
1192        """)
1193    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1194    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1195
1196  def testContinuationMarkerAfterStringWithContinuation(self):
1197    code = """\
1198s = 'foo \\
1199    bar' \\
1200    .format()
1201"""
1202    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1203    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1204
1205  def testEmptyContainers(self):
1206    code = textwrap.dedent("""\
1207        flags.DEFINE_list(
1208            'output_dirs', [],
1209            'Lorem ipsum dolor sit amet, consetetur adipiscing elit. Donec a diam lectus. '
1210            'Sed sit amet ipsum mauris. Maecenas congue.')
1211        """)
1212    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1213    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1214
1215  def testSplitStringsIfSurroundedByParens(self):
1216    unformatted_code = textwrap.dedent("""\
1217        a = foo.bar({'xxxxxxxxxxxxxxxxxxxxxxx' 'yyyyyyyyyyyyyyyyyyyyyyyyyy': baz[42]} + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' 'bbbbbbbbbbbbbbbbbbbbbbbbbb' 'cccccccccccccccccccccccccccccccc' 'ddddddddddddddddddddddddddddd')
1218        """)
1219    expected_formatted_code = textwrap.dedent("""\
1220        a = foo.bar({
1221            'xxxxxxxxxxxxxxxxxxxxxxx'
1222            'yyyyyyyyyyyyyyyyyyyyyyyyyy': baz[42]
1223        } + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
1224                    'bbbbbbbbbbbbbbbbbbbbbbbbbb'
1225                    'cccccccccccccccccccccccccccccccc'
1226                    'ddddddddddddddddddddddddddddd')
1227        """)
1228    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1229    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1230
1231    code = textwrap.dedent("""\
1232        a = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
1233'bbbbbbbbbbbbbbbbbbbbbbbbbb' 'cccccccccccccccccccccccccccccccc' \
1234'ddddddddddddddddddddddddddddd'
1235        """)
1236    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1237    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1238
1239  def testMultilineShebang(self):
1240    code = textwrap.dedent("""\
1241        #!/bin/sh
1242        if "true" : '''\'
1243        then
1244
1245        export FOO=123
1246        exec /usr/bin/env python "$0" "$@"
1247
1248        exit 127
1249        fi
1250        '''
1251
1252        import os
1253
1254        assert os.environ['FOO'] == '123'
1255        """)
1256    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1257    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1258
1259  def testNoSplittingAroundTermOperators(self):
1260    code = textwrap.dedent("""\
1261        a_very_long_function_call_yada_yada_etc_etc_etc(long_arg1,
1262                                                        long_arg2 / long_arg3)
1263        """)
1264    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1265    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1266
1267  def testNoSplittingWithinSubscriptList(self):
1268    code = textwrap.dedent("""\
1269        somequitelongvariablename.somemember[(a, b)] = {
1270            'somelongkey': 1,
1271            'someotherlongkey': 2
1272        }
1273        """)
1274    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1275    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1276
1277  def testExcessCharacters(self):
1278    code = textwrap.dedent("""\
1279        class foo:
1280
1281          def bar(self):
1282            self.write(s=[
1283                '%s%s %s' % ('many of really', 'long strings', '+ just makes up 81')
1284            ])
1285        """)
1286    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1287    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1288
1289    unformatted_code = textwrap.dedent("""\
1290        def _():
1291          if True:
1292            if True:
1293              if contract == allow_contract and attr_dict.get(if_attribute) == has_value:
1294                return True
1295        """)
1296    expected_code = textwrap.dedent("""\
1297        def _():
1298          if True:
1299            if True:
1300              if contract == allow_contract and attr_dict.get(
1301                  if_attribute) == has_value:
1302                return True
1303        """)
1304    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1305    self.assertEqual(expected_code, reformatter.Reformat(uwlines))
1306
1307  def testDictSetGenerator(self):
1308    code = textwrap.dedent("""\
1309        foo = {
1310            variable: 'hello world. How are you today?'
1311            for variable in fnord
1312            if variable != 37
1313        }
1314        """)
1315    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1316    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1317
1318  def testUnaryOpInDictionaryValue(self):
1319    code = textwrap.dedent("""\
1320        beta = "123"
1321
1322        test = {'alpha': beta[-1]}
1323
1324        print(beta[-1])
1325        """)
1326    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1327    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1328
1329  def testUnaryNotOperator(self):
1330    code = textwrap.dedent("""\
1331        if True:
1332          if True:
1333            if True:
1334              if True:
1335                remote_checksum = self.get_checksum(conn, tmp, dest, inject,
1336                                                    not directory_prepended, source)
1337        """)
1338    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1339    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1340
1341  def testRelaxArraySubscriptAffinity(self):
1342    code = textwrap.dedent("""\
1343        class A(object):
1344
1345          def f(self, aaaaaaaaa, bbbbbbbbbbbbb, row):
1346            if True:
1347              if True:
1348                if True:
1349                  if True:
1350                    if row[4] is None or row[5] is None:
1351                      bbbbbbbbbbbbb['..............'] = row[
1352                          5] if row[5] is not None else 5
1353        """)
1354    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1355    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1356
1357  def testFunctionCallInDict(self):
1358    code = "a = {'a': b(c=d, **e)}\n"
1359    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1360    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1361
1362  def testFunctionCallInNestedDict(self):
1363    code = "a = {'a': {'a': {'a': b(c=d, **e)}}}\n"
1364    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1365    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1366
1367  def testUnbreakableNot(self):
1368    code = textwrap.dedent("""\
1369        def test():
1370          if not "Foooooooooooooooooooooooooooooo" or "Foooooooooooooooooooooooooooooo" == "Foooooooooooooooooooooooooooooo":
1371            pass
1372        """)
1373    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1374    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1375
1376  def testSplitListWithComment(self):
1377    code = textwrap.dedent("""\
1378      a = [
1379          'a',
1380          'b',
1381          'c'  # hello world
1382      ]
1383      """)
1384    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1385    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1386
1387  def testOverColumnLimit(self):
1388    unformatted_code = textwrap.dedent("""\
1389      class Test:
1390
1391        def testSomething(self):
1392          expected = {
1393              ('aaaaaaaaaaaaa', 'bbbb'): 'ccccccccccccccccccccccccccccccccccccccccccc',
1394              ('aaaaaaaaaaaaa', 'bbbb'): 'ccccccccccccccccccccccccccccccccccccccccccc',
1395              ('aaaaaaaaaaaaa', 'bbbb'): 'ccccccccccccccccccccccccccccccccccccccccccc',
1396          }
1397        """)
1398    expected_formatted_code = textwrap.dedent("""\
1399      class Test:
1400
1401        def testSomething(self):
1402          expected = {
1403              ('aaaaaaaaaaaaa', 'bbbb'):
1404                  'ccccccccccccccccccccccccccccccccccccccccccc',
1405              ('aaaaaaaaaaaaa', 'bbbb'):
1406                  'ccccccccccccccccccccccccccccccccccccccccccc',
1407              ('aaaaaaaaaaaaa', 'bbbb'):
1408                  'ccccccccccccccccccccccccccccccccccccccccccc',
1409          }
1410        """)
1411    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1412    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1413
1414  def testEndingComment(self):
1415    code = textwrap.dedent("""\
1416      a = f(
1417          a="something",
1418          b="something requiring comment which is quite long",  # comment about b (pushes line over 79)
1419          c="something else, about which comment doesn't make sense")
1420      """)
1421    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1422    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1423
1424  def testContinuationSpaceRetention(self):
1425    code = textwrap.dedent("""\
1426      def fn():
1427        return module \\
1428               .method(Object(data,
1429                   fn2(arg)
1430               ))
1431      """)
1432    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1433    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1434
1435  def testIfExpressionWithFunctionCall(self):
1436    code = textwrap.dedent("""\
1437      if x or z.y(
1438          a,
1439          c,
1440          aaaaaaaaaaaaaaaaaaaaa=aaaaaaaaaaaaaaaaaa,
1441          bbbbbbbbbbbbbbbbbbbbb=bbbbbbbbbbbbbbbbbb):
1442        pass
1443      """)
1444    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1445    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1446
1447  def testUnformattedAfterMultilineString(self):
1448    code = textwrap.dedent("""\
1449      def foo():
1450        com_text = \\
1451      '''
1452      TEST
1453      ''' % (input_fname, output_fname)
1454      """)
1455    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1456    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1457
1458  def testNoSpacesAroundKeywordDefaultValues(self):
1459    code = textwrap.dedent("""\
1460      sources = {
1461          'json': request.get_json(silent=True) or {},
1462          'json2': request.get_json(silent=True),
1463      }
1464      json = request.get_json(silent=True) or {}
1465      """)
1466    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1467    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1468
1469  def testNoSplittingBeforeEndingSubscriptBracket(self):
1470    unformatted_code = textwrap.dedent("""\
1471        if True:
1472          if True:
1473            status = cf.describe_stacks(StackName=stackname)[u'Stacks'][0][u'StackStatus']
1474        """)
1475    expected_formatted_code = textwrap.dedent("""\
1476        if True:
1477          if True:
1478            status = cf.describe_stacks(
1479                StackName=stackname)[u'Stacks'][0][u'StackStatus']
1480        """)
1481    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1482    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1483
1484  def testNoSplittingOnSingleArgument(self):
1485    unformatted_code = textwrap.dedent("""\
1486        xxxxxxxxxxxxxx = (re.search(r'(\\d+\\.\\d+\\.\\d+\\.)\\d+',
1487                                    aaaaaaa.bbbbbbbbbbbb).group(1) +
1488                          re.search(r'\\d+\\.\\d+\\.\\d+\\.(\\d+)',
1489                                    ccccccc).group(1))
1490        xxxxxxxxxxxxxx = (re.search(r'(\\d+\\.\\d+\\.\\d+\\.)\\d+',
1491                                    aaaaaaa.bbbbbbbbbbbb).group(a.b) +
1492                          re.search(r'\\d+\\.\\d+\\.\\d+\\.(\\d+)',
1493                                    ccccccc).group(c.d))
1494        """)
1495    expected_formatted_code = textwrap.dedent("""\
1496        xxxxxxxxxxxxxx = (
1497            re.search(r'(\\d+\\.\\d+\\.\\d+\\.)\\d+', aaaaaaa.bbbbbbbbbbbb).group(1) +
1498            re.search(r'\\d+\\.\\d+\\.\\d+\\.(\\d+)', ccccccc).group(1))
1499        xxxxxxxxxxxxxx = (
1500            re.search(r'(\\d+\\.\\d+\\.\\d+\\.)\\d+', aaaaaaa.bbbbbbbbbbbb).group(a.b) +
1501            re.search(r'\\d+\\.\\d+\\.\\d+\\.(\\d+)', ccccccc).group(c.d))
1502        """)
1503    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1504    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1505
1506  def testSplittingArraysSensibly(self):
1507    unformatted_code = textwrap.dedent("""\
1508        while True:
1509          while True:
1510            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = list['bbbbbbbbbbbbbbbbbbbbbbbbb'].split(',')
1511            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = list('bbbbbbbbbbbbbbbbbbbbbbbbb').split(',')
1512        """)
1513    expected_formatted_code = textwrap.dedent("""\
1514        while True:
1515          while True:
1516            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = list[
1517                'bbbbbbbbbbbbbbbbbbbbbbbbb'].split(',')
1518            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = list(
1519                'bbbbbbbbbbbbbbbbbbbbbbbbb').split(',')
1520        """)
1521    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1522    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1523
1524  def testComprehensionForAndIf(self):
1525    unformatted_code = textwrap.dedent("""\
1526        class f:
1527
1528          def __repr__(self):
1529            tokens_repr = ','.join(['{0}({1!r})'.format(tok.name, tok.value) for tok in self._tokens])
1530        """)
1531    expected_formatted_code = textwrap.dedent("""\
1532        class f:
1533
1534          def __repr__(self):
1535            tokens_repr = ','.join(
1536                ['{0}({1!r})'.format(tok.name, tok.value) for tok in self._tokens])
1537        """)
1538    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1539    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1540
1541  def testFunctionCallArguments(self):
1542    unformatted_code = textwrap.dedent("""\
1543        def f():
1544          if True:
1545            pytree_utils.InsertNodesBefore(_CreateCommentsFromPrefix(
1546                comment_prefix, comment_lineno, comment_column,
1547                standalone=True), ancestor_at_indent)
1548            pytree_utils.InsertNodesBefore(_CreateCommentsFromPrefix(
1549                comment_prefix, comment_lineno, comment_column,
1550                standalone=True))
1551        """)
1552    expected_formatted_code = textwrap.dedent("""\
1553        def f():
1554          if True:
1555            pytree_utils.InsertNodesBefore(
1556                _CreateCommentsFromPrefix(
1557                    comment_prefix, comment_lineno, comment_column, standalone=True),
1558                ancestor_at_indent)
1559            pytree_utils.InsertNodesBefore(
1560                _CreateCommentsFromPrefix(
1561                    comment_prefix, comment_lineno, comment_column, standalone=True))
1562        """)
1563    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1564    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1565
1566  def testBinaryOperators(self):
1567    unformatted_code = textwrap.dedent("""\
1568        a = b ** 37
1569        c = (20 ** -3) / (_GRID_ROWS ** (code_length - 10))
1570        """)
1571    expected_formatted_code = textwrap.dedent("""\
1572        a = b**37
1573        c = (20**-3) / (_GRID_ROWS**(code_length - 10))
1574        """)
1575    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1576    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1577
1578    code = textwrap.dedent("""\
1579      def f():
1580        if True:
1581          if (self.stack[-1].split_before_closing_bracket and
1582              # FIXME(morbo): Use the 'matching_bracket' instead of this.
1583              # FIXME(morbo): Don't forget about tuples!
1584              current.value in ']}'):
1585            pass
1586      """)
1587    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1588    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1589
1590  def testContiguousList(self):
1591    code = textwrap.dedent("""\
1592      [retval1, retval2] = a_very_long_function(argument_1, argument2, argument_3,
1593                                                argument_4)
1594      """)
1595    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1596    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1597
1598  def testArgsAndKwargsFormatting(self):
1599    code = textwrap.dedent("""\
1600      a(a=aaaaaaaaaaaaaaaaaaaaa,
1601        b=aaaaaaaaaaaaaaaaaaaaaaaa,
1602        c=aaaaaaaaaaaaaaaaaa,
1603        *d,
1604        **e)
1605      """)
1606    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1607    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1608
1609    code = textwrap.dedent("""\
1610      def foo():
1611        return [
1612            Bar(xxx='some string',
1613                yyy='another long string',
1614                zzz='a third long string')
1615        ]
1616      """)
1617    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1618    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1619
1620  def testCommentColumnLimitOverflow(self):
1621    code = textwrap.dedent("""\
1622      def f():
1623        if True:
1624          TaskManager.get_tags = MagicMock(
1625              name='get_tags_mock',
1626              return_value=[157031694470475],
1627              # side_effect=[(157031694470475), (157031694470475),],
1628          )
1629      """)
1630    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1631    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1632
1633  def testMultilineLambdas(self):
1634    try:
1635      style.SetGlobalStyle(
1636          style.CreateStyleFromConfig(
1637              '{based_on_style: chromium, allow_multiline_lambdas: true}'))
1638      unformatted_code = textwrap.dedent("""\
1639          class SomeClass(object):
1640            do_something = True
1641
1642            def succeeded(self, dddddddddddddd):
1643              d = defer.succeed(None)
1644
1645              if self.do_something:
1646                d.addCallback(lambda _: self.aaaaaa.bbbbbbbbbbbbbbbb.cccccccccccccccccccccccccccccccc(dddddddddddddd))
1647              return d
1648          """)
1649      expected_formatted_code = textwrap.dedent("""\
1650          class SomeClass(object):
1651            do_something = True
1652
1653            def succeeded(self, dddddddddddddd):
1654              d = defer.succeed(None)
1655
1656              if self.do_something:
1657                d.addCallback(lambda _: self.aaaaaa.bbbbbbbbbbbbbbbb.
1658                              cccccccccccccccccccccccccccccccc(dddddddddddddd))
1659              return d
1660          """)
1661      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1662      self.assertCodeEqual(expected_formatted_code,
1663                           reformatter.Reformat(uwlines))
1664    finally:
1665      style.SetGlobalStyle(style.CreateChromiumStyle())
1666
1667  def testMultilineDictionaryKeys(self):
1668    try:
1669      style.SetGlobalStyle(
1670          style.CreateStyleFromConfig('{based_on_style: chromium, '
1671                                      'allow_multiline_dictionary_keys: true}'))
1672      unformatted_code = textwrap.dedent("""\
1673          MAP_WITH_LONG_KEYS = {
1674              ('lorem ipsum', 'dolor sit amet'):
1675                  1,
1676              ('consectetur adipiscing elit.', 'Vestibulum mauris justo, ornare eget dolor eget'):
1677                  2,
1678              ('vehicula convallis nulla. Vestibulum dictum nisl in malesuada finibus.',):
1679                  3
1680          }
1681          """)
1682      expected_formatted_code = textwrap.dedent("""\
1683          MAP_WITH_LONG_KEYS = {
1684              ('lorem ipsum', 'dolor sit amet'):
1685                  1,
1686              ('consectetur adipiscing elit.',
1687               'Vestibulum mauris justo, ornare eget dolor eget'):
1688                  2,
1689              ('vehicula convallis nulla. Vestibulum dictum nisl in malesuada finibus.',):
1690                  3
1691          }
1692          """)
1693      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1694      self.assertCodeEqual(expected_formatted_code,
1695                           reformatter.Reformat(uwlines))
1696    finally:
1697      style.SetGlobalStyle(style.CreateChromiumStyle())
1698
1699  def testStableDictionaryFormatting(self):
1700    try:
1701      style.SetGlobalStyle(
1702          style.CreateStyleFromConfig(
1703              '{based_on_style: pep8, indent_width: 2, '
1704              'continuation_indent_width: 4, indent_dictionary_value: True}'))
1705      code = textwrap.dedent("""\
1706          class A(object):
1707            def method(self):
1708              filters = {
1709                  'expressions': [{
1710                      'field': {
1711                          'search_field': {
1712                              'user_field': 'latest_party__number_of_guests'
1713                          },
1714                      }
1715                  }]
1716              }
1717          """)
1718      uwlines = yapf_test_helper.ParseAndUnwrap(code)
1719      reformatted_code = reformatter.Reformat(uwlines)
1720      self.assertCodeEqual(code, reformatted_code)
1721
1722      uwlines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
1723      reformatted_code = reformatter.Reformat(uwlines)
1724      self.assertCodeEqual(code, reformatted_code)
1725    finally:
1726      style.SetGlobalStyle(style.CreateChromiumStyle())
1727
1728  def testStableInlinedDictionaryFormatting(self):
1729    try:
1730      style.SetGlobalStyle(style.CreatePEP8Style())
1731      unformatted_code = textwrap.dedent("""\
1732          def _():
1733              url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
1734                  value, urllib.urlencode({'action': 'update', 'parameter': value}))
1735          """)
1736      expected_formatted_code = textwrap.dedent("""\
1737          def _():
1738              url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
1739                  value, urllib.urlencode({
1740                      'action': 'update',
1741                      'parameter': value
1742                  }))
1743          """)
1744
1745      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1746      reformatted_code = reformatter.Reformat(uwlines)
1747      self.assertCodeEqual(expected_formatted_code, reformatted_code)
1748
1749      uwlines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
1750      reformatted_code = reformatter.Reformat(uwlines)
1751      self.assertCodeEqual(expected_formatted_code, reformatted_code)
1752    finally:
1753      style.SetGlobalStyle(style.CreateChromiumStyle())
1754
1755  def testDontSplitKeywordValueArguments(self):
1756    unformatted_code = textwrap.dedent("""\
1757        def mark_game_scored(gid):
1758          _connect.execute(_games.update().where(_games.c.gid == gid).values(
1759              scored=True))
1760        """)
1761    expected_formatted_code = textwrap.dedent("""\
1762        def mark_game_scored(gid):
1763          _connect.execute(
1764              _games.update().where(_games.c.gid == gid).values(scored=True))
1765        """)
1766    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1767    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1768
1769  def testDontAddBlankLineAfterMultilineString(self):
1770    code = textwrap.dedent("""\
1771      query = '''SELECT id
1772      FROM table
1773      WHERE day in {}'''
1774      days = ",".join(days)
1775      """)
1776    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1777    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1778
1779  def testFormattingListComprehensions(self):
1780    code = textwrap.dedent("""\
1781      def a():
1782        if True:
1783          if True:
1784            if True:
1785              columns = [
1786                  x for x, y in self._heap_this_is_very_long if x.route[0] == choice
1787              ]
1788              self._heap = [x for x in self._heap if x.route and x.route[0] == choice]
1789      """)
1790    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1791    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1792
1793  def testNoSplittingWhenBinPacking(self):
1794    try:
1795      style.SetGlobalStyle(
1796          style.CreateStyleFromConfig(
1797              '{based_on_style: pep8, indent_width: 2, '
1798              'continuation_indent_width: 4, indent_dictionary_value: True, '
1799              'dedent_closing_brackets: True, '
1800              'split_before_named_assigns: False}'))
1801      code = textwrap.dedent("""\
1802          a_very_long_function_name(
1803              long_argument_name_1=1,
1804              long_argument_name_2=2,
1805              long_argument_name_3=3,
1806              long_argument_name_4=4,
1807          )
1808
1809          a_very_long_function_name(
1810              long_argument_name_1=1, long_argument_name_2=2, long_argument_name_3=3,
1811              long_argument_name_4=4
1812          )
1813          """)
1814      uwlines = yapf_test_helper.ParseAndUnwrap(code)
1815      reformatted_code = reformatter.Reformat(uwlines)
1816      self.assertCodeEqual(code, reformatted_code)
1817
1818      uwlines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
1819      reformatted_code = reformatter.Reformat(uwlines)
1820      self.assertCodeEqual(code, reformatted_code)
1821    finally:
1822      style.SetGlobalStyle(style.CreateChromiumStyle())
1823
1824  def testNotSplittingAfterSubscript(self):
1825    unformatted_code = textwrap.dedent("""\
1826        if not aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.b(c == d[
1827                'eeeeee']).ffffff():
1828          pass
1829        """)
1830    expected_formatted_code = textwrap.dedent("""\
1831        if not aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.b(
1832            c == d['eeeeee']).ffffff():
1833          pass
1834        """)
1835    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1836    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1837
1838  def testSplittingOneArgumentList(self):
1839    unformatted_code = textwrap.dedent("""\
1840        def _():
1841          if True:
1842            if True:
1843              if True:
1844                if True:
1845                  if True:
1846                    boxes[id_] = np.concatenate((points.min(axis=0), qoints.max(axis=0)))
1847        """)
1848    expected_formatted_code = textwrap.dedent("""\
1849        def _():
1850          if True:
1851            if True:
1852              if True:
1853                if True:
1854                  if True:
1855                    boxes[id_] = np.concatenate((points.min(axis=0),
1856                                                 qoints.max(axis=0)))
1857        """)
1858    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1859    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1860
1861  def testSplittingBeforeFirstElementListArgument(self):
1862    unformatted_code = textwrap.dedent("""\
1863        class _():
1864          @classmethod
1865          def _pack_results_for_constraint_or(cls, combination, constraints):
1866            if True:
1867              if True:
1868                if True:
1869                  return cls._create_investigation_result(
1870                          (
1871                                  clue for clue in combination if not clue == Verifier.UNMATCHED
1872                          ), constraints, InvestigationResult.OR
1873                  )
1874        """)
1875    expected_formatted_code = textwrap.dedent("""\
1876        class _():
1877
1878          @classmethod
1879          def _pack_results_for_constraint_or(cls, combination, constraints):
1880            if True:
1881              if True:
1882                if True:
1883                  return cls._create_investigation_result(
1884                      (clue for clue in combination if not clue == Verifier.UNMATCHED),
1885                      constraints, InvestigationResult.OR)
1886        """)
1887    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1888    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1889
1890  def testSplittingArgumentsTerminatedByComma(self):
1891    try:
1892      style.SetGlobalStyle(
1893          style.CreateStyleFromConfig(
1894              '{based_on_style: chromium, '
1895              'split_arguments_when_comma_terminated: True}'))
1896      unformatted_code = textwrap.dedent("""\
1897          function_name(argument_name_1=1, argument_name_2=2, argument_name_3=3)
1898
1899          function_name(argument_name_1=1, argument_name_2=2, argument_name_3=3,)
1900
1901          a_very_long_function_name(long_argument_name_1=1, long_argument_name_2=2, long_argument_name_3=3, long_argument_name_4=4)
1902
1903          a_very_long_function_name(long_argument_name_1, long_argument_name_2, long_argument_name_3, long_argument_name_4,)
1904
1905          r =f0 (1,  2,3,)
1906          """)
1907      expected_formatted_code = textwrap.dedent("""\
1908          function_name(argument_name_1=1, argument_name_2=2, argument_name_3=3)
1909
1910          function_name(
1911              argument_name_1=1,
1912              argument_name_2=2,
1913              argument_name_3=3,
1914          )
1915
1916          a_very_long_function_name(
1917              long_argument_name_1=1,
1918              long_argument_name_2=2,
1919              long_argument_name_3=3,
1920              long_argument_name_4=4)
1921
1922          a_very_long_function_name(
1923              long_argument_name_1,
1924              long_argument_name_2,
1925              long_argument_name_3,
1926              long_argument_name_4,
1927          )
1928
1929          r = f0(
1930              1,
1931              2,
1932              3,
1933          )
1934          """)
1935      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1936      reformatted_code = reformatter.Reformat(uwlines)
1937      self.assertCodeEqual(expected_formatted_code, reformatted_code)
1938
1939      uwlines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
1940      reformatted_code = reformatter.Reformat(uwlines)
1941      self.assertCodeEqual(expected_formatted_code, reformatted_code)
1942    finally:
1943      style.SetGlobalStyle(style.CreateChromiumStyle())
1944
1945  def testImportAsList(self):
1946    code = textwrap.dedent("""\
1947        from toto import titi, tata, tutu  # noqa
1948        from toto import titi, tata, tutu
1949        from toto import (titi, tata, tutu)
1950        """)
1951    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1952    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1953
1954  def testDictionaryValuesOnOwnLines(self):
1955    unformatted_code = textwrap.dedent("""\
1956        a = {
1957        'aaaaaaaaaaaaaaaaaaaaaaaa':
1958            Check('ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ', '=', True),
1959        'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb':
1960            Check('YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY', '=', True),
1961        'ccccccccccccccc':
1962            Check('XXXXXXXXXXXXXXXXXXX', '!=', 'SUSPENDED'),
1963        'dddddddddddddddddddddddddddddd':
1964            Check('WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW', '=', False),
1965        'eeeeeeeeeeeeeeeeeeeeeeeeeeeee':
1966            Check('VVVVVVVVVVVVVVVVVVVVVVVVVVVVVV', '=', False),
1967        'ffffffffffffffffffffffffff':
1968            Check('UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU', '=', True),
1969        'ggggggggggggggggg':
1970            Check('TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT', '=', True),
1971        'hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh':
1972            Check('SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS', '=', True),
1973        'iiiiiiiiiiiiiiiiiiiiiiii':
1974            Check('RRRRRRRRRRRRRRRRRRRRRRRRRRR', '=', True),
1975        'jjjjjjjjjjjjjjjjjjjjjjjjjj':
1976            Check('QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ', '=', False),
1977        }
1978        """)
1979    expected_formatted_code = textwrap.dedent("""\
1980        a = {
1981            'aaaaaaaaaaaaaaaaaaaaaaaa':
1982                Check('ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ', '=', True),
1983            'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb':
1984                Check('YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY', '=', True),
1985            'ccccccccccccccc':
1986                Check('XXXXXXXXXXXXXXXXXXX', '!=', 'SUSPENDED'),
1987            'dddddddddddddddddddddddddddddd':
1988                Check('WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW', '=', False),
1989            'eeeeeeeeeeeeeeeeeeeeeeeeeeeee':
1990                Check('VVVVVVVVVVVVVVVVVVVVVVVVVVVVVV', '=', False),
1991            'ffffffffffffffffffffffffff':
1992                Check('UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU', '=', True),
1993            'ggggggggggggggggg':
1994                Check('TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT', '=', True),
1995            'hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh':
1996                Check('SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS', '=', True),
1997            'iiiiiiiiiiiiiiiiiiiiiiii':
1998                Check('RRRRRRRRRRRRRRRRRRRRRRRRRRR', '=', True),
1999            'jjjjjjjjjjjjjjjjjjjjjjjjjj':
2000                Check('QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ', '=', False),
2001        }
2002        """)
2003    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2004    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
2005
2006  def testDictionaryOnOwnLine(self):
2007    unformatted_code = textwrap.dedent("""\
2008        doc = test_utils.CreateTestDocumentViaController(
2009            content={ 'a': 'b' },
2010            branch_key=branch.key,
2011            collection_key=collection.key)
2012        """)
2013    expected_formatted_code = textwrap.dedent("""\
2014        doc = test_utils.CreateTestDocumentViaController(
2015            content={'a': 'b'}, branch_key=branch.key, collection_key=collection.key)
2016        """)
2017    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2018    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
2019
2020    unformatted_code = textwrap.dedent("""\
2021        doc = test_utils.CreateTestDocumentViaController(
2022            content={ 'a': 'b' },
2023            branch_key=branch.key,
2024            collection_key=collection.key,
2025            collection_key2=collection.key2)
2026        """)
2027    expected_formatted_code = textwrap.dedent("""\
2028        doc = test_utils.CreateTestDocumentViaController(
2029            content={'a': 'b'},
2030            branch_key=branch.key,
2031            collection_key=collection.key,
2032            collection_key2=collection.key2)
2033        """)
2034    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2035    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
2036
2037  def testNestedListsInDictionary(self):
2038    unformatted_code = textwrap.dedent("""\
2039        _A = {
2040            'cccccccccc': ('^^1',),
2041            'rrrrrrrrrrrrrrrrrrrrrrrrr': ('^7913',  # AAAAAAAAAAAAAA.
2042                                         ),
2043            'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee': ('^6242',  # BBBBBBBBBBBBBBB.
2044                                                  ),
2045            'vvvvvvvvvvvvvvvvvvv': ('^27959',  # CCCCCCCCCCCCCCCCCC.
2046                                    '^19746',  # DDDDDDDDDDDDDDDDDDDDDDD.
2047                                    '^22907',  # EEEEEEEEEEEEEEEEEEEEEEEE.
2048                                    '^21098',  # FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.
2049                                    '^22826',  # GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG.
2050                                    '^22769',  # HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH.
2051                                    '^22935',  # IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII.
2052                                    '^3982',  # JJJJJJJJJJJJJ.
2053                                   ),
2054            'uuuuuuuuuuuu': ('^19745',  # LLLLLLLLLLLLLLLLLLLLLLLLLL.
2055                             '^21324',  # MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.
2056                             '^22831',  # NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN.
2057                             '^17081',  # OOOOOOOOOOOOOOOOOOOOO.
2058                            ),
2059            'eeeeeeeeeeeeee': (
2060                '^9416',  # Reporter email. Not necessarily the reporter.
2061                '^^3',  # This appears to be the raw email field.
2062            ),
2063            'cccccccccc': ('^21109',  # PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP.
2064                          ),
2065        }
2066        """)
2067    expected_formatted_code = textwrap.dedent("""\
2068        _A = {
2069            'cccccccccc': ('^^1',),
2070            'rrrrrrrrrrrrrrrrrrrrrrrrr': (
2071                '^7913',  # AAAAAAAAAAAAAA.
2072            ),
2073            'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee': (
2074                '^6242',  # BBBBBBBBBBBBBBB.
2075            ),
2076            'vvvvvvvvvvvvvvvvvvv': (
2077                '^27959',  # CCCCCCCCCCCCCCCCCC.
2078                '^19746',  # DDDDDDDDDDDDDDDDDDDDDDD.
2079                '^22907',  # EEEEEEEEEEEEEEEEEEEEEEEE.
2080                '^21098',  # FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.
2081                '^22826',  # GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG.
2082                '^22769',  # HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH.
2083                '^22935',  # IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII.
2084                '^3982',  # JJJJJJJJJJJJJ.
2085            ),
2086            'uuuuuuuuuuuu': (
2087                '^19745',  # LLLLLLLLLLLLLLLLLLLLLLLLLL.
2088                '^21324',  # MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.
2089                '^22831',  # NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN.
2090                '^17081',  # OOOOOOOOOOOOOOOOOOOOO.
2091            ),
2092            'eeeeeeeeeeeeee': (
2093                '^9416',  # Reporter email. Not necessarily the reporter.
2094                '^^3',  # This appears to be the raw email field.
2095            ),
2096            'cccccccccc': (
2097                '^21109',  # PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP.
2098            ),
2099        }
2100        """)
2101    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2102    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
2103
2104  def testNestedDictionary(self):
2105    unformatted_code = textwrap.dedent("""\
2106        class _():
2107          def _():
2108            breadcrumbs = [{'name': 'Admin',
2109                            'url': url_for(".home")},
2110                           {'title': title},]
2111            breadcrumbs = [{'name': 'Admin',
2112                            'url': url_for(".home")},
2113                           {'title': title}]
2114        """)
2115    expected_formatted_code = textwrap.dedent("""\
2116        class _():
2117          def _():
2118            breadcrumbs = [
2119                {
2120                    'name': 'Admin',
2121                    'url': url_for(".home")
2122                },
2123                {
2124                    'title': title
2125                },
2126            ]
2127            breadcrumbs = [{'name': 'Admin', 'url': url_for(".home")}, {'title': title}]
2128        """)
2129    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2130    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
2131
2132  def testDictionaryElementsOnOneLine(self):
2133    code = textwrap.dedent("""\
2134        class _():
2135
2136          @mock.patch.dict(
2137              os.environ,
2138              {'HTTP_' + xsrf._XSRF_TOKEN_HEADER.replace('-', '_'): 'atoken'})
2139          def _():
2140            pass
2141
2142
2143        AAAAAAAAAAAAAAAAAAAAAAAA = {
2144            Environment.XXXXXXXXXX: 'some text more text even more tex',
2145            Environment.YYYYYYY: 'some text more text even more text yet ag',
2146            Environment.ZZZZZZZZZZZ: 'some text more text even mor etext yet again tex',
2147        }
2148        """)
2149    uwlines = yapf_test_helper.ParseAndUnwrap(code)
2150    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
2151
2152  def testNotInParams(self):
2153    unformatted_code = textwrap.dedent("""\
2154        list("a long line to break the line. a long line to break the brk a long lin", not True)
2155        """)
2156    expected_code = textwrap.dedent("""\
2157        list("a long line to break the line. a long line to break the brk a long lin",
2158             not True)
2159        """)
2160    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2161    self.assertEqual(expected_code, reformatter.Reformat(uwlines))
2162
2163  def testNamedAssignNotAtEndOfLine(self):
2164    unformatted_code = textwrap.dedent("""\
2165        def _():
2166          if True:
2167            with py3compat.open_with_encoding(filename, mode='w',
2168                                              encoding=encoding) as fd:
2169              pass
2170        """)
2171    expected_code = textwrap.dedent("""\
2172        def _():
2173          if True:
2174            with py3compat.open_with_encoding(
2175                filename, mode='w', encoding=encoding) as fd:
2176              pass
2177        """)
2178    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2179    self.assertEqual(expected_code, reformatter.Reformat(uwlines))
2180
2181  def testBlankLineBeforeClassDocstring(self):
2182    unformatted_code = textwrap.dedent('''\
2183        class A:
2184
2185          """Does something.
2186
2187          Also, here are some details.
2188          """
2189
2190          def __init__(self):
2191            pass
2192        ''')
2193    expected_code = textwrap.dedent('''\
2194        class A:
2195          """Does something.
2196
2197          Also, here are some details.
2198          """
2199
2200          def __init__(self):
2201            pass
2202        ''')
2203    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2204    self.assertEqual(expected_code, reformatter.Reformat(uwlines))
2205
2206    try:
2207      style.SetGlobalStyle(
2208          style.CreateStyleFromConfig(
2209              '{based_on_style: chromium, '
2210              'blank_line_before_class_docstring: True}'))
2211      unformatted_code = textwrap.dedent('''\
2212          class A:
2213
2214            """Does something.
2215
2216            Also, here are some details.
2217            """
2218
2219            def __init__(self):
2220              pass
2221          ''')
2222      expected_formatted_code = textwrap.dedent('''\
2223          class A:
2224
2225            """Does something.
2226
2227            Also, here are some details.
2228            """
2229
2230            def __init__(self):
2231              pass
2232          ''')
2233      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2234      self.assertCodeEqual(expected_formatted_code,
2235                           reformatter.Reformat(uwlines))
2236    finally:
2237      style.SetGlobalStyle(style.CreateChromiumStyle())
2238
2239  def testBlankLineBeforeModuleDocstring(self):
2240    unformatted_code = textwrap.dedent('''\
2241        #!/usr/bin/env python
2242        # -*- coding: utf-8 name> -*-
2243
2244        """Some module docstring."""
2245
2246
2247        def foobar():
2248          pass
2249        ''')
2250    expected_code = textwrap.dedent('''\
2251        #!/usr/bin/env python
2252        # -*- coding: utf-8 name> -*-
2253        """Some module docstring."""
2254
2255
2256        def foobar():
2257          pass
2258        ''')
2259    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2260    self.assertEqual(expected_code, reformatter.Reformat(uwlines))
2261
2262    try:
2263      style.SetGlobalStyle(
2264          style.CreateStyleFromConfig(
2265              '{based_on_style: pep8, '
2266              'blank_line_before_module_docstring: True}'))
2267      unformatted_code = textwrap.dedent('''\
2268        #!/usr/bin/env python
2269        # -*- coding: utf-8 name> -*-
2270        """Some module docstring."""
2271
2272
2273        def foobar():
2274            pass
2275          ''')
2276      expected_formatted_code = textwrap.dedent('''\
2277        #!/usr/bin/env python
2278        # -*- coding: utf-8 name> -*-
2279
2280        """Some module docstring."""
2281
2282
2283        def foobar():
2284            pass
2285          ''')
2286      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2287      self.assertCodeEqual(expected_formatted_code,
2288                           reformatter.Reformat(uwlines))
2289    finally:
2290      style.SetGlobalStyle(style.CreateChromiumStyle())
2291
2292  def testTupleCohesion(self):
2293    unformatted_code = textwrap.dedent("""\
2294        def f():
2295          this_is_a_very_long_function_name(an_extremely_long_variable_name, (
2296              'a string that may be too long %s' % 'M15'))
2297        """)
2298    expected_code = textwrap.dedent("""\
2299        def f():
2300          this_is_a_very_long_function_name(
2301              an_extremely_long_variable_name,
2302              ('a string that may be too long %s' % 'M15'))
2303        """)
2304    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2305    self.assertEqual(expected_code, reformatter.Reformat(uwlines))
2306
2307  def testSubscriptExpression(self):
2308    code = textwrap.dedent("""\
2309        foo = d[not a]
2310        """)
2311    uwlines = yapf_test_helper.ParseAndUnwrap(code)
2312    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
2313
2314  def testListWithFunctionCalls(self):
2315    unformatted_code = textwrap.dedent("""\
2316        def foo():
2317          return [
2318              Bar(
2319                  xxx='some string',
2320                  yyy='another long string',
2321                  zzz='a third long string'), Bar(
2322                      xxx='some string',
2323                      yyy='another long string',
2324                      zzz='a third long string')
2325          ]
2326        """)
2327    expected_code = textwrap.dedent("""\
2328        def foo():
2329          return [
2330              Bar(xxx='some string',
2331                  yyy='another long string',
2332                  zzz='a third long string'),
2333              Bar(xxx='some string',
2334                  yyy='another long string',
2335                  zzz='a third long string')
2336          ]
2337        """)
2338    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2339    self.assertEqual(expected_code, reformatter.Reformat(uwlines))
2340
2341  def testEllipses(self):
2342    unformatted_code = textwrap.dedent("""\
2343        X=...
2344        Y = X if ... else X
2345        """)
2346    expected_code = textwrap.dedent("""\
2347        X = ...
2348        Y = X if ... else X
2349        """)
2350    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2351    self.assertEqual(expected_code, reformatter.Reformat(uwlines))
2352
2353  def testSplittingBeforeFirstArgumentOnFunctionCall(self):
2354    """Tests split_before_first_argument on a function call."""
2355    try:
2356      style.SetGlobalStyle(
2357          style.CreateStyleFromConfig(
2358              '{based_on_style: chromium, split_before_first_argument: True}'))
2359      unformatted_code = textwrap.dedent("""\
2360          a_very_long_function_name("long string with formatting {0:s}".format(
2361              "mystring"))
2362          """)
2363      expected_formatted_code = textwrap.dedent("""\
2364          a_very_long_function_name(
2365              "long string with formatting {0:s}".format("mystring"))
2366          """)
2367      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2368      self.assertCodeEqual(expected_formatted_code,
2369                           reformatter.Reformat(uwlines))
2370    finally:
2371      style.SetGlobalStyle(style.CreateChromiumStyle())
2372
2373  def testSplittingBeforeFirstArgumentOnFunctionDefinition(self):
2374    """Tests split_before_first_argument on a function definition."""
2375    try:
2376      style.SetGlobalStyle(
2377          style.CreateStyleFromConfig(
2378              '{based_on_style: chromium, split_before_first_argument: True}'))
2379      unformatted_code = textwrap.dedent("""\
2380          def _GetNumberOfSecondsFromElements(year, month, day, hours,
2381                                              minutes, seconds, microseconds):
2382            return
2383          """)
2384      expected_formatted_code = textwrap.dedent("""\
2385          def _GetNumberOfSecondsFromElements(
2386              year, month, day, hours, minutes, seconds, microseconds):
2387            return
2388          """)
2389      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2390      self.assertCodeEqual(expected_formatted_code,
2391                           reformatter.Reformat(uwlines))
2392    finally:
2393      style.SetGlobalStyle(style.CreateChromiumStyle())
2394
2395  def testSplittingBeforeFirstArgumentOnCompoundStatement(self):
2396    """Tests split_before_first_argument on a compound statement."""
2397    try:
2398      style.SetGlobalStyle(
2399          style.CreateStyleFromConfig(
2400              '{based_on_style: chromium, split_before_first_argument: True}'))
2401      unformatted_code = textwrap.dedent("""\
2402          if (long_argument_name_1 == 1 or
2403              long_argument_name_2 == 2 or
2404              long_argument_name_3 == 3 or
2405              long_argument_name_4 == 4):
2406            pass
2407          """)
2408      expected_formatted_code = textwrap.dedent("""\
2409          if (long_argument_name_1 == 1 or long_argument_name_2 == 2 or
2410              long_argument_name_3 == 3 or long_argument_name_4 == 4):
2411            pass
2412          """)
2413      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2414      self.assertCodeEqual(expected_formatted_code,
2415                           reformatter.Reformat(uwlines))
2416    finally:
2417      style.SetGlobalStyle(style.CreateChromiumStyle())
2418
2419  def testCoalesceBracketsOnDict(self):
2420    """Tests coalesce_brackets on a dictionary."""
2421    try:
2422      style.SetGlobalStyle(
2423          style.CreateStyleFromConfig(
2424              '{based_on_style: chromium, coalesce_brackets: True}'))
2425      unformatted_code = textwrap.dedent("""\
2426          date_time_values = (
2427              {
2428                  u'year': year,
2429                  u'month': month,
2430                  u'day_of_month': day_of_month,
2431                  u'hours': hours,
2432                  u'minutes': minutes,
2433                  u'seconds': seconds
2434              }
2435          )
2436          """)
2437      expected_formatted_code = textwrap.dedent("""\
2438          date_time_values = ({
2439              u'year': year,
2440              u'month': month,
2441              u'day_of_month': day_of_month,
2442              u'hours': hours,
2443              u'minutes': minutes,
2444              u'seconds': seconds
2445          })
2446          """)
2447      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
2448      self.assertCodeEqual(expected_formatted_code,
2449                           reformatter.Reformat(uwlines))
2450    finally:
2451      style.SetGlobalStyle(style.CreateChromiumStyle())
2452
2453  def testSplitAfterComment(self):
2454    try:
2455      style.SetGlobalStyle(
2456          style.CreateStyleFromConfig(
2457              '{based_on_style: chromium, coalesce_brackets: True, '
2458              'dedent_closing_brackets: true}'))
2459      code = textwrap.dedent("""\
2460          if __name__ == "__main__":
2461            with another_resource:
2462              account = {
2463                  "validUntil":
2464                      int(time() + (6 * 7 * 24 * 60 * 60))  # in 6 weeks time
2465              }
2466          """)
2467      uwlines = yapf_test_helper.ParseAndUnwrap(code)
2468      self.assertCodeEqual(code, reformatter.Reformat(uwlines))
2469    finally:
2470      style.SetGlobalStyle(style.CreateChromiumStyle())
2471
2472  def testAsyncAsNonKeyword(self):
2473    try:
2474      style.SetGlobalStyle(style.CreatePEP8Style())
2475
2476      # In Python 2, async may be used as a non-keyword identifier.
2477      code = textwrap.dedent("""\
2478          from util import async
2479
2480
2481          class A(object):
2482              def foo(self):
2483                  async.run()
2484
2485              def bar(self):
2486                  pass
2487          """)
2488      uwlines = yapf_test_helper.ParseAndUnwrap(code)
2489      self.assertCodeEqual(code, reformatter.Reformat(uwlines, verify=False))
2490    finally:
2491      style.SetGlobalStyle(style.CreateChromiumStyle())
2492
2493  def testDisableEndingCommaHeuristic(self):
2494    try:
2495      style.SetGlobalStyle(
2496          style.CreateStyleFromConfig('{based_on_style: chromium,'
2497                                      ' disable_ending_comma_heuristic: True}'))
2498
2499      code = """\
2500x = [1, 2, 3, 4, 5, 6, 7,]
2501"""
2502      uwlines = yapf_test_helper.ParseAndUnwrap(code)
2503      self.assertCodeEqual(code, reformatter.Reformat(uwlines))
2504    finally:
2505      style.SetGlobalStyle(style.CreateChromiumStyle())
2506
2507
2508if __name__ == '__main__':
2509  unittest.main()
2510