xref: /aosp_15_r20/external/yapf/yapftests/reformatter_pep8_test.py (revision 7249d1a64f4850ccf838e62a46276f891f72998e)
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"""PEP8 tests for yapf.reformatter."""
15
16import textwrap
17import unittest
18
19from yapf.yapflib import py3compat
20from yapf.yapflib import reformatter
21from yapf.yapflib import style
22
23from yapftests import yapf_test_helper
24
25
26class TestsForPEP8Style(yapf_test_helper.YAPFTest):
27
28  @classmethod
29  def setUpClass(cls):  # pylint: disable=g-missing-super-call
30    style.SetGlobalStyle(style.CreatePEP8Style())
31
32  def testIndent4(self):
33    unformatted_code = textwrap.dedent("""\
34        if a+b:
35          pass
36        """)
37    expected_formatted_code = textwrap.dedent("""\
38        if a + b:
39            pass
40        """)
41    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
42    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
43
44  def testSingleLineIfStatements(self):
45    code = textwrap.dedent("""\
46        if True: a = 42
47        elif False: b = 42
48        else: c = 42
49        """)
50    llines = yapf_test_helper.ParseAndUnwrap(code)
51    self.assertCodeEqual(code, reformatter.Reformat(llines))
52
53  def testBlankBetweenClassAndDef(self):
54    unformatted_code = textwrap.dedent("""\
55        class Foo:
56          def joe():
57            pass
58        """)
59    expected_formatted_code = textwrap.dedent("""\
60        class Foo:
61
62            def joe():
63                pass
64        """)
65    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
66    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
67
68  def testBlankBetweenDefsInClass(self):
69    unformatted_code = textwrap.dedent('''\
70        class TestClass:
71            def __init__(self):
72                self.running = False
73            def run(self):
74                """Override in subclass"""
75            def is_running(self):
76                return self.running
77        ''')
78    expected_formatted_code = textwrap.dedent('''\
79        class TestClass:
80
81            def __init__(self):
82                self.running = False
83
84            def run(self):
85                """Override in subclass"""
86
87            def is_running(self):
88                return self.running
89        ''')
90    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
91    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
92
93  def testSingleWhiteBeforeTrailingComment(self):
94    unformatted_code = textwrap.dedent("""\
95        if a+b: # comment
96          pass
97        """)
98    expected_formatted_code = textwrap.dedent("""\
99        if a + b:  # comment
100            pass
101        """)
102    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
103    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
104
105  def testSpaceBetweenEndingCommandAndClosingBracket(self):
106    unformatted_code = textwrap.dedent("""\
107        a = (
108            1,
109        )
110        """)
111    expected_formatted_code = textwrap.dedent("""\
112        a = (1, )
113        """)
114    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
115    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
116
117  def testContinuedNonOutdentedLine(self):
118    code = textwrap.dedent("""\
119        class eld(d):
120            if str(geom.geom_type).upper(
121            ) != self.geom_type and not self.geom_type == 'GEOMETRY':
122                ror(code='om_type')
123        """)
124    llines = yapf_test_helper.ParseAndUnwrap(code)
125    self.assertCodeEqual(code, reformatter.Reformat(llines))
126
127  def testWrappingPercentExpressions(self):
128    unformatted_code = textwrap.dedent("""\
129        def f():
130            if True:
131                zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxx.yyy + 1)
132                zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxx.yyy + 1)
133                zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxxxxxx + 1)
134                zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxxxxxx + 1)
135        """)  # noqa
136    expected_formatted_code = textwrap.dedent("""\
137        def f():
138            if True:
139                zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxxxxx + 1,
140                                   xxxxxxxxxxxxxxxxx.yyy + 1)
141                zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxxxxx + 1,
142                                   xxxxxxxxxxxxxxxxx.yyy + 1)
143                zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxx + 1,
144                                   xxxxxxxxxxxxxxxxxxxxx + 1)
145                zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxx + 1,
146                                   xxxxxxxxxxxxxxxxxxxxx + 1)
147        """)
148    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
149    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
150
151  def testAlignClosingBracketWithVisualIndentation(self):
152    unformatted_code = textwrap.dedent("""\
153        TEST_LIST = ('foo', 'bar',  # first comment
154                     'baz'  # second comment
155                    )
156        """)
157    expected_formatted_code = textwrap.dedent("""\
158        TEST_LIST = (
159            'foo',
160            'bar',  # first comment
161            'baz'  # second comment
162        )
163        """)
164    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
165    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
166
167    unformatted_code = textwrap.dedent("""\
168        def f():
169
170          def g():
171            while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa' and
172                   xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'
173                  ):
174              pass
175        """)  # noqa
176    expected_formatted_code = textwrap.dedent("""\
177        def f():
178
179            def g():
180                while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa'
181                       and xxxxxxxxxxxxxxxxxxxx(
182                           yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'):
183                    pass
184        """)  # noqa
185    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
186    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
187
188  def testIndentSizeChanging(self):
189    unformatted_code = textwrap.dedent("""\
190        if True:
191          runtime_mins = (program_end_time - program_start_time).total_seconds() / 60.0
192        """)  # noqa
193    expected_formatted_code = textwrap.dedent("""\
194        if True:
195            runtime_mins = (program_end_time -
196                            program_start_time).total_seconds() / 60.0
197        """)
198    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
199    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
200
201  def testHangingIndentCollision(self):
202    unformatted_code = textwrap.dedent("""\
203        if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbbb == ccccccccccccccccc and xxxxxxxxxxxxx or yyyyyyyyyyyyyyyyy):
204            pass
205        elif (xxxxxxxxxxxxxxx(aaaaaaaaaaa, bbbbbbbbbbbbbb, cccccccccccc, dddddddddd=None)):
206            pass
207
208
209        def h():
210            if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
211                pass
212
213            for connection in itertools.chain(branch.contact, branch.address, morestuff.andmore.andmore.andmore.andmore.andmore.andmore.andmore):
214                dosomething(connection)
215        """)  # noqa
216    expected_formatted_code = textwrap.dedent("""\
217        if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbbb == ccccccccccccccccc and xxxxxxxxxxxxx
218                or yyyyyyyyyyyyyyyyy):
219            pass
220        elif (xxxxxxxxxxxxxxx(aaaaaaaaaaa,
221                              bbbbbbbbbbbbbb,
222                              cccccccccccc,
223                              dddddddddd=None)):
224            pass
225
226
227        def h():
228            if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
229                    xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
230                pass
231
232            for connection in itertools.chain(
233                    branch.contact, branch.address,
234                    morestuff.andmore.andmore.andmore.andmore.andmore.andmore.andmore):
235                dosomething(connection)
236        """)  # noqa
237    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
238    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
239
240  def testSplittingBeforeLogicalOperator(self):
241    try:
242      style.SetGlobalStyle(
243          style.CreateStyleFromConfig(
244              '{based_on_style: pep8, split_before_logical_operator: True}'))
245      unformatted_code = textwrap.dedent("""\
246          def foo():
247              return bool(update.message.new_chat_member or update.message.left_chat_member or
248                          update.message.new_chat_title or update.message.new_chat_photo or
249                          update.message.delete_chat_photo or update.message.group_chat_created or
250                          update.message.supergroup_chat_created or update.message.channel_chat_created
251                          or update.message.migrate_to_chat_id or update.message.migrate_from_chat_id or
252                          update.message.pinned_message)
253          """)  # noqa
254      expected_formatted_code = textwrap.dedent("""\
255          def foo():
256              return bool(
257                  update.message.new_chat_member or update.message.left_chat_member
258                  or update.message.new_chat_title or update.message.new_chat_photo
259                  or update.message.delete_chat_photo
260                  or update.message.group_chat_created
261                  or update.message.supergroup_chat_created
262                  or update.message.channel_chat_created
263                  or update.message.migrate_to_chat_id
264                  or update.message.migrate_from_chat_id
265                  or update.message.pinned_message)
266          """)  # noqa
267      llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
268      self.assertCodeEqual(expected_formatted_code,
269                           reformatter.Reformat(llines))
270    finally:
271      style.SetGlobalStyle(style.CreatePEP8Style())
272
273  def testContiguousListEndingWithComment(self):
274    unformatted_code = textwrap.dedent("""\
275        if True:
276            if True:
277                keys.append(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)  # may be unassigned.
278        """)  # noqa
279    expected_formatted_code = textwrap.dedent("""\
280        if True:
281            if True:
282                keys.append(
283                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)  # may be unassigned.
284        """)  # noqa
285    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
286    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
287
288  def testSplittingBeforeFirstArgument(self):
289    try:
290      style.SetGlobalStyle(
291          style.CreateStyleFromConfig(
292              '{based_on_style: pep8, split_before_first_argument: True}'))
293      unformatted_code = textwrap.dedent("""\
294          a_very_long_function_name(long_argument_name_1=1, long_argument_name_2=2,
295                                    long_argument_name_3=3, long_argument_name_4=4)
296          """)  # noqa
297      expected_formatted_code = textwrap.dedent("""\
298          a_very_long_function_name(
299              long_argument_name_1=1,
300              long_argument_name_2=2,
301              long_argument_name_3=3,
302              long_argument_name_4=4)
303          """)
304      llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
305      self.assertCodeEqual(expected_formatted_code,
306                           reformatter.Reformat(llines))
307    finally:
308      style.SetGlobalStyle(style.CreatePEP8Style())
309
310  def testSplittingExpressionsInsideSubscripts(self):
311    unformatted_code = textwrap.dedent("""\
312        def foo():
313            df = df[(df['campaign_status'] == 'LIVE') & (df['action_status'] == 'LIVE')]
314        """)  # noqa
315    expected_formatted_code = textwrap.dedent("""\
316        def foo():
317            df = df[(df['campaign_status'] == 'LIVE')
318                    & (df['action_status'] == 'LIVE')]
319        """)
320    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
321    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
322
323  def testSplitListsAndDictSetMakersIfCommaTerminated(self):
324    unformatted_code = textwrap.dedent("""\
325        DJANGO_TEMPLATES_OPTIONS = {"context_processors": []}
326        DJANGO_TEMPLATES_OPTIONS = {"context_processors": [],}
327        x = ["context_processors"]
328        x = ["context_processors",]
329        """)
330    expected_formatted_code = textwrap.dedent("""\
331        DJANGO_TEMPLATES_OPTIONS = {"context_processors": []}
332        DJANGO_TEMPLATES_OPTIONS = {
333            "context_processors": [],
334        }
335        x = ["context_processors"]
336        x = [
337            "context_processors",
338        ]
339        """)
340    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
341    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
342
343  def testSplitAroundNamedAssigns(self):
344    unformatted_code = textwrap.dedent("""\
345        class a():
346
347            def a(): return a(
348             aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)
349        """)
350    expected_formatted_code = textwrap.dedent("""\
351        class a():
352
353            def a():
354                return a(
355                    aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
356                )
357        """)
358    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
359    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
360
361  def testUnaryOperator(self):
362    unformatted_code = textwrap.dedent("""\
363        if not -3 < x < 3:
364          pass
365        if -3 < x < 3:
366          pass
367        """)
368    expected_formatted_code = textwrap.dedent("""\
369        if not -3 < x < 3:
370            pass
371        if -3 < x < 3:
372            pass
373        """)
374    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
375    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
376
377  def testNoSplitBeforeDictValue(self):
378    try:
379      style.SetGlobalStyle(
380          style.CreateStyleFromConfig('{based_on_style: pep8, '
381                                      'allow_split_before_dict_value: false, '
382                                      'coalesce_brackets: true, '
383                                      'dedent_closing_brackets: true, '
384                                      'each_dict_entry_on_separate_line: true, '
385                                      'split_before_logical_operator: true}'))
386
387      unformatted_code = textwrap.dedent("""\
388          some_dict = {
389              'title': _("I am example data"),
390              'description': _("Lorem ipsum dolor met sit amet elit, si vis pacem para bellum "
391                               "elites nihi very long string."),
392          }
393          """)  # noqa
394      expected_formatted_code = textwrap.dedent("""\
395          some_dict = {
396              'title': _("I am example data"),
397              'description': _(
398                  "Lorem ipsum dolor met sit amet elit, si vis pacem para bellum "
399                  "elites nihi very long string."
400              ),
401          }
402          """)  # noqa
403      llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
404      self.assertCodeEqual(expected_formatted_code,
405                           reformatter.Reformat(llines))
406
407      unformatted_code = textwrap.dedent("""\
408          X = {'a': 1, 'b': 2, 'key': this_is_a_function_call_that_goes_over_the_column_limit_im_pretty_sure()}
409          """)  # noqa
410      expected_formatted_code = textwrap.dedent("""\
411          X = {
412              'a': 1,
413              'b': 2,
414              'key': this_is_a_function_call_that_goes_over_the_column_limit_im_pretty_sure()
415          }
416          """)  # noqa
417      llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
418      self.assertCodeEqual(expected_formatted_code,
419                           reformatter.Reformat(llines))
420
421      unformatted_code = textwrap.dedent("""\
422          attrs = {
423              'category': category,
424              'role': forms.ModelChoiceField(label=_("Role"), required=False, queryset=category_roles, initial=selected_role, empty_label=_("No access"),),
425          }
426          """)  # noqa
427      expected_formatted_code = textwrap.dedent("""\
428          attrs = {
429              'category': category,
430              'role': forms.ModelChoiceField(
431                  label=_("Role"),
432                  required=False,
433                  queryset=category_roles,
434                  initial=selected_role,
435                  empty_label=_("No access"),
436              ),
437          }
438          """)
439      llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
440      self.assertCodeEqual(expected_formatted_code,
441                           reformatter.Reformat(llines))
442
443      unformatted_code = textwrap.dedent("""\
444          css_class = forms.CharField(
445              label=_("CSS class"),
446              required=False,
447              help_text=_("Optional CSS class used to customize this category appearance from templates."),
448          )
449          """)  # noqa
450      expected_formatted_code = textwrap.dedent("""\
451          css_class = forms.CharField(
452              label=_("CSS class"),
453              required=False,
454              help_text=_(
455                  "Optional CSS class used to customize this category appearance from templates."
456              ),
457          )
458          """)  # noqa
459      llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
460      self.assertCodeEqual(expected_formatted_code,
461                           reformatter.Reformat(llines))
462    finally:
463      style.SetGlobalStyle(style.CreatePEP8Style())
464
465  def testBitwiseOperandSplitting(self):
466    unformatted_code = """\
467def _():
468    include_values = np.where(
469                (cdffile['Quality_Flag'][:] >= 5) & (
470                cdffile['Day_Night_Flag'][:] == 1) & (
471                cdffile['Longitude'][:] >= select_lon - radius) & (
472                cdffile['Longitude'][:] <= select_lon + radius) & (
473                cdffile['Latitude'][:] >= select_lat - radius) & (
474                cdffile['Latitude'][:] <= select_lat + radius))
475"""
476    expected_code = """\
477def _():
478    include_values = np.where(
479        (cdffile['Quality_Flag'][:] >= 5) & (cdffile['Day_Night_Flag'][:] == 1)
480        & (cdffile['Longitude'][:] >= select_lon - radius)
481        & (cdffile['Longitude'][:] <= select_lon + radius)
482        & (cdffile['Latitude'][:] >= select_lat - radius)
483        & (cdffile['Latitude'][:] <= select_lat + radius))
484"""
485    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
486    self.assertEqual(expected_code, reformatter.Reformat(llines))
487
488  def testNoBlankLinesOnlyForFirstNestedObject(self):
489    unformatted_code = '''\
490class Demo:
491    """
492    Demo docs
493    """
494    def foo(self):
495        """
496        foo docs
497        """
498    def bar(self):
499        """
500        bar docs
501        """
502'''
503    expected_code = '''\
504class Demo:
505    """
506    Demo docs
507    """
508
509    def foo(self):
510        """
511        foo docs
512        """
513
514    def bar(self):
515        """
516        bar docs
517        """
518'''
519    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
520    self.assertEqual(expected_code, reformatter.Reformat(llines))
521
522  def testSplitBeforeArithmeticOperators(self):
523    try:
524      style.SetGlobalStyle(
525          style.CreateStyleFromConfig(
526              '{based_on_style: pep8, split_before_arithmetic_operator: true}'))
527
528      unformatted_code = """\
529def _():
530    raise ValueError('This is a long message that ends with an argument: ' + str(42))
531"""  # noqa
532      expected_formatted_code = """\
533def _():
534    raise ValueError('This is a long message that ends with an argument: '
535                     + str(42))
536"""
537      llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
538      self.assertCodeEqual(expected_formatted_code,
539                           reformatter.Reformat(llines))
540    finally:
541      style.SetGlobalStyle(style.CreatePEP8Style())
542
543  def testListSplitting(self):
544    unformatted_code = """\
545foo([(1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
546     (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
547     (1,10), (1,11), (1, 10), (1,11), (10,11)])
548"""
549    expected_code = """\
550foo([(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1),
551     (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 10), (1, 11), (1, 10),
552     (1, 11), (10, 11)])
553"""
554    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
555    self.assertCodeEqual(expected_code, reformatter.Reformat(llines))
556
557  def testNoBlankLineBeforeNestedFuncOrClass(self):
558    try:
559      style.SetGlobalStyle(
560          style.CreateStyleFromConfig(
561              '{based_on_style: pep8, '
562              'blank_line_before_nested_class_or_def: false}'))
563
564      unformatted_code = '''\
565def normal_function():
566    """Return the nested function."""
567
568    def nested_function():
569        """Do nothing just nest within."""
570
571        @nested(klass)
572        class nested_class():
573            pass
574
575        pass
576
577    return nested_function
578'''
579      expected_formatted_code = '''\
580def normal_function():
581    """Return the nested function."""
582    def nested_function():
583        """Do nothing just nest within."""
584        @nested(klass)
585        class nested_class():
586            pass
587
588        pass
589
590    return nested_function
591'''
592      llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
593      self.assertCodeEqual(expected_formatted_code,
594                           reformatter.Reformat(llines))
595    finally:
596      style.SetGlobalStyle(style.CreatePEP8Style())
597
598  def testParamListIndentationCollision1(self):
599    unformatted_code = textwrap.dedent("""\
600class _():
601
602    def __init__(self, title: Optional[str], diffs: Collection[BinaryDiff] = (), charset: Union[Type[AsciiCharset], Type[LineCharset]] = AsciiCharset, preprocess: Callable[[str], str] = identity,
603            # TODO(somebody): Make this a Literal type.
604            justify: str = 'rjust'):
605        self._cs = charset
606        self._preprocess = preprocess
607        """)  # noqa
608    expected_formatted_code = textwrap.dedent("""\
609class _():
610
611    def __init__(
612            self,
613            title: Optional[str],
614            diffs: Collection[BinaryDiff] = (),
615            charset: Union[Type[AsciiCharset],
616                           Type[LineCharset]] = AsciiCharset,
617            preprocess: Callable[[str], str] = identity,
618            # TODO(somebody): Make this a Literal type.
619            justify: str = 'rjust'):
620        self._cs = charset
621        self._preprocess = preprocess
622        """)
623    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
624    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
625
626  def testParamListIndentationCollision2(self):
627    code = textwrap.dedent("""\
628        def simple_pass_function_with_an_extremely_long_name_and_some_arguments(
629                argument0, argument1):
630            pass
631        """)
632    llines = yapf_test_helper.ParseAndUnwrap(code)
633    self.assertCodeEqual(code, reformatter.Reformat(llines))
634
635  def testParamListIndentationCollision3(self):
636    code = textwrap.dedent("""\
637        def func1(
638            arg1,
639            arg2,
640        ) -> None:
641            pass
642
643
644        def func2(
645            arg1,
646            arg2,
647        ):
648            pass
649        """)
650    llines = yapf_test_helper.ParseAndUnwrap(code)
651    self.assertCodeEqual(code, reformatter.Reformat(llines))
652
653  def testTwoWordComparisonOperators(self):
654    unformatted_code = textwrap.dedent("""\
655        _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl is not ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj)
656        _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl not in {ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj})
657        """)  # noqa
658    expected_formatted_code = textwrap.dedent("""\
659        _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl
660             is not ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj)
661        _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl
662             not in {ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj})
663        """)
664    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
665    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
666
667  @unittest.skipUnless(not py3compat.PY3, 'Requires Python 2.7')
668  def testAsyncAsNonKeyword(self):
669    # In Python 2, async may be used as a non-keyword identifier.
670    code = textwrap.dedent("""\
671        from util import async
672
673
674        class A(object):
675
676            def foo(self):
677                async.run()
678
679            def bar(self):
680                pass
681        """)
682    llines = yapf_test_helper.ParseAndUnwrap(code)
683    self.assertCodeEqual(code, reformatter.Reformat(llines, verify=False))
684
685  def testStableInlinedDictionaryFormatting(self):
686    unformatted_code = textwrap.dedent("""\
687        def _():
688            url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
689                value, urllib.urlencode({'action': 'update', 'parameter': value}))
690        """)  # noqa
691    expected_formatted_code = textwrap.dedent("""\
692        def _():
693            url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
694                value, urllib.urlencode({
695                    'action': 'update',
696                    'parameter': value
697                }))
698        """)
699
700    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
701    reformatted_code = reformatter.Reformat(llines)
702    self.assertCodeEqual(expected_formatted_code, reformatted_code)
703
704    llines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
705    reformatted_code = reformatter.Reformat(llines)
706    self.assertCodeEqual(expected_formatted_code, reformatted_code)
707
708  @unittest.skipUnless(py3compat.PY36, 'Requires Python 3.6')
709  def testSpaceBetweenColonAndElipses(self):
710    style.SetGlobalStyle(style.CreatePEP8Style())
711    code = textwrap.dedent("""\
712      class MyClass(ABC):
713
714          place: ...
715    """)
716    llines = yapf_test_helper.ParseAndUnwrap(code)
717    self.assertCodeEqual(code, reformatter.Reformat(llines, verify=False))
718
719  @unittest.skipUnless(py3compat.PY36, 'Requires Python 3.6')
720  def testSpaceBetweenDictColonAndElipses(self):
721    style.SetGlobalStyle(style.CreatePEP8Style())
722    unformatted_code = textwrap.dedent("""\
723      {0:"...", 1:...}
724    """)
725    expected_formatted_code = textwrap.dedent("""\
726      {0: "...", 1: ...}
727    """)
728
729    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
730    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
731
732
733class TestsForSpacesInsideBrackets(yapf_test_helper.YAPFTest):
734  """Test the SPACE_INSIDE_BRACKETS style option."""
735  unformatted_code = textwrap.dedent("""\
736    foo()
737    foo(1)
738    foo(1,2)
739    foo((1,))
740    foo((1, 2))
741    foo((1, 2,))
742    foo(bar['baz'][0])
743    set1 = {1, 2, 3}
744    dict1 = {1: 1, foo: 2, 3: bar}
745    dict2 = {
746        1: 1,
747        foo: 2,
748        3: bar,
749    }
750    dict3[3][1][get_index(*args,**kwargs)]
751    dict4[3][1][get_index(**kwargs)]
752    x = dict5[4](foo(*args))
753    a = list1[:]
754    b = list2[slice_start:]
755    c = list3[slice_start:slice_end]
756    d = list4[slice_start:slice_end:]
757    e = list5[slice_start:slice_end:slice_step]
758    # Print gets special handling
759    print(set2)
760    compound = ((10+3)/(5-2**(6+x)))
761    string_idx = "mystring"[3]
762    """)
763
764  def testEnabled(self):
765    style.SetGlobalStyle(
766        style.CreateStyleFromConfig('{space_inside_brackets: True}'))
767
768    expected_formatted_code = textwrap.dedent("""\
769      foo()
770      foo( 1 )
771      foo( 1, 2 )
772      foo( ( 1, ) )
773      foo( ( 1, 2 ) )
774      foo( (
775          1,
776          2,
777      ) )
778      foo( bar[ 'baz' ][ 0 ] )
779      set1 = { 1, 2, 3 }
780      dict1 = { 1: 1, foo: 2, 3: bar }
781      dict2 = {
782          1: 1,
783          foo: 2,
784          3: bar,
785      }
786      dict3[ 3 ][ 1 ][ get_index( *args, **kwargs ) ]
787      dict4[ 3 ][ 1 ][ get_index( **kwargs ) ]
788      x = dict5[ 4 ]( foo( *args ) )
789      a = list1[ : ]
790      b = list2[ slice_start: ]
791      c = list3[ slice_start:slice_end ]
792      d = list4[ slice_start:slice_end: ]
793      e = list5[ slice_start:slice_end:slice_step ]
794      # Print gets special handling
795      print( set2 )
796      compound = ( ( 10 + 3 ) / ( 5 - 2**( 6 + x ) ) )
797      string_idx = "mystring"[ 3 ]
798      """)
799
800    llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
801    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
802
803  def testDefault(self):
804    style.SetGlobalStyle(style.CreatePEP8Style())
805
806    expected_formatted_code = textwrap.dedent("""\
807      foo()
808      foo(1)
809      foo(1, 2)
810      foo((1, ))
811      foo((1, 2))
812      foo((
813          1,
814          2,
815      ))
816      foo(bar['baz'][0])
817      set1 = {1, 2, 3}
818      dict1 = {1: 1, foo: 2, 3: bar}
819      dict2 = {
820          1: 1,
821          foo: 2,
822          3: bar,
823      }
824      dict3[3][1][get_index(*args, **kwargs)]
825      dict4[3][1][get_index(**kwargs)]
826      x = dict5[4](foo(*args))
827      a = list1[:]
828      b = list2[slice_start:]
829      c = list3[slice_start:slice_end]
830      d = list4[slice_start:slice_end:]
831      e = list5[slice_start:slice_end:slice_step]
832      # Print gets special handling
833      print(set2)
834      compound = ((10 + 3) / (5 - 2**(6 + x)))
835      string_idx = "mystring"[3]
836      """)
837
838    llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
839    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
840
841  @unittest.skipUnless(py3compat.PY36, 'Requires Python 3.6')
842  def testAwait(self):
843    style.SetGlobalStyle(
844        style.CreateStyleFromConfig('{space_inside_brackets: True}'))
845    unformatted_code = textwrap.dedent("""\
846      import asyncio
847      import time
848
849      @print_args
850      async def slow_operation():
851        await asyncio.sleep(1)
852        # print("Slow operation {} complete".format(n))
853        async def main():
854          start = time.time()
855          if (await get_html()):
856            pass
857      """)
858    expected_formatted_code = textwrap.dedent("""\
859      import asyncio
860      import time
861
862
863      @print_args
864      async def slow_operation():
865          await asyncio.sleep( 1 )
866
867          # print("Slow operation {} complete".format(n))
868          async def main():
869              start = time.time()
870              if ( await get_html() ):
871                  pass
872      """)
873    llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
874    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
875
876
877class TestsForSpacesAroundSubscriptColon(yapf_test_helper.YAPFTest):
878  """Test the SPACES_AROUND_SUBSCRIPT_COLON style option."""
879  unformatted_code = textwrap.dedent("""\
880    a = list1[ : ]
881    b = list2[ slice_start: ]
882    c = list3[ slice_start:slice_end ]
883    d = list4[ slice_start:slice_end: ]
884    e = list5[ slice_start:slice_end:slice_step ]
885    a1 = list1[ : ]
886    b1 = list2[ 1: ]
887    c1 = list3[ 1:20 ]
888    d1 = list4[ 1:20: ]
889    e1 = list5[ 1:20:3 ]
890  """)
891
892  def testEnabled(self):
893    style.SetGlobalStyle(
894        style.CreateStyleFromConfig('{spaces_around_subscript_colon: True}'))
895    expected_formatted_code = textwrap.dedent("""\
896      a = list1[:]
897      b = list2[slice_start :]
898      c = list3[slice_start : slice_end]
899      d = list4[slice_start : slice_end :]
900      e = list5[slice_start : slice_end : slice_step]
901      a1 = list1[:]
902      b1 = list2[1 :]
903      c1 = list3[1 : 20]
904      d1 = list4[1 : 20 :]
905      e1 = list5[1 : 20 : 3]
906    """)
907    llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
908    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
909
910  def testWithSpaceInsideBrackets(self):
911    style.SetGlobalStyle(
912        style.CreateStyleFromConfig('{'
913                                    'spaces_around_subscript_colon: true, '
914                                    'space_inside_brackets: true,'
915                                    '}'))
916    expected_formatted_code = textwrap.dedent("""\
917      a = list1[ : ]
918      b = list2[ slice_start : ]
919      c = list3[ slice_start : slice_end ]
920      d = list4[ slice_start : slice_end : ]
921      e = list5[ slice_start : slice_end : slice_step ]
922      a1 = list1[ : ]
923      b1 = list2[ 1 : ]
924      c1 = list3[ 1 : 20 ]
925      d1 = list4[ 1 : 20 : ]
926      e1 = list5[ 1 : 20 : 3 ]
927    """)
928    llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
929    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
930
931  def testDefault(self):
932    style.SetGlobalStyle(style.CreatePEP8Style())
933    expected_formatted_code = textwrap.dedent("""\
934      a = list1[:]
935      b = list2[slice_start:]
936      c = list3[slice_start:slice_end]
937      d = list4[slice_start:slice_end:]
938      e = list5[slice_start:slice_end:slice_step]
939      a1 = list1[:]
940      b1 = list2[1:]
941      c1 = list3[1:20]
942      d1 = list4[1:20:]
943      e1 = list5[1:20:3]
944    """)
945    llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
946    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
947
948
949if __name__ == '__main__':
950  unittest.main()
951