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