1 # -*- coding: utf-8 -*-
2 # Copyright 2015 Google Inc. All Rights Reserved.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 """Tests for yapf.yapf."""
26 from io
import StringIO
28 from yapf_third_party
._ylib
2to
3.pgen2
import tokenize
30 from yapf
.yapflib
import errors
31 from yapf
.yapflib
import style
32 from yapf
.yapflib
import yapf_api
34 from yapftests
import utils
35 from yapftests
import yapf_test_helper
37 YAPF_BINARY
= [sys
.executable
, '-m', 'yapf', '--no-local-style']
40 class FormatCodeTest(yapf_test_helper
.YAPFTest
):
42 def _Check(self
, unformatted_code
, expected_formatted_code
):
43 formatted_code
, _
= yapf_api
.FormatCode(
44 unformatted_code
, style_config
='yapf')
45 self
.assertCodeEqual(expected_formatted_code
, formatted_code
)
48 unformatted_code
= textwrap
.dedent("""\
51 self
._Check
(unformatted_code
, unformatted_code
)
53 def testNoEndingNewline(self
):
54 unformatted_code
= textwrap
.dedent("""\
57 expected_formatted_code
= textwrap
.dedent("""\
61 self
._Check
(unformatted_code
, expected_formatted_code
)
64 class FormatFileTest(yapf_test_helper
.YAPFTest
):
66 def setUp(self
): # pylint: disable=g-missing-super-call
67 self
.test_tmpdir
= tempfile
.mkdtemp()
69 def tearDown(self
): # pylint: disable=g-missing-super-call
70 shutil
.rmtree(self
.test_tmpdir
)
72 def testFormatFile(self
):
73 unformatted_code
= textwrap
.dedent("""\
77 expected_formatted_code_pep8
= textwrap
.dedent("""\
81 expected_formatted_code_yapf
= textwrap
.dedent("""\
85 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
86 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
87 self
.assertCodeEqual(expected_formatted_code_pep8
, formatted_code
)
89 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='yapf')
90 self
.assertCodeEqual(expected_formatted_code_yapf
, formatted_code
)
92 def testDisableLinesPattern(self
):
93 unformatted_code
= textwrap
.dedent("""\
101 expected_formatted_code
= textwrap
.dedent("""\
109 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
110 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
111 self
.assertCodeEqual(expected_formatted_code
, formatted_code
)
113 def testDisableAndReenableLinesPattern(self
):
114 unformatted_code
= textwrap
.dedent("""\
123 expected_formatted_code
= textwrap
.dedent("""\
132 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
133 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
134 self
.assertCodeEqual(expected_formatted_code
, formatted_code
)
136 def testFmtOnOff(self
):
137 unformatted_code
= textwrap
.dedent("""\
146 expected_formatted_code
= textwrap
.dedent("""\
155 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
156 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
157 self
.assertCodeEqual(expected_formatted_code
, formatted_code
)
159 def testDisablePartOfMultilineComment(self
):
160 unformatted_code
= textwrap
.dedent("""\
163 # This is a multiline comment that disables YAPF.
167 # This is a multiline comment that enables YAPF.
171 expected_formatted_code
= textwrap
.dedent("""\
174 # This is a multiline comment that disables YAPF.
178 # This is a multiline comment that enables YAPF.
182 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
183 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
184 self
.assertCodeEqual(expected_formatted_code
, formatted_code
)
186 code
= textwrap
.dedent("""\
198 with utils
.TempFileContents(self
.test_tmpdir
, code
) as filepath
:
199 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
200 self
.assertCodeEqual(code
, formatted_code
)
202 def testEnabledDisabledSameComment(self
):
203 code
= textwrap
.dedent("""\
205 a(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, ccccccccccccccccccccccccccccccc, ddddddddddddddddddddddd, eeeeeeeeeeeeeeeeeeeeeeeeeee)
208 a(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, ccccccccccccccccccccccccccccccc, ddddddddddddddddddddddd, eeeeeeeeeeeeeeeeeeeeeeeeeee)
211 with utils
.TempFileContents(self
.test_tmpdir
, code
) as filepath
:
212 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
213 self
.assertCodeEqual(code
, formatted_code
)
215 def testFormatFileLinesSelection(self
):
216 unformatted_code
= textwrap
.dedent("""\
223 expected_formatted_code_lines1and2
= textwrap
.dedent("""\
230 expected_formatted_code_lines3
= textwrap
.dedent("""\
237 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
238 formatted_code
, _
, _
= yapf_api
.FormatFile(
239 filepath
, style_config
='pep8', lines
=[(1, 2)])
240 self
.assertCodeEqual(expected_formatted_code_lines1and2
, formatted_code
)
241 formatted_code
, _
, _
= yapf_api
.FormatFile(
242 filepath
, style_config
='pep8', lines
=[(3, 3)])
243 self
.assertCodeEqual(expected_formatted_code_lines3
, formatted_code
)
245 def testFormatFileDiff(self
):
246 unformatted_code
= textwrap
.dedent("""\
250 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
251 diff
, _
, _
= yapf_api
.FormatFile(filepath
, print_diff
=True)
252 self
.assertIn('+ pass', diff
)
254 def testFormatFileInPlace(self
):
255 unformatted_code
= 'True==False\n'
256 formatted_code
= 'True == False\n'
257 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
258 result
, _
, _
= yapf_api
.FormatFile(filepath
, in_place
=True)
259 self
.assertEqual(result
, None)
260 with
open(filepath
) as fd
:
261 self
.assertCodeEqual(formatted_code
, fd
.read())
270 def testNoFile(self
):
271 with self
.assertRaises(IOError) as context
:
272 yapf_api
.FormatFile('not_a_file.py')
275 str(context
.exception
),
276 "[Errno 2] No such file or directory: 'not_a_file.py'")
278 def testCommentsUnformatted(self
):
279 code
= textwrap
.dedent("""\
280 foo = [# A list of things
284 'two'] # yapf: disable
286 with utils
.TempFileContents(self
.test_tmpdir
, code
) as filepath
:
287 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
288 self
.assertCodeEqual(code
, formatted_code
)
290 def testDisabledHorizontalFormattingOnNewLine(self
):
291 code
= textwrap
.dedent("""\
297 with utils
.TempFileContents(self
.test_tmpdir
, code
) as filepath
:
298 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
299 self
.assertCodeEqual(code
, formatted_code
)
301 def testSplittingSemicolonStatements(self
):
302 unformatted_code
= textwrap
.dedent("""\
304 x = y + 42 ; z = n * 42
305 if True: a += 1 ; b += 1; c += 1
307 expected_formatted_code
= textwrap
.dedent("""\
316 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
317 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
318 self
.assertCodeEqual(expected_formatted_code
, formatted_code
)
320 def testSemicolonStatementsDisabled(self
):
321 unformatted_code
= textwrap
.dedent("""\
323 x = y + 42 ; z = n * 42 # yapf: disable
324 if True: a += 1 ; b += 1; c += 1
326 expected_formatted_code
= textwrap
.dedent("""\
328 x = y + 42 ; z = n * 42 # yapf: disable
334 with utils
.TempFileContents(self
.test_tmpdir
, unformatted_code
) as filepath
:
335 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
336 self
.assertCodeEqual(expected_formatted_code
, formatted_code
)
338 def testDisabledSemiColonSeparatedStatements(self
):
339 code
= textwrap
.dedent("""\
343 with utils
.TempFileContents(self
.test_tmpdir
, code
) as filepath
:
344 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='pep8')
345 self
.assertCodeEqual(code
, formatted_code
)
347 def testDisabledMultilineStringInDictionary(self
):
348 code
= textwrap
.dedent("""\
353 "aaaaaaaaaaaaaaaaaaa": '''
354 bbbbbbbbbbb: "ccccccccccc"
357 ffffffffff: "ggggggg"
362 with utils
.TempFileContents(self
.test_tmpdir
, code
) as filepath
:
363 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='yapf')
364 self
.assertCodeEqual(code
, formatted_code
)
366 def testDisabledWithPrecedingText(self
):
367 code
= textwrap
.dedent("""\
368 # TODO(fix formatting): yapf: disable
372 "aaaaaaaaaaaaaaaaaaa": '''
373 bbbbbbbbbbb: "ccccccccccc"
376 ffffffffff: "ggggggg"
381 with utils
.TempFileContents(self
.test_tmpdir
, code
) as filepath
:
382 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='yapf')
383 self
.assertCodeEqual(code
, formatted_code
)
385 def testCRLFLineEnding(self
):
386 code
= 'class _():\r\n pass\r\n'
387 with utils
.TempFileContents(self
.test_tmpdir
, code
) as filepath
:
388 formatted_code
, _
, _
= yapf_api
.FormatFile(filepath
, style_config
='yapf')
389 self
.assertCodeEqual(code
, formatted_code
)
392 class CommandLineTest(yapf_test_helper
.YAPFTest
):
393 """Test how calling yapf from the command line acts."""
396 def setUpClass(cls
): # pylint: disable=g-missing-super-call
397 cls
.test_tmpdir
= tempfile
.mkdtemp()
400 def tearDownClass(cls
): # pylint: disable=g-missing-super-call
401 shutil
.rmtree(cls
.test_tmpdir
)
403 def assertYapfReformats(self
,
408 """Check that yapf reformats the given code as expected.
410 Invokes yapf in a subprocess, piping the unformatted code into its stdin.
411 Checks that the formatted output is as expected.
414 unformatted: unformatted code - input to yapf
415 expected: expected formatted code at the output of yapf
416 extra_options: iterable of extra command-line options to pass to yapf
417 env: dict of environment variables.
419 cmdline
= YAPF_BINARY
+ (extra_options
or [])
420 p
= subprocess
.Popen(
422 stdout
=subprocess
.PIPE
,
423 stdin
=subprocess
.PIPE
,
424 stderr
=subprocess
.PIPE
,
426 reformatted_code
, stderrdata
= p
.communicate(
427 unformatted
.encode('utf-8-sig'))
428 self
.assertEqual(stderrdata
, b
'')
429 self
.assertMultiLineEqual(reformatted_code
.decode('utf-8'), expected
)
431 def testInPlaceReformatting(self
):
432 unformatted_code
= textwrap
.dedent("""\
436 expected_formatted_code
= textwrap
.dedent("""\
440 with utils
.TempFileContents(
441 self
.test_tmpdir
, unformatted_code
, suffix
='.py') as filepath
:
442 p
= subprocess
.Popen(YAPF_BINARY
+ ['--in-place', filepath
])
444 with io
.open(filepath
, mode
='r', newline
='') as fd
:
445 reformatted_code
= fd
.read()
446 self
.assertEqual(reformatted_code
, expected_formatted_code
)
448 def testInPlaceReformattingBlank(self
):
449 unformatted_code
= '\n\n'
450 expected_formatted_code
= '\n'
451 with utils
.TempFileContents(
452 self
.test_tmpdir
, unformatted_code
, suffix
='.py') as filepath
:
453 p
= subprocess
.Popen(YAPF_BINARY
+ ['--in-place', filepath
])
455 with io
.open(filepath
, mode
='r', encoding
='utf-8', newline
='') as fd
:
456 reformatted_code
= fd
.read()
457 self
.assertEqual(reformatted_code
, expected_formatted_code
)
459 def testInPlaceReformattingWindowsNewLine(self
):
460 unformatted_code
= '\r\n\r\n'
461 expected_formatted_code
= '\r\n'
462 with utils
.TempFileContents(
463 self
.test_tmpdir
, unformatted_code
, suffix
='.py') as filepath
:
464 p
= subprocess
.Popen(YAPF_BINARY
+ ['--in-place', filepath
])
466 with io
.open(filepath
, mode
='r', encoding
='utf-8', newline
='') as fd
:
467 reformatted_code
= fd
.read()
468 self
.assertEqual(reformatted_code
, expected_formatted_code
)
470 def testInPlaceReformattingNoNewLine(self
):
471 unformatted_code
= textwrap
.dedent('def foo(): x = 37')
472 expected_formatted_code
= textwrap
.dedent("""\
476 with utils
.TempFileContents(
477 self
.test_tmpdir
, unformatted_code
, suffix
='.py') as filepath
:
478 p
= subprocess
.Popen(YAPF_BINARY
+ ['--in-place', filepath
])
480 with io
.open(filepath
, mode
='r', newline
='') as fd
:
481 reformatted_code
= fd
.read()
482 self
.assertEqual(reformatted_code
, expected_formatted_code
)
484 def testInPlaceReformattingEmpty(self
):
485 unformatted_code
= ''
486 expected_formatted_code
= ''
487 with utils
.TempFileContents(
488 self
.test_tmpdir
, unformatted_code
, suffix
='.py') as filepath
:
489 p
= subprocess
.Popen(YAPF_BINARY
+ ['--in-place', filepath
])
491 with io
.open(filepath
, mode
='r', encoding
='utf-8', newline
='') as fd
:
492 reformatted_code
= fd
.read()
493 self
.assertEqual(reformatted_code
, expected_formatted_code
)
495 def testPrintModified(self
):
496 for unformatted_code
, has_change
in [('1==2', True), ('1 == 2', False)]:
497 with utils
.TempFileContents(
498 self
.test_tmpdir
, unformatted_code
, suffix
='.py') as filepath
:
499 output
= subprocess
.check_output(
500 YAPF_BINARY
+ ['--in-place', '--print-modified', filepath
],
502 check
= self
.assertIn
if has_change
else self
.assertNotIn
503 check(f
'Formatted {filepath}', output
)
505 def testReadFromStdin(self
):
506 unformatted_code
= textwrap
.dedent("""\
510 expected_formatted_code
= textwrap
.dedent("""\
514 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
516 def testReadFromStdinWithEscapedStrings(self
):
517 unformatted_code
= textwrap
.dedent("""\
520 expected_formatted_code
= textwrap
.dedent("""\
523 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
525 def testSetYapfStyle(self
):
526 unformatted_code
= textwrap
.dedent("""\
530 expected_formatted_code
= textwrap
.dedent("""\
534 self
.assertYapfReformats(
536 expected_formatted_code
,
537 extra_options
=['--style=yapf'])
539 def testSetCustomStyleBasedOnYapf(self
):
540 unformatted_code
= textwrap
.dedent("""\
544 expected_formatted_code
= textwrap
.dedent("""\
548 style_file
= textwrap
.dedent("""\
550 based_on_style = yapf
551 spaces_before_comment = 4
553 with utils
.TempFileContents(self
.test_tmpdir
, style_file
) as stylepath
:
554 self
.assertYapfReformats(
556 expected_formatted_code
,
557 extra_options
=['--style={0}'.format(stylepath
)])
559 def testSetCustomStyleSpacesBeforeComment(self
):
560 unformatted_code
= textwrap
.dedent("""\
561 a_very_long_statement_that_extends_way_beyond # Comment
562 short # This is a shorter statement
564 expected_formatted_code
= textwrap
.dedent("""\
565 a_very_long_statement_that_extends_way_beyond # Comment
566 short # This is a shorter statement
568 style_file
= textwrap
.dedent("""\
570 spaces_before_comment = 15, 20
572 with utils
.TempFileContents(self
.test_tmpdir
, style_file
) as stylepath
:
573 self
.assertYapfReformats(
575 expected_formatted_code
,
576 extra_options
=['--style={0}'.format(stylepath
)])
578 def testReadSingleLineCodeFromStdin(self
):
579 unformatted_code
= textwrap
.dedent("""\
582 expected_formatted_code
= textwrap
.dedent("""\
585 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
587 def testEncodingVerification(self
):
588 unformatted_code
= textwrap
.dedent("""\
589 '''The module docstring.'''
590 # -*- coding: utf-8 -*-
595 with utils
.NamedTempFile(
596 suffix
='.py', dirname
=self
.test_tmpdir
) as (out
, _
):
597 with utils
.TempFileContents(
598 self
.test_tmpdir
, unformatted_code
, suffix
='.py') as filepath
:
600 subprocess
.check_call(YAPF_BINARY
+ ['--diff', filepath
], stdout
=out
)
601 except subprocess
.CalledProcessError
as e
:
602 # Indicates the text changed.
603 self
.assertEqual(e
.returncode
, 1) # pylint: disable=g-assert-in-except # noqa
605 def testReformattingSpecificLines(self
):
606 unformatted_code
= textwrap
.dedent("""\
608 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
613 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
616 expected_formatted_code
= textwrap
.dedent("""\
618 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
619 xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
624 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
627 # TODO(ambv): the `expected_formatted_code` here is not PEP8 compliant,
628 # raising "E129 visually indented line with same indent as next logical
630 self
.assertYapfReformats(
632 expected_formatted_code
,
633 extra_options
=['--lines', '1-2'])
635 def testOmitFormattingLinesBeforeDisabledFunctionComment(self
):
636 unformatted_code
= textwrap
.dedent("""\
641 x = ["badly" , "formatted","line" ]
643 expected_formatted_code
= textwrap
.dedent("""\
648 x = ["badly", "formatted", "line"]
650 self
.assertYapfReformats(
652 expected_formatted_code
,
653 extra_options
=['--lines', '5-5'])
655 def testReformattingSkippingLines(self
):
656 unformatted_code
= textwrap
.dedent("""\
658 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
663 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
667 expected_formatted_code
= textwrap
.dedent("""\
669 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
670 xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
676 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
680 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
682 def testReformattingSkippingToEndOfFile(self
):
683 unformatted_code
= textwrap
.dedent("""\
685 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
690 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
695 while (xxxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa' and
696 xxxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) ==
700 expected_formatted_code
= textwrap
.dedent("""\
702 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
703 xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
709 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
714 while (xxxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa' and
715 xxxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) ==
719 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
721 def testReformattingSkippingSingleLine(self
):
722 unformatted_code
= textwrap
.dedent("""\
724 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
728 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'): # yapf: disable
731 expected_formatted_code
= textwrap
.dedent("""\
733 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
734 xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
739 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'): # yapf: disable
742 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
744 def testDisableWholeDataStructure(self
):
745 unformatted_code
= textwrap
.dedent("""\
751 expected_formatted_code
= textwrap
.dedent("""\
757 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
759 def testDisableButAdjustIndentations(self
):
760 unformatted_code
= textwrap
.dedent("""\
761 class SplitPenaltyTest(unittest.TestCase):
763 def testUnbreakable(self):
764 self._CheckPenalties(tree, [
767 expected_formatted_code
= textwrap
.dedent("""\
768 class SplitPenaltyTest(unittest.TestCase):
770 def testUnbreakable(self):
771 self._CheckPenalties(tree, [
774 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
776 def testRetainingHorizontalWhitespace(self
):
777 unformatted_code
= textwrap
.dedent("""\
779 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
783 if (xxxxxxxxxxxx.yyyyyyyy (zzzzzzzzzzzzz [0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'): # yapf: disable
786 expected_formatted_code
= textwrap
.dedent("""\
788 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
789 xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
794 if (xxxxxxxxxxxx.yyyyyyyy (zzzzzzzzzzzzz [0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'): # yapf: disable
797 self
.assertYapfReformats(unformatted_code
, expected_formatted_code
)
799 def testRetainingVerticalWhitespace(self
):
800 unformatted_code
= textwrap
.dedent("""\
802 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
808 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
812 expected_formatted_code
= textwrap
.dedent("""\
814 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
815 xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
821 if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
825 self
.assertYapfReformats(
827 expected_formatted_code
,
828 extra_options
=['--lines', '1-2'])
830 unformatted_code
= textwrap
.dedent("""\
845 # trailing whitespace
847 expected_formatted_code
= textwrap
.dedent("""\
860 # trailing whitespace
862 self
.assertYapfReformats(
864 expected_formatted_code
,
865 extra_options
=['--lines', '3-3', '--lines', '13-13'])
867 unformatted_code
= textwrap
.dedent("""\
876 self
.assertYapfReformats(
877 unformatted_code
, unformatted_code
, extra_options
=['--lines', '2-2'])
879 def testVerticalSpacingWithCommentWithContinuationMarkers(self
):
880 unformatted_code
= textwrap
.dedent("""\
888 expected_formatted_code
= textwrap
.dedent("""\
896 self
.assertYapfReformats(
898 expected_formatted_code
,
899 extra_options
=['--lines', '1-1'])
901 def testRetainingSemicolonsWhenSpecifyingLines(self
):
902 unformatted_code
= textwrap
.dedent("""\
905 x = y + 42; z = n * 42
906 if True: a += 1 ; b += 1 ; c += 1
908 expected_formatted_code
= textwrap
.dedent("""\
911 x = y + 42; z = n * 42
912 if True: a += 1 ; b += 1 ; c += 1
914 self
.assertYapfReformats(
916 expected_formatted_code
,
917 extra_options
=['--lines', '1-1'])
919 def testDisabledMultilineStrings(self
):
920 unformatted_code
= textwrap
.dedent('''\
923 email_text += """<html>This is a really long docstring that goes over the column limit and is multi-line.<br><br>
924 <b>Czar: </b>"""+despot["Nicholas"]+"""<br>
925 <b>Minion: </b>"""+serf["Dmitri"]+"""<br>
926 <b>Residence: </b>"""+palace["Winter"]+"""<br>
930 expected_formatted_code
= textwrap
.dedent('''\
933 email_text += """<html>This is a really long docstring that goes over the column limit and is multi-line.<br><br>
934 <b>Czar: </b>"""+despot["Nicholas"]+"""<br>
935 <b>Minion: </b>"""+serf["Dmitri"]+"""<br>
936 <b>Residence: </b>"""+palace["Winter"]+"""<br>
940 self
.assertYapfReformats(
942 expected_formatted_code
,
943 extra_options
=['--lines', '1-1'])
945 def testDisableWhenSpecifyingLines(self
):
946 unformatted_code
= textwrap
.dedent("""\
958 expected_formatted_code
= textwrap
.dedent("""\
970 self
.assertYapfReformats(
972 expected_formatted_code
,
973 extra_options
=['--lines', '1-10'])
975 def testDisableFormattingInDataLiteral(self
):
976 unformatted_code
= textwrap
.dedent("""\
986 def still_horrible():
995 expected_formatted_code
= textwrap
.dedent("""\
1005 def still_horrible():
1010 self
.assertYapfReformats(
1012 expected_formatted_code
,
1013 extra_options
=['--lines', '14-15'])
1015 def testRetainVerticalFormattingBetweenDisabledAndEnabledLines(self
):
1016 unformatted_code
= textwrap
.dedent("""\
1018 def aaaaaaaaaaaaa(self):
1019 c = bbbbbbbbb.ccccccccc('challenge', 0, 1, 10)
1021 ('ddddddddddddddddddddddddd',
1022 'eeeeeeeeeeeeeeeeeeeeeeeee.%s' %
1024 gggggggggggg.hhhhhhhhh(c, c.ffffffffffff))
1025 iiiii = jjjjjjjjjjjjjj.iiiii
1027 expected_formatted_code
= textwrap
.dedent("""\
1029 def aaaaaaaaaaaaa(self):
1030 c = bbbbbbbbb.ccccccccc('challenge', 0, 1, 10)
1031 self.assertEqual(('ddddddddddddddddddddddddd',
1032 'eeeeeeeeeeeeeeeeeeeeeeeee.%s' % c.ffffffffffff),
1033 gggggggggggg.hhhhhhhhh(c, c.ffffffffffff))
1034 iiiii = jjjjjjjjjjjjjj.iiiii
1036 self
.assertYapfReformats(
1038 expected_formatted_code
,
1039 extra_options
=['--lines', '4-7'])
1041 def testRetainVerticalFormattingBetweenDisabledLines(self
):
1042 unformatted_code
= textwrap
.dedent("""\
1044 def aaaaaaaaaaaaa(self):
1048 def bbbbbbbbbbbbb(self): # 5
1051 expected_formatted_code
= textwrap
.dedent("""\
1053 def aaaaaaaaaaaaa(self):
1057 def bbbbbbbbbbbbb(self): # 5
1060 self
.assertYapfReformats(
1062 expected_formatted_code
,
1063 extra_options
=['--lines', '4-4'])
1065 def testFormatLinesSpecifiedInMiddleOfExpression(self
):
1066 unformatted_code
= textwrap
.dedent("""\
1068 def aaaaaaaaaaaaa(self):
1069 c = bbbbbbbbb.ccccccccc('challenge', 0, 1, 10)
1071 ('ddddddddddddddddddddddddd',
1072 'eeeeeeeeeeeeeeeeeeeeeeeee.%s' %
1074 gggggggggggg.hhhhhhhhh(c, c.ffffffffffff))
1075 iiiii = jjjjjjjjjjjjjj.iiiii
1077 expected_formatted_code
= textwrap
.dedent("""\
1079 def aaaaaaaaaaaaa(self):
1080 c = bbbbbbbbb.ccccccccc('challenge', 0, 1, 10)
1081 self.assertEqual(('ddddddddddddddddddddddddd',
1082 'eeeeeeeeeeeeeeeeeeeeeeeee.%s' % c.ffffffffffff),
1083 gggggggggggg.hhhhhhhhh(c, c.ffffffffffff))
1084 iiiii = jjjjjjjjjjjjjj.iiiii
1086 self
.assertYapfReformats(
1088 expected_formatted_code
,
1089 extra_options
=['--lines', '5-6'])
1091 def testCommentFollowingMultilineString(self
):
1092 unformatted_code
= textwrap
.dedent("""\
1097 x = '''hello world''' # second comment
1098 return 42 # another comment
1100 expected_formatted_code
= textwrap
.dedent("""\
1105 x = '''hello world''' # second comment
1106 return 42 # another comment
1108 self
.assertYapfReformats(
1110 expected_formatted_code
,
1111 extra_options
=['--lines', '1-1'])
1113 def testDedentClosingBracket(self
):
1114 # no line-break on the first argument, not dedenting closing brackets
1115 unformatted_code
= textwrap
.dedent("""\
1116 def overly_long_function_name(first_argument_on_the_same_line,
1117 second_argument_makes_the_line_too_long):
1120 expected_formatted_code
= textwrap
.dedent("""\
1121 def overly_long_function_name(first_argument_on_the_same_line,
1122 second_argument_makes_the_line_too_long):
1125 self
.assertYapfReformats(
1127 expected_formatted_code
,
1128 extra_options
=['--style=pep8'])
1130 # TODO(ambv): currently the following produces the closing bracket on a new
1131 # line but indented to the opening bracket which is the worst of both
1132 # worlds. Expected behaviour would be to format as --style=pep8 does in
1134 # self.assertYapfReformats(unformatted_code, expected_formatted_code,
1135 # extra_options=['--style=facebook'])
1137 # line-break before the first argument, dedenting closing brackets if set
1138 unformatted_code
= textwrap
.dedent("""\
1139 def overly_long_function_name(
1140 first_argument_on_the_same_line,
1141 second_argument_makes_the_line_too_long):
1144 # expected_formatted_pep8_code = textwrap.dedent("""\
1145 # def overly_long_function_name(
1146 # first_argument_on_the_same_line,
1147 # second_argument_makes_the_line_too_long):
1150 expected_formatted_fb_code
= textwrap
.dedent("""\
1151 def overly_long_function_name(
1152 first_argument_on_the_same_line, second_argument_makes_the_line_too_long
1156 self
.assertYapfReformats(
1158 expected_formatted_fb_code
,
1159 extra_options
=['--style=facebook'])
1160 # TODO(ambv): currently the following produces code that is not PEP8
1161 # compliant, raising "E125 continuation line with same indent as next
1162 # logical line" with flake8. Expected behaviour for PEP8 would be to use
1163 # double-indentation here.
1164 # self.assertYapfReformats(unformatted_code, expected_formatted_pep8_code,
1165 # extra_options=['--style=pep8'])
1167 def testCoalesceBrackets(self
):
1168 unformatted_code
= textwrap
.dedent("""\
1169 some_long_function_name_foo(
1171 'first_argument_of_the_thing': id,
1172 'second_argument_of_the_thing': "some thing"
1176 expected_formatted_code
= textwrap
.dedent("""\
1177 some_long_function_name_foo({
1178 'first_argument_of_the_thing': id,
1179 'second_argument_of_the_thing': "some thing"
1182 with utils
.NamedTempFile(dirname
=self
.test_tmpdir
, mode
='w') as (f
, name
):
1184 textwrap
.dedent("""\
1187 coalesce_brackets = True
1190 self
.assertYapfReformats(
1192 expected_formatted_code
,
1193 extra_options
=['--style={0}'.format(name
)])
1195 def testPseudoParenSpaces(self
):
1196 unformatted_code
= textwrap
.dedent("""\
1199 return {msg_id: author for author, msg_id in reader}
1201 expected_formatted_code
= textwrap
.dedent("""\
1204 return {msg_id: author for author, msg_id in reader}
1206 self
.assertYapfReformats(
1208 expected_formatted_code
,
1209 extra_options
=['--lines', '1-1', '--style', 'yapf'])
1211 def testMultilineCommentFormattingDisabled(self
):
1212 unformatted_code
= textwrap
.dedent("""\
1217 # Multiline comment.
1221 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx':
1222 ('yyyyy', zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz),
1223 '#': lambda x: x # do nothing
1226 expected_formatted_code
= textwrap
.dedent("""\
1231 # Multiline comment.
1235 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx':
1236 ('yyyyy', zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz),
1237 '#': lambda x: x # do nothing
1240 self
.assertYapfReformats(
1242 expected_formatted_code
,
1243 extra_options
=['--lines', '1-1', '--style', 'yapf'])
1245 def testTrailingCommentsWithDisabledFormatting(self
):
1246 unformatted_code
= textwrap
.dedent("""\
1250 'hello world' # This is a comment.
1253 expected_formatted_code
= textwrap
.dedent("""\
1257 'hello world' # This is a comment.
1260 self
.assertYapfReformats(
1262 expected_formatted_code
,
1263 extra_options
=['--lines', '1-1', '--style', 'yapf'])
1265 def testUseTabs(self
):
1266 unformatted_code
= textwrap
.dedent("""\
1271 expected_formatted_code
= """\
1275 """ # noqa: W191,E101
1276 style_contents
= textwrap
.dedent("""\
1278 based_on_style = yapf
1282 with utils
.TempFileContents(self
.test_tmpdir
, style_contents
) as stylepath
:
1283 self
.assertYapfReformats(
1285 expected_formatted_code
,
1286 extra_options
=['--style={0}'.format(stylepath
)])
1288 def testUseTabsWith(self
):
1289 unformatted_code
= """\
1291 return ['hello', 'world',]
1293 expected_formatted_code
= """\
1299 """ # noqa: W191,E101
1300 style_contents
= textwrap
.dedent("""\
1302 based_on_style = yapf
1306 with utils
.TempFileContents(self
.test_tmpdir
, style_contents
) as stylepath
:
1307 self
.assertYapfReformats(
1309 expected_formatted_code
,
1310 extra_options
=['--style={0}'.format(stylepath
)])
1312 def testUseTabsContinuationAlignStyleFixed(self
):
1313 unformatted_code
= """\
1314 def foo_function(arg1, arg2, arg3):
1315 return ['hello', 'world',]
1317 expected_formatted_code
= """\
1324 """ # noqa: W191,E101
1325 style_contents
= textwrap
.dedent("""\
1327 based_on_style = yapf
1331 continuation_indent_width=8
1332 continuation_align_style = fixed
1334 with utils
.TempFileContents(self
.test_tmpdir
, style_contents
) as stylepath
:
1335 self
.assertYapfReformats(
1337 expected_formatted_code
,
1338 extra_options
=['--style={0}'.format(stylepath
)])
1340 def testUseTabsContinuationAlignStyleVAlignRight(self
):
1341 unformatted_code
= """\
1342 def foo_function(arg1, arg2, arg3):
1343 return ['hello', 'world',]
1345 expected_formatted_code
= """\
1346 def foo_function(arg1, arg2,
1352 """ # noqa: W191,E101
1353 style_contents
= textwrap
.dedent("""\
1355 based_on_style = yapf
1359 continuation_indent_width = 8
1360 continuation_align_style = valign-right
1362 with utils
.TempFileContents(self
.test_tmpdir
, style_contents
) as stylepath
:
1363 self
.assertYapfReformats(
1365 expected_formatted_code
,
1366 extra_options
=['--style={0}'.format(stylepath
)])
1368 def testUseSpacesContinuationAlignStyleFixed(self
):
1369 unformatted_code
= textwrap
.dedent("""\
1370 def foo_function(arg1, arg2, arg3):
1371 return ['hello', 'world',]
1373 expected_formatted_code
= textwrap
.dedent("""\
1381 style_contents
= textwrap
.dedent("""\
1383 based_on_style = yapf
1386 continuation_indent_width = 8
1387 continuation_align_style = fixed
1389 with utils
.TempFileContents(self
.test_tmpdir
, style_contents
) as stylepath
:
1390 self
.assertYapfReformats(
1392 expected_formatted_code
,
1393 extra_options
=['--style={0}'.format(stylepath
)])
1395 def testUseSpacesContinuationAlignStyleVAlignRight(self
):
1396 unformatted_code
= textwrap
.dedent("""\
1397 def foo_function(arg1, arg2, arg3):
1398 return ['hello', 'world',]
1400 expected_formatted_code
= textwrap
.dedent("""\
1401 def foo_function(arg1, arg2,
1408 style_contents
= textwrap
.dedent("""\
1410 based_on_style = yapf
1413 continuation_indent_width = 8
1414 continuation_align_style = valign-right
1416 with utils
.TempFileContents(self
.test_tmpdir
, style_contents
) as stylepath
:
1417 self
.assertYapfReformats(
1419 expected_formatted_code
,
1420 extra_options
=['--style={0}'.format(stylepath
)])
1422 def testStyleOutputRoundTrip(self
):
1423 unformatted_code
= textwrap
.dedent("""\
1427 expected_formatted_code
= textwrap
.dedent("""\
1432 with utils
.NamedTempFile(dirname
=self
.test_tmpdir
) as (stylefile
,
1434 p
= subprocess
.Popen(
1435 YAPF_BINARY
+ ['--style-help'],
1437 stdin
=subprocess
.PIPE
,
1438 stderr
=subprocess
.PIPE
)
1439 _
, stderrdata
= p
.communicate()
1440 self
.assertEqual(stderrdata
, b
'')
1441 self
.assertYapfReformats(
1443 expected_formatted_code
,
1444 extra_options
=['--style={0}'.format(stylepath
)])
1446 def testSpacingBeforeComments(self
):
1447 unformatted_code
= textwrap
.dedent("""\
1457 expected_formatted_code
= textwrap
.dedent("""\
1467 self
.assertYapfReformats(
1469 expected_formatted_code
,
1470 extra_options
=['--lines', '1-2'])
1472 def testSpacingBeforeCommentsInDicts(self
):
1473 unformatted_code
= textwrap
.dedent("""\
1482 TIMED_OUT: # Timed out.
1488 expected_formatted_code
= textwrap
.dedent("""\
1497 TIMED_OUT: # Timed out.
1503 self
.assertYapfReformats(
1505 expected_formatted_code
,
1506 extra_options
=['--style', 'yapf', '--lines', '1-1'])
1508 def testDisableWithLinesOption(self
):
1509 unformatted_code
= textwrap
.dedent("""\
1518 expected_formatted_code
= textwrap
.dedent("""\
1527 self
.assertYapfReformats(
1529 expected_formatted_code
,
1530 extra_options
=['--lines', '1-8'])
1532 def testDisableWithLineRanges(self
):
1533 unformatted_code
= textwrap
.dedent("""\
1542 expected_formatted_code
= textwrap
.dedent("""\
1551 self
.assertYapfReformats(
1553 expected_formatted_code
,
1554 extra_options
=['--style', 'yapf', '--lines', '1-100'])
1557 class BadInputTest(yapf_test_helper
.YAPFTest
):
1558 """Test yapf's behaviour when passed bad input."""
1560 def testBadSyntax(self
):
1562 self
.assertRaises(errors
.YapfError
, yapf_api
.FormatCode
, code
)
1564 def testBadCode(self
):
1565 code
= 'x = """hello\n'
1566 self
.assertRaises(errors
.YapfError
, yapf_api
.FormatCode
, code
)
1569 class DiffIndentTest(yapf_test_helper
.YAPFTest
):
1573 my_style
= style
.CreatePEP8Style()
1574 my_style
['INDENT_WIDTH'] = 3
1575 my_style
['CONTINUATION_INDENT_WIDTH'] = 3
1578 def _Check(self
, unformatted_code
, expected_formatted_code
):
1579 formatted_code
, _
= yapf_api
.FormatCode(
1580 unformatted_code
, style_config
=style
.SetGlobalStyle(self
._OwnStyle
()))
1581 self
.assertEqual(expected_formatted_code
, formatted_code
)
1583 def testSimple(self
):
1584 unformatted_code
= textwrap
.dedent("""\
1588 expected_formatted_code
= textwrap
.dedent("""\
1592 self
._Check
(unformatted_code
, expected_formatted_code
)
1595 class HorizontallyAlignedTrailingCommentsTest(yapf_test_helper
.YAPFTest
):
1599 my_style
= style
.CreatePEP8Style()
1600 my_style
['SPACES_BEFORE_COMMENT'] = [
1607 def _Check(self
, unformatted_code
, expected_formatted_code
):
1608 formatted_code
, _
= yapf_api
.FormatCode(
1609 unformatted_code
, style_config
=style
.SetGlobalStyle(self
._OwnStyle
()))
1610 self
.assertCodeEqual(expected_formatted_code
, formatted_code
)
1612 def testSimple(self
):
1613 unformatted_code
= textwrap
.dedent("""\
1614 foo = '1' # Aligned at first list value
1616 foo = '2__<15>' # Aligned at second list value
1618 foo = '3____________<25>' # Aligned at third list value
1620 foo = '4______________________<35>' # Aligned beyond list values
1622 expected_formatted_code
= textwrap
.dedent("""\
1623 foo = '1' # Aligned at first list value
1625 foo = '2__<15>' # Aligned at second list value
1627 foo = '3____________<25>' # Aligned at third list value
1629 foo = '4______________________<35>' # Aligned beyond list values
1631 self
._Check
(unformatted_code
, expected_formatted_code
)
1633 def testBlock(self
):
1634 unformatted_code
= textwrap
.dedent("""\
1642 expected_formatted_code
= textwrap
.dedent("""\
1650 self
._Check
(unformatted_code
, expected_formatted_code
)
1652 def testBlockWithLongLine(self
):
1653 unformatted_code
= textwrap
.dedent("""\
1655 func___________________(2) # Line 2
1661 expected_formatted_code
= textwrap
.dedent("""\
1663 func___________________(2) # Line 2
1669 self
._Check
(unformatted_code
, expected_formatted_code
)
1671 def testBlockFuncSuffix(self
):
1672 unformatted_code
= textwrap
.dedent("""\
1683 expected_formatted_code
= textwrap
.dedent("""\
1695 self
._Check
(unformatted_code
, expected_formatted_code
)
1697 def testBlockCommentSuffix(self
):
1698 unformatted_code
= textwrap
.dedent("""\
1703 # Line 5 - SpliceComments makes this part of the previous block
1706 # Aligned with prev comment block
1708 expected_formatted_code
= textwrap
.dedent("""\
1713 # Line 5 - SpliceComments makes this part of the previous block
1716 # Aligned with prev comment block
1718 self
._Check
(unformatted_code
, expected_formatted_code
)
1720 def testBlockIndentedFuncSuffix(self
):
1721 unformatted_code
= textwrap
.dedent("""\
1727 # Line 5 - SpliceComments makes this a new block
1735 expected_formatted_code
= textwrap
.dedent("""\
1742 # Line 5 - SpliceComments makes this a new block
1751 self
._Check
(unformatted_code
, expected_formatted_code
)
1753 def testBlockIndentedCommentSuffix(self
):
1754 unformatted_code
= textwrap
.dedent("""\
1765 expected_formatted_code
= textwrap
.dedent("""\
1776 self
._Check
(unformatted_code
, expected_formatted_code
)
1778 def testBlockMultiIndented(self
):
1779 unformatted_code
= textwrap
.dedent("""\
1792 expected_formatted_code
= textwrap
.dedent("""\
1805 self
._Check
(unformatted_code
, expected_formatted_code
)
1808 unformatted_code
= textwrap
.dedent("""\
1812 a_longer_var_name, # Desc 3
1819 expected_formatted_code
= textwrap
.dedent("""\
1823 a_longer_var_name, # Desc 3
1830 self
._Check
(unformatted_code
, expected_formatted_code
)
1832 def testDisableBlock(self
):
1833 unformatted_code
= textwrap
.dedent("""\
1845 expected_formatted_code
= textwrap
.dedent("""\
1857 self
._Check
(unformatted_code
, expected_formatted_code
)
1859 def testDisabledLine(self
):
1860 unformatted_code
= textwrap
.dedent("""\
1862 do_not_touch1 # yapf: disable
1863 do_not_touch2 # yapf: disable
1864 a_longer_statement # comment 2
1866 expected_formatted_code
= textwrap
.dedent("""\
1868 do_not_touch1 # yapf: disable
1869 do_not_touch2 # yapf: disable
1870 a_longer_statement # comment 2
1872 self
._Check
(unformatted_code
, expected_formatted_code
)
1875 class _SpacesAroundDictListTupleTestImpl(yapf_test_helper
.YAPFTest
):
1879 my_style
= style
.CreatePEP8Style()
1880 my_style
['DISABLE_ENDING_COMMA_HEURISTIC'] = True
1881 my_style
['SPLIT_ALL_COMMA_SEPARATED_VALUES'] = False
1882 my_style
['SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED'] = False
1885 def _Check(self
, unformatted_code
, expected_formatted_code
):
1886 formatted_code
, _
= yapf_api
.FormatCode(
1887 unformatted_code
, style_config
=style
.SetGlobalStyle(self
._OwnStyle
()))
1888 self
.assertEqual(expected_formatted_code
, formatted_code
)
1894 class SpacesAroundDictTest(_SpacesAroundDictListTupleTestImpl
):
1898 style
= super(SpacesAroundDictTest
, cls
)._OwnStyle
()
1899 style
['SPACES_AROUND_DICT_DELIMITERS'] = True
1903 def testStandard(self
):
1904 unformatted_code
= textwrap
.dedent("""\
1906 {k:v for k, v in other.items()}
1907 {k for k in [1, 2, 3]}
1909 # The following statements should not change
1911 {1 : 2} # yapf: disable
1917 # Dict settings should not impact lists or tuples
1921 expected_formatted_code
= textwrap
.dedent("""\
1923 { k: v for k, v in other.items() }
1924 { k for k in [1, 2, 3] }
1926 # The following statements should not change
1928 {1 : 2} # yapf: disable
1934 # Dict settings should not impact lists or tuples
1938 self
._Check
(unformatted_code
, expected_formatted_code
)
1941 class SpacesAroundListTest(_SpacesAroundDictListTupleTestImpl
):
1945 style
= super(SpacesAroundListTest
, cls
)._OwnStyle
()
1946 style
['SPACES_AROUND_LIST_DELIMITERS'] = True
1950 def testStandard(self
):
1951 unformatted_code
= textwrap
.dedent("""\
1955 [v for v in [1,2,3] if v & 1]
1957 # The following statements should not change
1961 [v for v in [1,2,3] if v & 1] # yapf: disable
1968 # List settings should not impact dicts or tuples
1972 expected_formatted_code
= textwrap
.dedent("""\
1976 [ v for v in [ 1, 2, 3 ] if v & 1 ]
1978 # The following statements should not change
1982 [v for v in [1,2,3] if v & 1] # yapf: disable
1989 # List settings should not impact dicts or tuples
1993 self
._Check
(unformatted_code
, expected_formatted_code
)
1996 class SpacesAroundTupleTest(_SpacesAroundDictListTupleTestImpl
):
2000 style
= super(SpacesAroundTupleTest
, cls
)._OwnStyle
()
2001 style
['SPACES_AROUND_TUPLE_DELIMITERS'] = True
2005 def testStandard(self
):
2006 unformatted_code
= textwrap
.dedent("""\
2012 # The following statements should not change
2014 (this_func or that_func)(3, 4)
2015 if (True and False): pass
2018 (0, 1) # yapf: disable
2025 # Tuple settings should not impact dicts or lists
2029 expected_formatted_code
= textwrap
.dedent("""\
2035 # The following statements should not change
2037 (this_func or that_func)(3, 4)
2038 if (True and False): pass
2041 (0, 1) # yapf: disable
2048 # Tuple settings should not impact dicts or lists
2052 self
._Check
(unformatted_code
, expected_formatted_code
)
2055 if __name__
== '__main__':