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