How to use unchanged method in hypothesis

Best Python code snippet using hypothesis

test_fixers.py

Source:test_fixers.py Github

copy

Full Screen

...33 tree = self._check(before, after)34 self.assertIn(message, "".join(self.fixer_log))35 if not unchanged:36 self.assertTrue(tree.was_changed)37 def warns_unchanged(self, before, message):38 self.warns(before, before, message, unchanged=True)39 def unchanged(self, before, ignore_warnings=False):40 self._check(before, before)41 if not ignore_warnings:42 self.assertEqual(self.fixer_log, [])43 def assert_runs_after(self, *names):44 fixes = [self.fixer]45 fixes.extend(names)46 r = support.get_refactorer("lib2to3", fixes)47 (pre, post) = r.get_fixers()48 n = "fix_" + self.fixer49 if post and post[-1].__class__.__module__.endswith(n):50 # We're the last fixer to run51 return52 if pre and pre[-1].__class__.__module__.endswith(n) and not post:53 # We're the last in pre and post is empty54 return55 self.fail("Fixer run order (%s) is incorrect; %s should be last."\56 %(", ".join([x.__class__.__module__ for x in (pre+post)]), n))57class Test_ne(FixerTestCase):58 fixer = "ne"59 def test_basic(self):60 b = """if x <> y:61 pass"""62 a = """if x != y:63 pass"""64 self.check(b, a)65 def test_no_spaces(self):66 b = """if x<>y:67 pass"""68 a = """if x!=y:69 pass"""70 self.check(b, a)71 def test_chained(self):72 b = """if x<>y<>z:73 pass"""74 a = """if x!=y!=z:75 pass"""76 self.check(b, a)77class Test_has_key(FixerTestCase):78 fixer = "has_key"79 def test_1(self):80 b = """x = d.has_key("x") or d.has_key("y")"""81 a = """x = "x" in d or "y" in d"""82 self.check(b, a)83 def test_2(self):84 b = """x = a.b.c.d.has_key("x") ** 3"""85 a = """x = ("x" in a.b.c.d) ** 3"""86 self.check(b, a)87 def test_3(self):88 b = """x = a.b.has_key(1 + 2).__repr__()"""89 a = """x = (1 + 2 in a.b).__repr__()"""90 self.check(b, a)91 def test_4(self):92 b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4"""93 a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4"""94 self.check(b, a)95 def test_5(self):96 b = """x = a.has_key(f or g)"""97 a = """x = (f or g) in a"""98 self.check(b, a)99 def test_6(self):100 b = """x = a + b.has_key(c)"""101 a = """x = a + (c in b)"""102 self.check(b, a)103 def test_7(self):104 b = """x = a.has_key(lambda: 12)"""105 a = """x = (lambda: 12) in a"""106 self.check(b, a)107 def test_8(self):108 b = """x = a.has_key(a for a in b)"""109 a = """x = (a for a in b) in a"""110 self.check(b, a)111 def test_9(self):112 b = """if not a.has_key(b): pass"""113 a = """if b not in a: pass"""114 self.check(b, a)115 def test_10(self):116 b = """if not a.has_key(b).__repr__(): pass"""117 a = """if not (b in a).__repr__(): pass"""118 self.check(b, a)119 def test_11(self):120 b = """if not a.has_key(b) ** 2: pass"""121 a = """if not (b in a) ** 2: pass"""122 self.check(b, a)123class Test_apply(FixerTestCase):124 fixer = "apply"125 def test_1(self):126 b = """x = apply(f, g + h)"""127 a = """x = f(*g + h)"""128 self.check(b, a)129 def test_2(self):130 b = """y = apply(f, g, h)"""131 a = """y = f(*g, **h)"""132 self.check(b, a)133 def test_3(self):134 b = """z = apply(fs[0], g or h, h or g)"""135 a = """z = fs[0](*g or h, **h or g)"""136 self.check(b, a)137 def test_4(self):138 b = """apply(f, (x, y) + t)"""139 a = """f(*(x, y) + t)"""140 self.check(b, a)141 def test_5(self):142 b = """apply(f, args,)"""143 a = """f(*args)"""144 self.check(b, a)145 def test_6(self):146 b = """apply(f, args, kwds,)"""147 a = """f(*args, **kwds)"""148 self.check(b, a)149 # Test that complex functions are parenthesized150 def test_complex_1(self):151 b = """x = apply(f+g, args)"""152 a = """x = (f+g)(*args)"""153 self.check(b, a)154 def test_complex_2(self):155 b = """x = apply(f*g, args)"""156 a = """x = (f*g)(*args)"""157 self.check(b, a)158 def test_complex_3(self):159 b = """x = apply(f**g, args)"""160 a = """x = (f**g)(*args)"""161 self.check(b, a)162 # But dotted names etc. not163 def test_dotted_name(self):164 b = """x = apply(f.g, args)"""165 a = """x = f.g(*args)"""166 self.check(b, a)167 def test_subscript(self):168 b = """x = apply(f[x], args)"""169 a = """x = f[x](*args)"""170 self.check(b, a)171 def test_call(self):172 b = """x = apply(f(), args)"""173 a = """x = f()(*args)"""174 self.check(b, a)175 # Extreme case176 def test_extreme(self):177 b = """x = apply(a.b.c.d.e.f, args, kwds)"""178 a = """x = a.b.c.d.e.f(*args, **kwds)"""179 self.check(b, a)180 # XXX Comments in weird places still get lost181 def test_weird_comments(self):182 b = """apply( # foo183 f, # bar184 args)"""185 a = """f(*args)"""186 self.check(b, a)187 # These should *not* be touched188 def test_unchanged_1(self):189 s = """apply()"""190 self.unchanged(s)191 def test_unchanged_2(self):192 s = """apply(f)"""193 self.unchanged(s)194 def test_unchanged_3(self):195 s = """apply(f,)"""196 self.unchanged(s)197 def test_unchanged_4(self):198 s = """apply(f, args, kwds, extras)"""199 self.unchanged(s)200 def test_unchanged_5(self):201 s = """apply(f, *args, **kwds)"""202 self.unchanged(s)203 def test_unchanged_6(self):204 s = """apply(f, *args)"""205 self.unchanged(s)206 def test_unchanged_6b(self):207 s = """apply(f, **kwds)"""208 self.unchanged(s)209 def test_unchanged_7(self):210 s = """apply(func=f, args=args, kwds=kwds)"""211 self.unchanged(s)212 def test_unchanged_8(self):213 s = """apply(f, args=args, kwds=kwds)"""214 self.unchanged(s)215 def test_unchanged_9(self):216 s = """apply(f, args, kwds=kwds)"""217 self.unchanged(s)218 def test_space_1(self):219 a = """apply( f, args, kwds)"""220 b = """f(*args, **kwds)"""221 self.check(a, b)222 def test_space_2(self):223 a = """apply( f ,args,kwds )"""224 b = """f(*args, **kwds)"""225 self.check(a, b)226class Test_reload(FixerTestCase):227 fixer = "reload"228 def test(self):229 b = """reload(a)"""230 a = """import importlib\nimportlib.reload(a)"""231 self.check(b, a)232 def test_comment(self):233 b = """reload( a ) # comment"""234 a = """import importlib\nimportlib.reload( a ) # comment"""235 self.check(b, a)236 # PEP 8 comments237 b = """reload( a ) # comment"""238 a = """import importlib\nimportlib.reload( a ) # comment"""239 self.check(b, a)240 def test_space(self):241 b = """reload( a )"""242 a = """import importlib\nimportlib.reload( a )"""243 self.check(b, a)244 b = """reload( a)"""245 a = """import importlib\nimportlib.reload( a)"""246 self.check(b, a)247 b = """reload(a )"""248 a = """import importlib\nimportlib.reload(a )"""249 self.check(b, a)250 def test_unchanged(self):251 s = """reload(a=1)"""252 self.unchanged(s)253 s = """reload(f, g)"""254 self.unchanged(s)255 s = """reload(f, *h)"""256 self.unchanged(s)257 s = """reload(f, *h, **i)"""258 self.unchanged(s)259 s = """reload(f, **i)"""260 self.unchanged(s)261 s = """reload(*h, **i)"""262 self.unchanged(s)263 s = """reload(*h)"""264 self.unchanged(s)265 s = """reload(**i)"""266 self.unchanged(s)267 s = """reload()"""268 self.unchanged(s)269class Test_intern(FixerTestCase):270 fixer = "intern"271 def test_prefix_preservation(self):272 b = """x = intern( a )"""273 a = """import sys\nx = sys.intern( a )"""274 self.check(b, a)275 b = """y = intern("b" # test276 )"""277 a = """import sys\ny = sys.intern("b" # test278 )"""279 self.check(b, a)280 b = """z = intern(a+b+c.d, )"""281 a = """import sys\nz = sys.intern(a+b+c.d, )"""282 self.check(b, a)283 def test(self):284 b = """x = intern(a)"""285 a = """import sys\nx = sys.intern(a)"""286 self.check(b, a)287 b = """z = intern(a+b+c.d,)"""288 a = """import sys\nz = sys.intern(a+b+c.d,)"""289 self.check(b, a)290 b = """intern("y%s" % 5).replace("y", "")"""291 a = """import sys\nsys.intern("y%s" % 5).replace("y", "")"""292 self.check(b, a)293 # These should not be refactored294 def test_unchanged(self):295 s = """intern(a=1)"""296 self.unchanged(s)297 s = """intern(f, g)"""298 self.unchanged(s)299 s = """intern(*h)"""300 self.unchanged(s)301 s = """intern(**i)"""302 self.unchanged(s)303 s = """intern()"""304 self.unchanged(s)305class Test_reduce(FixerTestCase):306 fixer = "reduce"307 def test_simple_call(self):308 b = "reduce(a, b, c)"309 a = "from functools import reduce\nreduce(a, b, c)"310 self.check(b, a)311 def test_bug_7253(self):312 # fix_tuple_params was being bad and orphaning nodes in the tree.313 b = "def x(arg): reduce(sum, [])"314 a = "from functools import reduce\ndef x(arg): reduce(sum, [])"315 self.check(b, a)316 def test_call_with_lambda(self):317 b = "reduce(lambda x, y: x + y, seq)"318 a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)"319 self.check(b, a)320 def test_unchanged(self):321 s = "reduce(a)"322 self.unchanged(s)323 s = "reduce(a, b=42)"324 self.unchanged(s)325 s = "reduce(a, b, c, d)"326 self.unchanged(s)327 s = "reduce(**c)"328 self.unchanged(s)329 s = "reduce()"330 self.unchanged(s)331class Test_print(FixerTestCase):332 fixer = "print"333 def test_prefix_preservation(self):334 b = """print 1, 1+1, 1+1+1"""335 a = """print(1, 1+1, 1+1+1)"""336 self.check(b, a)337 def test_idempotency(self):338 s = """print()"""339 self.unchanged(s)340 s = """print('')"""341 self.unchanged(s)342 def test_idempotency_print_as_function(self):343 self.refactor.driver.grammar = pygram.python_grammar_no_print_statement344 s = """print(1, 1+1, 1+1+1)"""345 self.unchanged(s)346 s = """print()"""347 self.unchanged(s)348 s = """print('')"""349 self.unchanged(s)350 def test_1(self):351 b = """print 1, 1+1, 1+1+1"""352 a = """print(1, 1+1, 1+1+1)"""353 self.check(b, a)354 def test_2(self):355 b = """print 1, 2"""356 a = """print(1, 2)"""357 self.check(b, a)358 def test_3(self):359 b = """print"""360 a = """print()"""361 self.check(b, a)362 def test_4(self):363 # from bug 3000364 b = """print whatever; print"""365 a = """print(whatever); print()"""366 self.check(b, a)367 def test_5(self):368 b = """print; print whatever;"""369 a = """print(); print(whatever);"""370 self.check(b, a)371 def test_tuple(self):372 b = """print (a, b, c)"""373 a = """print((a, b, c))"""374 self.check(b, a)375 # trailing commas376 def test_trailing_comma_1(self):377 b = """print 1, 2, 3,"""378 a = """print(1, 2, 3, end=' ')"""379 self.check(b, a)380 def test_trailing_comma_2(self):381 b = """print 1, 2,"""382 a = """print(1, 2, end=' ')"""383 self.check(b, a)384 def test_trailing_comma_3(self):385 b = """print 1,"""386 a = """print(1, end=' ')"""387 self.check(b, a)388 # >> stuff389 def test_vargs_without_trailing_comma(self):390 b = """print >>sys.stderr, 1, 2, 3"""391 a = """print(1, 2, 3, file=sys.stderr)"""392 self.check(b, a)393 def test_with_trailing_comma(self):394 b = """print >>sys.stderr, 1, 2,"""395 a = """print(1, 2, end=' ', file=sys.stderr)"""396 self.check(b, a)397 def test_no_trailing_comma(self):398 b = """print >>sys.stderr, 1+1"""399 a = """print(1+1, file=sys.stderr)"""400 self.check(b, a)401 def test_spaces_before_file(self):402 b = """print >> sys.stderr"""403 a = """print(file=sys.stderr)"""404 self.check(b, a)405 def test_with_future_print_function(self):406 s = "from __future__ import print_function\n" \407 "print('Hai!', end=' ')"408 self.unchanged(s)409 b = "print 'Hello, world!'"410 a = "print('Hello, world!')"411 self.check(b, a)412class Test_exec(FixerTestCase):413 fixer = "exec"414 def test_prefix_preservation(self):415 b = """ exec code in ns1, ns2"""416 a = """ exec(code, ns1, ns2)"""417 self.check(b, a)418 def test_basic(self):419 b = """exec code"""420 a = """exec(code)"""421 self.check(b, a)422 def test_with_globals(self):423 b = """exec code in ns"""424 a = """exec(code, ns)"""425 self.check(b, a)426 def test_with_globals_locals(self):427 b = """exec code in ns1, ns2"""428 a = """exec(code, ns1, ns2)"""429 self.check(b, a)430 def test_complex_1(self):431 b = """exec (a.b()) in ns"""432 a = """exec((a.b()), ns)"""433 self.check(b, a)434 def test_complex_2(self):435 b = """exec a.b() + c in ns"""436 a = """exec(a.b() + c, ns)"""437 self.check(b, a)438 # These should not be touched439 def test_unchanged_1(self):440 s = """exec(code)"""441 self.unchanged(s)442 def test_unchanged_2(self):443 s = """exec (code)"""444 self.unchanged(s)445 def test_unchanged_3(self):446 s = """exec(code, ns)"""447 self.unchanged(s)448 def test_unchanged_4(self):449 s = """exec(code, ns1, ns2)"""450 self.unchanged(s)451class Test_repr(FixerTestCase):452 fixer = "repr"453 def test_prefix_preservation(self):454 b = """x = `1 + 2`"""455 a = """x = repr(1 + 2)"""456 self.check(b, a)457 def test_simple_1(self):458 b = """x = `1 + 2`"""459 a = """x = repr(1 + 2)"""460 self.check(b, a)461 def test_simple_2(self):462 b = """y = `x`"""463 a = """y = repr(x)"""464 self.check(b, a)465 def test_complex(self):466 b = """z = `y`.__repr__()"""467 a = """z = repr(y).__repr__()"""468 self.check(b, a)469 def test_tuple(self):470 b = """x = `1, 2, 3`"""471 a = """x = repr((1, 2, 3))"""472 self.check(b, a)473 def test_nested(self):474 b = """x = `1 + `2``"""475 a = """x = repr(1 + repr(2))"""476 self.check(b, a)477 def test_nested_tuples(self):478 b = """x = `1, 2 + `3, 4``"""479 a = """x = repr((1, 2 + repr((3, 4))))"""480 self.check(b, a)481class Test_except(FixerTestCase):482 fixer = "except"483 def test_prefix_preservation(self):484 b = """485 try:486 pass487 except (RuntimeError, ImportError), e:488 pass"""489 a = """490 try:491 pass492 except (RuntimeError, ImportError) as e:493 pass"""494 self.check(b, a)495 def test_simple(self):496 b = """497 try:498 pass499 except Foo, e:500 pass"""501 a = """502 try:503 pass504 except Foo as e:505 pass"""506 self.check(b, a)507 def test_simple_no_space_before_target(self):508 b = """509 try:510 pass511 except Foo,e:512 pass"""513 a = """514 try:515 pass516 except Foo as e:517 pass"""518 self.check(b, a)519 def test_tuple_unpack(self):520 b = """521 def foo():522 try:523 pass524 except Exception, (f, e):525 pass526 except ImportError, e:527 pass"""528 a = """529 def foo():530 try:531 pass532 except Exception as xxx_todo_changeme:533 (f, e) = xxx_todo_changeme.args534 pass535 except ImportError as e:536 pass"""537 self.check(b, a)538 def test_multi_class(self):539 b = """540 try:541 pass542 except (RuntimeError, ImportError), e:543 pass"""544 a = """545 try:546 pass547 except (RuntimeError, ImportError) as e:548 pass"""549 self.check(b, a)550 def test_list_unpack(self):551 b = """552 try:553 pass554 except Exception, [a, b]:555 pass"""556 a = """557 try:558 pass559 except Exception as xxx_todo_changeme:560 [a, b] = xxx_todo_changeme.args561 pass"""562 self.check(b, a)563 def test_weird_target_1(self):564 b = """565 try:566 pass567 except Exception, d[5]:568 pass"""569 a = """570 try:571 pass572 except Exception as xxx_todo_changeme:573 d[5] = xxx_todo_changeme574 pass"""575 self.check(b, a)576 def test_weird_target_2(self):577 b = """578 try:579 pass580 except Exception, a.foo:581 pass"""582 a = """583 try:584 pass585 except Exception as xxx_todo_changeme:586 a.foo = xxx_todo_changeme587 pass"""588 self.check(b, a)589 def test_weird_target_3(self):590 b = """591 try:592 pass593 except Exception, a().foo:594 pass"""595 a = """596 try:597 pass598 except Exception as xxx_todo_changeme:599 a().foo = xxx_todo_changeme600 pass"""601 self.check(b, a)602 def test_bare_except(self):603 b = """604 try:605 pass606 except Exception, a:607 pass608 except:609 pass"""610 a = """611 try:612 pass613 except Exception as a:614 pass615 except:616 pass"""617 self.check(b, a)618 def test_bare_except_and_else_finally(self):619 b = """620 try:621 pass622 except Exception, a:623 pass624 except:625 pass626 else:627 pass628 finally:629 pass"""630 a = """631 try:632 pass633 except Exception as a:634 pass635 except:636 pass637 else:638 pass639 finally:640 pass"""641 self.check(b, a)642 def test_multi_fixed_excepts_before_bare_except(self):643 b = """644 try:645 pass646 except TypeError, b:647 pass648 except Exception, a:649 pass650 except:651 pass"""652 a = """653 try:654 pass655 except TypeError as b:656 pass657 except Exception as a:658 pass659 except:660 pass"""661 self.check(b, a)662 def test_one_line_suites(self):663 b = """664 try: raise TypeError665 except TypeError, e:666 pass667 """668 a = """669 try: raise TypeError670 except TypeError as e:671 pass672 """673 self.check(b, a)674 b = """675 try:676 raise TypeError677 except TypeError, e: pass678 """679 a = """680 try:681 raise TypeError682 except TypeError as e: pass683 """684 self.check(b, a)685 b = """686 try: raise TypeError687 except TypeError, e: pass688 """689 a = """690 try: raise TypeError691 except TypeError as e: pass692 """693 self.check(b, a)694 b = """695 try: raise TypeError696 except TypeError, e: pass697 else: function()698 finally: done()699 """700 a = """701 try: raise TypeError702 except TypeError as e: pass703 else: function()704 finally: done()705 """706 self.check(b, a)707 # These should not be touched:708 def test_unchanged_1(self):709 s = """710 try:711 pass712 except:713 pass"""714 self.unchanged(s)715 def test_unchanged_2(self):716 s = """717 try:718 pass719 except Exception:720 pass"""721 self.unchanged(s)722 def test_unchanged_3(self):723 s = """724 try:725 pass726 except (Exception, SystemExit):727 pass"""728 self.unchanged(s)729class Test_raise(FixerTestCase):730 fixer = "raise"731 def test_basic(self):732 b = """raise Exception, 5"""733 a = """raise Exception(5)"""734 self.check(b, a)735 def test_prefix_preservation(self):736 b = """raise Exception,5"""737 a = """raise Exception(5)"""738 self.check(b, a)739 b = """raise Exception, 5"""740 a = """raise Exception(5)"""741 self.check(b, a)742 def test_with_comments(self):743 b = """raise Exception, 5 # foo"""744 a = """raise Exception(5) # foo"""745 self.check(b, a)746 b = """raise E, (5, 6) % (a, b) # foo"""747 a = """raise E((5, 6) % (a, b)) # foo"""748 self.check(b, a)749 b = """def foo():750 raise Exception, 5, 6 # foo"""751 a = """def foo():752 raise Exception(5).with_traceback(6) # foo"""753 self.check(b, a)754 def test_None_value(self):755 b = """raise Exception(5), None, tb"""756 a = """raise Exception(5).with_traceback(tb)"""757 self.check(b, a)758 def test_tuple_value(self):759 b = """raise Exception, (5, 6, 7)"""760 a = """raise Exception(5, 6, 7)"""761 self.check(b, a)762 def test_tuple_detection(self):763 b = """raise E, (5, 6) % (a, b)"""764 a = """raise E((5, 6) % (a, b))"""765 self.check(b, a)766 def test_tuple_exc_1(self):767 b = """raise (((E1, E2), E3), E4), V"""768 a = """raise E1(V)"""769 self.check(b, a)770 def test_tuple_exc_2(self):771 b = """raise (E1, (E2, E3), E4), V"""772 a = """raise E1(V)"""773 self.check(b, a)774 # These should produce a warning775 def test_string_exc(self):776 s = """raise 'foo'"""777 self.warns_unchanged(s, "Python 3 does not support string exceptions")778 def test_string_exc_val(self):779 s = """raise "foo", 5"""780 self.warns_unchanged(s, "Python 3 does not support string exceptions")781 def test_string_exc_val_tb(self):782 s = """raise "foo", 5, 6"""783 self.warns_unchanged(s, "Python 3 does not support string exceptions")784 # These should result in traceback-assignment785 def test_tb_1(self):786 b = """def foo():787 raise Exception, 5, 6"""788 a = """def foo():789 raise Exception(5).with_traceback(6)"""790 self.check(b, a)791 def test_tb_2(self):792 b = """def foo():793 a = 5794 raise Exception, 5, 6795 b = 6"""796 a = """def foo():797 a = 5798 raise Exception(5).with_traceback(6)799 b = 6"""800 self.check(b, a)801 def test_tb_3(self):802 b = """def foo():803 raise Exception,5,6"""804 a = """def foo():805 raise Exception(5).with_traceback(6)"""806 self.check(b, a)807 def test_tb_4(self):808 b = """def foo():809 a = 5810 raise Exception,5,6811 b = 6"""812 a = """def foo():813 a = 5814 raise Exception(5).with_traceback(6)815 b = 6"""816 self.check(b, a)817 def test_tb_5(self):818 b = """def foo():819 raise Exception, (5, 6, 7), 6"""820 a = """def foo():821 raise Exception(5, 6, 7).with_traceback(6)"""822 self.check(b, a)823 def test_tb_6(self):824 b = """def foo():825 a = 5826 raise Exception, (5, 6, 7), 6827 b = 6"""828 a = """def foo():829 a = 5830 raise Exception(5, 6, 7).with_traceback(6)831 b = 6"""832 self.check(b, a)833class Test_throw(FixerTestCase):834 fixer = "throw"835 def test_1(self):836 b = """g.throw(Exception, 5)"""837 a = """g.throw(Exception(5))"""838 self.check(b, a)839 def test_2(self):840 b = """g.throw(Exception,5)"""841 a = """g.throw(Exception(5))"""842 self.check(b, a)843 def test_3(self):844 b = """g.throw(Exception, (5, 6, 7))"""845 a = """g.throw(Exception(5, 6, 7))"""846 self.check(b, a)847 def test_4(self):848 b = """5 + g.throw(Exception, 5)"""849 a = """5 + g.throw(Exception(5))"""850 self.check(b, a)851 # These should produce warnings852 def test_warn_1(self):853 s = """g.throw("foo")"""854 self.warns_unchanged(s, "Python 3 does not support string exceptions")855 def test_warn_2(self):856 s = """g.throw("foo", 5)"""857 self.warns_unchanged(s, "Python 3 does not support string exceptions")858 def test_warn_3(self):859 s = """g.throw("foo", 5, 6)"""860 self.warns_unchanged(s, "Python 3 does not support string exceptions")861 # These should not be touched862 def test_untouched_1(self):863 s = """g.throw(Exception)"""864 self.unchanged(s)865 def test_untouched_2(self):866 s = """g.throw(Exception(5, 6))"""867 self.unchanged(s)868 def test_untouched_3(self):869 s = """5 + g.throw(Exception(5, 6))"""870 self.unchanged(s)871 # These should result in traceback-assignment872 def test_tb_1(self):873 b = """def foo():874 g.throw(Exception, 5, 6)"""875 a = """def foo():876 g.throw(Exception(5).with_traceback(6))"""877 self.check(b, a)878 def test_tb_2(self):879 b = """def foo():880 a = 5881 g.throw(Exception, 5, 6)882 b = 6"""883 a = """def foo():884 a = 5885 g.throw(Exception(5).with_traceback(6))886 b = 6"""887 self.check(b, a)888 def test_tb_3(self):889 b = """def foo():890 g.throw(Exception,5,6)"""891 a = """def foo():892 g.throw(Exception(5).with_traceback(6))"""893 self.check(b, a)894 def test_tb_4(self):895 b = """def foo():896 a = 5897 g.throw(Exception,5,6)898 b = 6"""899 a = """def foo():900 a = 5901 g.throw(Exception(5).with_traceback(6))902 b = 6"""903 self.check(b, a)904 def test_tb_5(self):905 b = """def foo():906 g.throw(Exception, (5, 6, 7), 6)"""907 a = """def foo():908 g.throw(Exception(5, 6, 7).with_traceback(6))"""909 self.check(b, a)910 def test_tb_6(self):911 b = """def foo():912 a = 5913 g.throw(Exception, (5, 6, 7), 6)914 b = 6"""915 a = """def foo():916 a = 5917 g.throw(Exception(5, 6, 7).with_traceback(6))918 b = 6"""919 self.check(b, a)920 def test_tb_7(self):921 b = """def foo():922 a + g.throw(Exception, 5, 6)"""923 a = """def foo():924 a + g.throw(Exception(5).with_traceback(6))"""925 self.check(b, a)926 def test_tb_8(self):927 b = """def foo():928 a = 5929 a + g.throw(Exception, 5, 6)930 b = 6"""931 a = """def foo():932 a = 5933 a + g.throw(Exception(5).with_traceback(6))934 b = 6"""935 self.check(b, a)936class Test_long(FixerTestCase):937 fixer = "long"938 def test_1(self):939 b = """x = long(x)"""940 a = """x = int(x)"""941 self.check(b, a)942 def test_2(self):943 b = """y = isinstance(x, long)"""944 a = """y = isinstance(x, int)"""945 self.check(b, a)946 def test_3(self):947 b = """z = type(x) in (int, long)"""948 a = """z = type(x) in (int, int)"""949 self.check(b, a)950 def test_unchanged(self):951 s = """long = True"""952 self.unchanged(s)953 s = """s.long = True"""954 self.unchanged(s)955 s = """def long(): pass"""956 self.unchanged(s)957 s = """class long(): pass"""958 self.unchanged(s)959 s = """def f(long): pass"""960 self.unchanged(s)961 s = """def f(g, long): pass"""962 self.unchanged(s)963 s = """def f(x, long=True): pass"""964 self.unchanged(s)965 def test_prefix_preservation(self):966 b = """x = long( x )"""967 a = """x = int( x )"""968 self.check(b, a)969class Test_execfile(FixerTestCase):970 fixer = "execfile"971 def test_conversion(self):972 b = """execfile("fn")"""973 a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'))"""974 self.check(b, a)975 b = """execfile("fn", glob)"""976 a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), glob)"""977 self.check(b, a)978 b = """execfile("fn", glob, loc)"""979 a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), glob, loc)"""980 self.check(b, a)981 b = """execfile("fn", globals=glob)"""982 a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), globals=glob)"""983 self.check(b, a)984 b = """execfile("fn", locals=loc)"""985 a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), locals=loc)"""986 self.check(b, a)987 b = """execfile("fn", globals=glob, locals=loc)"""988 a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), globals=glob, locals=loc)"""989 self.check(b, a)990 def test_spacing(self):991 b = """execfile( "fn" )"""992 a = """exec(compile(open( "fn", "rb" ).read(), "fn", 'exec'))"""993 self.check(b, a)994 b = """execfile("fn", globals = glob)"""995 a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), globals = glob)"""996 self.check(b, a)997class Test_isinstance(FixerTestCase):998 fixer = "isinstance"999 def test_remove_multiple_items(self):1000 b = """isinstance(x, (int, int, int))"""1001 a = """isinstance(x, int)"""1002 self.check(b, a)1003 b = """isinstance(x, (int, float, int, int, float))"""1004 a = """isinstance(x, (int, float))"""1005 self.check(b, a)1006 b = """isinstance(x, (int, float, int, int, float, str))"""1007 a = """isinstance(x, (int, float, str))"""1008 self.check(b, a)1009 b = """isinstance(foo() + bar(), (x(), y(), x(), int, int))"""1010 a = """isinstance(foo() + bar(), (x(), y(), x(), int))"""1011 self.check(b, a)1012 def test_prefix_preservation(self):1013 b = """if isinstance( foo(), ( bar, bar, baz )) : pass"""1014 a = """if isinstance( foo(), ( bar, baz )) : pass"""1015 self.check(b, a)1016 def test_unchanged(self):1017 self.unchanged("isinstance(x, (str, int))")1018class Test_dict(FixerTestCase):1019 fixer = "dict"1020 def test_prefix_preservation(self):1021 b = "if d. keys ( ) : pass"1022 a = "if list(d. keys ( )) : pass"1023 self.check(b, a)1024 b = "if d. items ( ) : pass"1025 a = "if list(d. items ( )) : pass"1026 self.check(b, a)1027 b = "if d. iterkeys ( ) : pass"1028 a = "if iter(d. keys ( )) : pass"1029 self.check(b, a)1030 b = "[i for i in d. iterkeys( ) ]"1031 a = "[i for i in d. keys( ) ]"1032 self.check(b, a)1033 b = "if d. viewkeys ( ) : pass"1034 a = "if d. keys ( ) : pass"1035 self.check(b, a)1036 b = "[i for i in d. viewkeys( ) ]"1037 a = "[i for i in d. keys( ) ]"1038 self.check(b, a)1039 def test_trailing_comment(self):1040 b = "d.keys() # foo"1041 a = "list(d.keys()) # foo"1042 self.check(b, a)1043 b = "d.items() # foo"1044 a = "list(d.items()) # foo"1045 self.check(b, a)1046 b = "d.iterkeys() # foo"1047 a = "iter(d.keys()) # foo"1048 self.check(b, a)1049 b = """[i for i in d.iterkeys() # foo1050 ]"""1051 a = """[i for i in d.keys() # foo1052 ]"""1053 self.check(b, a)1054 b = """[i for i in d.iterkeys() # foo1055 ]"""1056 a = """[i for i in d.keys() # foo1057 ]"""1058 self.check(b, a)1059 b = "d.viewitems() # foo"1060 a = "d.items() # foo"1061 self.check(b, a)1062 def test_unchanged(self):1063 for wrapper in fixer_util.consuming_calls:1064 s = "s = %s(d.keys())" % wrapper1065 self.unchanged(s)1066 s = "s = %s(d.values())" % wrapper1067 self.unchanged(s)1068 s = "s = %s(d.items())" % wrapper1069 self.unchanged(s)1070 def test_01(self):1071 b = "d.keys()"1072 a = "list(d.keys())"1073 self.check(b, a)1074 b = "a[0].foo().keys()"1075 a = "list(a[0].foo().keys())"1076 self.check(b, a)1077 def test_02(self):1078 b = "d.items()"1079 a = "list(d.items())"1080 self.check(b, a)1081 def test_03(self):1082 b = "d.values()"1083 a = "list(d.values())"1084 self.check(b, a)1085 def test_04(self):1086 b = "d.iterkeys()"1087 a = "iter(d.keys())"1088 self.check(b, a)1089 def test_05(self):1090 b = "d.iteritems()"1091 a = "iter(d.items())"1092 self.check(b, a)1093 def test_06(self):1094 b = "d.itervalues()"1095 a = "iter(d.values())"1096 self.check(b, a)1097 def test_07(self):1098 s = "list(d.keys())"1099 self.unchanged(s)1100 def test_08(self):1101 s = "sorted(d.keys())"1102 self.unchanged(s)1103 def test_09(self):1104 b = "iter(d.keys())"1105 a = "iter(list(d.keys()))"1106 self.check(b, a)1107 def test_10(self):1108 b = "foo(d.keys())"1109 a = "foo(list(d.keys()))"1110 self.check(b, a)1111 def test_11(self):1112 b = "for i in d.keys(): print i"1113 a = "for i in list(d.keys()): print i"1114 self.check(b, a)1115 def test_12(self):1116 b = "for i in d.iterkeys(): print i"1117 a = "for i in d.keys(): print i"1118 self.check(b, a)1119 def test_13(self):1120 b = "[i for i in d.keys()]"1121 a = "[i for i in list(d.keys())]"1122 self.check(b, a)1123 def test_14(self):1124 b = "[i for i in d.iterkeys()]"1125 a = "[i for i in d.keys()]"1126 self.check(b, a)1127 def test_15(self):1128 b = "(i for i in d.keys())"1129 a = "(i for i in list(d.keys()))"1130 self.check(b, a)1131 def test_16(self):1132 b = "(i for i in d.iterkeys())"1133 a = "(i for i in d.keys())"1134 self.check(b, a)1135 def test_17(self):1136 b = "iter(d.iterkeys())"1137 a = "iter(d.keys())"1138 self.check(b, a)1139 def test_18(self):1140 b = "list(d.iterkeys())"1141 a = "list(d.keys())"1142 self.check(b, a)1143 def test_19(self):1144 b = "sorted(d.iterkeys())"1145 a = "sorted(d.keys())"1146 self.check(b, a)1147 def test_20(self):1148 b = "foo(d.iterkeys())"1149 a = "foo(iter(d.keys()))"1150 self.check(b, a)1151 def test_21(self):1152 b = "print h.iterkeys().next()"1153 a = "print iter(h.keys()).next()"1154 self.check(b, a)1155 def test_22(self):1156 b = "print h.keys()[0]"1157 a = "print list(h.keys())[0]"1158 self.check(b, a)1159 def test_23(self):1160 b = "print list(h.iterkeys().next())"1161 a = "print list(iter(h.keys()).next())"1162 self.check(b, a)1163 def test_24(self):1164 b = "for x in h.keys()[0]: print x"1165 a = "for x in list(h.keys())[0]: print x"1166 self.check(b, a)1167 def test_25(self):1168 b = "d.viewkeys()"1169 a = "d.keys()"1170 self.check(b, a)1171 def test_26(self):1172 b = "d.viewitems()"1173 a = "d.items()"1174 self.check(b, a)1175 def test_27(self):1176 b = "d.viewvalues()"1177 a = "d.values()"1178 self.check(b, a)1179 def test_28(self):1180 b = "[i for i in d.viewkeys()]"1181 a = "[i for i in d.keys()]"1182 self.check(b, a)1183 def test_29(self):1184 b = "(i for i in d.viewkeys())"1185 a = "(i for i in d.keys())"1186 self.check(b, a)1187 def test_30(self):1188 b = "iter(d.viewkeys())"1189 a = "iter(d.keys())"1190 self.check(b, a)1191 def test_31(self):1192 b = "list(d.viewkeys())"1193 a = "list(d.keys())"1194 self.check(b, a)1195 def test_32(self):1196 b = "sorted(d.viewkeys())"1197 a = "sorted(d.keys())"1198 self.check(b, a)1199class Test_xrange(FixerTestCase):1200 fixer = "xrange"1201 def test_prefix_preservation(self):1202 b = """x = xrange( 10 )"""1203 a = """x = range( 10 )"""1204 self.check(b, a)1205 b = """x = xrange( 1 , 10 )"""1206 a = """x = range( 1 , 10 )"""1207 self.check(b, a)1208 b = """x = xrange( 0 , 10 , 2 )"""1209 a = """x = range( 0 , 10 , 2 )"""1210 self.check(b, a)1211 def test_single_arg(self):1212 b = """x = xrange(10)"""1213 a = """x = range(10)"""1214 self.check(b, a)1215 def test_two_args(self):1216 b = """x = xrange(1, 10)"""1217 a = """x = range(1, 10)"""1218 self.check(b, a)1219 def test_three_args(self):1220 b = """x = xrange(0, 10, 2)"""1221 a = """x = range(0, 10, 2)"""1222 self.check(b, a)1223 def test_wrap_in_list(self):1224 b = """x = range(10, 3, 9)"""1225 a = """x = list(range(10, 3, 9))"""1226 self.check(b, a)1227 b = """x = foo(range(10, 3, 9))"""1228 a = """x = foo(list(range(10, 3, 9)))"""1229 self.check(b, a)1230 b = """x = range(10, 3, 9) + [4]"""1231 a = """x = list(range(10, 3, 9)) + [4]"""1232 self.check(b, a)1233 b = """x = range(10)[::-1]"""1234 a = """x = list(range(10))[::-1]"""1235 self.check(b, a)1236 b = """x = range(10) [3]"""1237 a = """x = list(range(10)) [3]"""1238 self.check(b, a)1239 def test_xrange_in_for(self):1240 b = """for i in xrange(10):\n j=i"""1241 a = """for i in range(10):\n j=i"""1242 self.check(b, a)1243 b = """[i for i in xrange(10)]"""1244 a = """[i for i in range(10)]"""1245 self.check(b, a)1246 def test_range_in_for(self):1247 self.unchanged("for i in range(10): pass")1248 self.unchanged("[i for i in range(10)]")1249 def test_in_contains_test(self):1250 self.unchanged("x in range(10, 3, 9)")1251 def test_in_consuming_context(self):1252 for call in fixer_util.consuming_calls:1253 self.unchanged("a = %s(range(10))" % call)1254class Test_xrange_with_reduce(FixerTestCase):1255 def setUp(self):1256 super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"])1257 def test_double_transform(self):1258 b = """reduce(x, xrange(5))"""1259 a = """from functools import reduce1260reduce(x, range(5))"""1261 self.check(b, a)1262class Test_raw_input(FixerTestCase):1263 fixer = "raw_input"1264 def test_prefix_preservation(self):1265 b = """x = raw_input( )"""1266 a = """x = input( )"""1267 self.check(b, a)1268 b = """x = raw_input( '' )"""1269 a = """x = input( '' )"""1270 self.check(b, a)1271 def test_1(self):1272 b = """x = raw_input()"""1273 a = """x = input()"""1274 self.check(b, a)1275 def test_2(self):1276 b = """x = raw_input('')"""1277 a = """x = input('')"""1278 self.check(b, a)1279 def test_3(self):1280 b = """x = raw_input('prompt')"""1281 a = """x = input('prompt')"""1282 self.check(b, a)1283 def test_4(self):1284 b = """x = raw_input(foo(a) + 6)"""1285 a = """x = input(foo(a) + 6)"""1286 self.check(b, a)1287 def test_5(self):1288 b = """x = raw_input(invite).split()"""1289 a = """x = input(invite).split()"""1290 self.check(b, a)1291 def test_6(self):1292 b = """x = raw_input(invite) . split ()"""1293 a = """x = input(invite) . split ()"""1294 self.check(b, a)1295 def test_8(self):1296 b = "x = int(raw_input())"1297 a = "x = int(input())"1298 self.check(b, a)1299class Test_funcattrs(FixerTestCase):1300 fixer = "funcattrs"1301 attrs = ["closure", "doc", "name", "defaults", "code", "globals", "dict"]1302 def test(self):1303 for attr in self.attrs:1304 b = "a.func_%s" % attr1305 a = "a.__%s__" % attr1306 self.check(b, a)1307 b = "self.foo.func_%s.foo_bar" % attr1308 a = "self.foo.__%s__.foo_bar" % attr1309 self.check(b, a)1310 def test_unchanged(self):1311 for attr in self.attrs:1312 s = "foo(func_%s + 5)" % attr1313 self.unchanged(s)1314 s = "f(foo.__%s__)" % attr1315 self.unchanged(s)1316 s = "f(foo.__%s__.foo)" % attr1317 self.unchanged(s)1318class Test_xreadlines(FixerTestCase):1319 fixer = "xreadlines"1320 def test_call(self):1321 b = "for x in f.xreadlines(): pass"1322 a = "for x in f: pass"1323 self.check(b, a)1324 b = "for x in foo().xreadlines(): pass"1325 a = "for x in foo(): pass"1326 self.check(b, a)1327 b = "for x in (5 + foo()).xreadlines(): pass"1328 a = "for x in (5 + foo()): pass"1329 self.check(b, a)1330 def test_attr_ref(self):1331 b = "foo(f.xreadlines + 5)"1332 a = "foo(f.__iter__ + 5)"1333 self.check(b, a)1334 b = "foo(f().xreadlines + 5)"1335 a = "foo(f().__iter__ + 5)"1336 self.check(b, a)1337 b = "foo((5 + f()).xreadlines + 5)"1338 a = "foo((5 + f()).__iter__ + 5)"1339 self.check(b, a)1340 def test_unchanged(self):1341 s = "for x in f.xreadlines(5): pass"1342 self.unchanged(s)1343 s = "for x in f.xreadlines(k=5): pass"1344 self.unchanged(s)1345 s = "for x in f.xreadlines(*k, **v): pass"1346 self.unchanged(s)1347 s = "foo(xreadlines)"1348 self.unchanged(s)1349class ImportsFixerTests:1350 def test_import_module(self):1351 for old, new in self.modules.items():1352 b = "import %s" % old1353 a = "import %s" % new1354 self.check(b, a)1355 b = "import foo, %s, bar" % old1356 a = "import foo, %s, bar" % new1357 self.check(b, a)1358 def test_import_from(self):1359 for old, new in self.modules.items():1360 b = "from %s import foo" % old1361 a = "from %s import foo" % new1362 self.check(b, a)1363 b = "from %s import foo, bar" % old1364 a = "from %s import foo, bar" % new1365 self.check(b, a)1366 b = "from %s import (yes, no)" % old1367 a = "from %s import (yes, no)" % new1368 self.check(b, a)1369 def test_import_module_as(self):1370 for old, new in self.modules.items():1371 b = "import %s as foo_bar" % old1372 a = "import %s as foo_bar" % new1373 self.check(b, a)1374 b = "import %s as foo_bar" % old1375 a = "import %s as foo_bar" % new1376 self.check(b, a)1377 def test_import_from_as(self):1378 for old, new in self.modules.items():1379 b = "from %s import foo as bar" % old1380 a = "from %s import foo as bar" % new1381 self.check(b, a)1382 def test_star(self):1383 for old, new in self.modules.items():1384 b = "from %s import *" % old1385 a = "from %s import *" % new1386 self.check(b, a)1387 def test_import_module_usage(self):1388 for old, new in self.modules.items():1389 b = """1390 import %s1391 foo(%s.bar)1392 """ % (old, old)1393 a = """1394 import %s1395 foo(%s.bar)1396 """ % (new, new)1397 self.check(b, a)1398 b = """1399 from %s import x1400 %s = 231401 """ % (old, old)1402 a = """1403 from %s import x1404 %s = 231405 """ % (new, old)1406 self.check(b, a)1407 s = """1408 def f():1409 %s.method()1410 """ % (old,)1411 self.unchanged(s)1412 # test nested usage1413 b = """1414 import %s1415 %s.bar(%s.foo)1416 """ % (old, old, old)1417 a = """1418 import %s1419 %s.bar(%s.foo)1420 """ % (new, new, new)1421 self.check(b, a)1422 b = """1423 import %s1424 x.%s1425 """ % (old, old)1426 a = """1427 import %s1428 x.%s1429 """ % (new, old)1430 self.check(b, a)1431class Test_imports(FixerTestCase, ImportsFixerTests):1432 fixer = "imports"1433 from ..fixes.fix_imports import MAPPING as modules1434 def test_multiple_imports(self):1435 b = """import urlparse, cStringIO"""1436 a = """import urllib.parse, io"""1437 self.check(b, a)1438 def test_multiple_imports_as(self):1439 b = """1440 import copy_reg as bar, HTMLParser as foo, urlparse1441 s = urlparse.spam(bar.foo())1442 """1443 a = """1444 import copyreg as bar, html.parser as foo, urllib.parse1445 s = urllib.parse.spam(bar.foo())1446 """1447 self.check(b, a)1448class Test_imports2(FixerTestCase, ImportsFixerTests):1449 fixer = "imports2"1450 from ..fixes.fix_imports2 import MAPPING as modules1451class Test_imports_fixer_order(FixerTestCase, ImportsFixerTests):1452 def setUp(self):1453 super(Test_imports_fixer_order, self).setUp(['imports', 'imports2'])1454 from ..fixes.fix_imports2 import MAPPING as mapping21455 self.modules = mapping2.copy()1456 from ..fixes.fix_imports import MAPPING as mapping11457 for key in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'):1458 self.modules[key] = mapping1[key]1459 def test_after_local_imports_refactoring(self):1460 for fix in ("imports", "imports2"):1461 self.fixer = fix1462 self.assert_runs_after("import")1463class Test_urllib(FixerTestCase):1464 fixer = "urllib"1465 from ..fixes.fix_urllib import MAPPING as modules1466 def test_import_module(self):1467 for old, changes in self.modules.items():1468 b = "import %s" % old1469 a = "import %s" % ", ".join(map(itemgetter(0), changes))1470 self.check(b, a)1471 def test_import_from(self):1472 for old, changes in self.modules.items():1473 all_members = []1474 for new, members in changes:1475 for member in members:1476 all_members.append(member)1477 b = "from %s import %s" % (old, member)1478 a = "from %s import %s" % (new, member)1479 self.check(b, a)1480 s = "from foo import %s" % member1481 self.unchanged(s)1482 b = "from %s import %s" % (old, ", ".join(members))1483 a = "from %s import %s" % (new, ", ".join(members))1484 self.check(b, a)1485 s = "from foo import %s" % ", ".join(members)1486 self.unchanged(s)1487 # test the breaking of a module into multiple replacements1488 b = "from %s import %s" % (old, ", ".join(all_members))1489 a = "\n".join(["from %s import %s" % (new, ", ".join(members))1490 for (new, members) in changes])1491 self.check(b, a)1492 def test_import_module_as(self):1493 for old in self.modules:1494 s = "import %s as foo" % old1495 self.warns_unchanged(s, "This module is now multiple modules")1496 def test_import_from_as(self):1497 for old, changes in self.modules.items():1498 for new, members in changes:1499 for member in members:1500 b = "from %s import %s as foo_bar" % (old, member)1501 a = "from %s import %s as foo_bar" % (new, member)1502 self.check(b, a)1503 b = "from %s import %s as blah, %s" % (old, member, member)1504 a = "from %s import %s as blah, %s" % (new, member, member)1505 self.check(b, a)1506 def test_star(self):1507 for old in self.modules:1508 s = "from %s import *" % old1509 self.warns_unchanged(s, "Cannot handle star imports")1510 def test_indented(self):1511 b = """1512def foo():1513 from urllib import urlencode, urlopen1514"""1515 a = """1516def foo():1517 from urllib.parse import urlencode1518 from urllib.request import urlopen1519"""1520 self.check(b, a)1521 b = """1522def foo():1523 other()1524 from urllib import urlencode, urlopen1525"""1526 a = """1527def foo():1528 other()1529 from urllib.parse import urlencode1530 from urllib.request import urlopen1531"""1532 self.check(b, a)1533 def test_import_module_usage(self):1534 for old, changes in self.modules.items():1535 for new, members in changes:1536 for member in members:1537 new_import = ", ".join([n for (n, mems)1538 in self.modules[old]])1539 b = """1540 import %s1541 foo(%s.%s)1542 """ % (old, old, member)1543 a = """1544 import %s1545 foo(%s.%s)1546 """ % (new_import, new, member)1547 self.check(b, a)1548 b = """1549 import %s1550 %s.%s(%s.%s)1551 """ % (old, old, member, old, member)1552 a = """1553 import %s1554 %s.%s(%s.%s)1555 """ % (new_import, new, member, new, member)1556 self.check(b, a)1557class Test_input(FixerTestCase):1558 fixer = "input"1559 def test_prefix_preservation(self):1560 b = """x = input( )"""1561 a = """x = eval(input( ))"""1562 self.check(b, a)1563 b = """x = input( '' )"""1564 a = """x = eval(input( '' ))"""1565 self.check(b, a)1566 def test_trailing_comment(self):1567 b = """x = input() # foo"""1568 a = """x = eval(input()) # foo"""1569 self.check(b, a)1570 def test_idempotency(self):1571 s = """x = eval(input())"""1572 self.unchanged(s)1573 s = """x = eval(input(''))"""1574 self.unchanged(s)1575 s = """x = eval(input(foo(5) + 9))"""1576 self.unchanged(s)1577 def test_1(self):1578 b = """x = input()"""1579 a = """x = eval(input())"""1580 self.check(b, a)1581 def test_2(self):1582 b = """x = input('')"""1583 a = """x = eval(input(''))"""1584 self.check(b, a)1585 def test_3(self):1586 b = """x = input('prompt')"""1587 a = """x = eval(input('prompt'))"""1588 self.check(b, a)1589 def test_4(self):1590 b = """x = input(foo(5) + 9)"""1591 a = """x = eval(input(foo(5) + 9))"""1592 self.check(b, a)1593class Test_tuple_params(FixerTestCase):1594 fixer = "tuple_params"1595 def test_unchanged_1(self):1596 s = """def foo(): pass"""1597 self.unchanged(s)1598 def test_unchanged_2(self):1599 s = """def foo(a, b, c): pass"""1600 self.unchanged(s)1601 def test_unchanged_3(self):1602 s = """def foo(a=3, b=4, c=5): pass"""1603 self.unchanged(s)1604 def test_1(self):1605 b = """1606 def foo(((a, b), c)):1607 x = 5"""1608 a = """1609 def foo(xxx_todo_changeme):1610 ((a, b), c) = xxx_todo_changeme1611 x = 5"""1612 self.check(b, a)1613 def test_2(self):1614 b = """1615 def foo(((a, b), c), d):1616 x = 5"""1617 a = """1618 def foo(xxx_todo_changeme, d):1619 ((a, b), c) = xxx_todo_changeme1620 x = 5"""1621 self.check(b, a)1622 def test_3(self):1623 b = """1624 def foo(((a, b), c), d) -> e:1625 x = 5"""1626 a = """1627 def foo(xxx_todo_changeme, d) -> e:1628 ((a, b), c) = xxx_todo_changeme1629 x = 5"""1630 self.check(b, a)1631 def test_semicolon(self):1632 b = """1633 def foo(((a, b), c)): x = 5; y = 7"""1634 a = """1635 def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme; x = 5; y = 7"""1636 self.check(b, a)1637 def test_keywords(self):1638 b = """1639 def foo(((a, b), c), d, e=5) -> z:1640 x = 5"""1641 a = """1642 def foo(xxx_todo_changeme, d, e=5) -> z:1643 ((a, b), c) = xxx_todo_changeme1644 x = 5"""1645 self.check(b, a)1646 def test_varargs(self):1647 b = """1648 def foo(((a, b), c), d, *vargs, **kwargs) -> z:1649 x = 5"""1650 a = """1651 def foo(xxx_todo_changeme, d, *vargs, **kwargs) -> z:1652 ((a, b), c) = xxx_todo_changeme1653 x = 5"""1654 self.check(b, a)1655 def test_multi_1(self):1656 b = """1657 def foo(((a, b), c), (d, e, f)) -> z:1658 x = 5"""1659 a = """1660 def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:1661 ((a, b), c) = xxx_todo_changeme1662 (d, e, f) = xxx_todo_changeme11663 x = 5"""1664 self.check(b, a)1665 def test_multi_2(self):1666 b = """1667 def foo(x, ((a, b), c), d, (e, f, g), y) -> z:1668 x = 5"""1669 a = """1670 def foo(x, xxx_todo_changeme, d, xxx_todo_changeme1, y) -> z:1671 ((a, b), c) = xxx_todo_changeme1672 (e, f, g) = xxx_todo_changeme11673 x = 5"""1674 self.check(b, a)1675 def test_docstring(self):1676 b = """1677 def foo(((a, b), c), (d, e, f)) -> z:1678 "foo foo foo foo"1679 x = 5"""1680 a = """1681 def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:1682 "foo foo foo foo"1683 ((a, b), c) = xxx_todo_changeme1684 (d, e, f) = xxx_todo_changeme11685 x = 5"""1686 self.check(b, a)1687 def test_lambda_no_change(self):1688 s = """lambda x: x + 5"""1689 self.unchanged(s)1690 def test_lambda_parens_single_arg(self):1691 b = """lambda (x): x + 5"""1692 a = """lambda x: x + 5"""1693 self.check(b, a)1694 b = """lambda(x): x + 5"""1695 a = """lambda x: x + 5"""1696 self.check(b, a)1697 b = """lambda ((((x)))): x + 5"""1698 a = """lambda x: x + 5"""1699 self.check(b, a)1700 b = """lambda((((x)))): x + 5"""1701 a = """lambda x: x + 5"""1702 self.check(b, a)1703 def test_lambda_simple(self):1704 b = """lambda (x, y): x + f(y)"""1705 a = """lambda x_y: x_y[0] + f(x_y[1])"""1706 self.check(b, a)1707 b = """lambda(x, y): x + f(y)"""1708 a = """lambda x_y: x_y[0] + f(x_y[1])"""1709 self.check(b, a)1710 b = """lambda (((x, y))): x + f(y)"""1711 a = """lambda x_y: x_y[0] + f(x_y[1])"""1712 self.check(b, a)1713 b = """lambda(((x, y))): x + f(y)"""1714 a = """lambda x_y: x_y[0] + f(x_y[1])"""1715 self.check(b, a)1716 def test_lambda_one_tuple(self):1717 b = """lambda (x,): x + f(x)"""1718 a = """lambda x1: x1[0] + f(x1[0])"""1719 self.check(b, a)1720 b = """lambda (((x,))): x + f(x)"""1721 a = """lambda x1: x1[0] + f(x1[0])"""1722 self.check(b, a)1723 def test_lambda_simple_multi_use(self):1724 b = """lambda (x, y): x + x + f(x) + x"""1725 a = """lambda x_y: x_y[0] + x_y[0] + f(x_y[0]) + x_y[0]"""1726 self.check(b, a)1727 def test_lambda_simple_reverse(self):1728 b = """lambda (x, y): y + x"""1729 a = """lambda x_y: x_y[1] + x_y[0]"""1730 self.check(b, a)1731 def test_lambda_nested(self):1732 b = """lambda (x, (y, z)): x + y + z"""1733 a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""1734 self.check(b, a)1735 b = """lambda (((x, (y, z)))): x + y + z"""1736 a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""1737 self.check(b, a)1738 def test_lambda_nested_multi_use(self):1739 b = """lambda (x, (y, z)): x + y + f(y)"""1740 a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + f(x_y_z[1][0])"""1741 self.check(b, a)1742class Test_methodattrs(FixerTestCase):1743 fixer = "methodattrs"1744 attrs = ["func", "self", "class"]1745 def test(self):1746 for attr in self.attrs:1747 b = "a.im_%s" % attr1748 if attr == "class":1749 a = "a.__self__.__class__"1750 else:1751 a = "a.__%s__" % attr1752 self.check(b, a)1753 b = "self.foo.im_%s.foo_bar" % attr1754 if attr == "class":1755 a = "self.foo.__self__.__class__.foo_bar"1756 else:1757 a = "self.foo.__%s__.foo_bar" % attr1758 self.check(b, a)1759 def test_unchanged(self):1760 for attr in self.attrs:1761 s = "foo(im_%s + 5)" % attr1762 self.unchanged(s)1763 s = "f(foo.__%s__)" % attr1764 self.unchanged(s)1765 s = "f(foo.__%s__.foo)" % attr1766 self.unchanged(s)1767class Test_next(FixerTestCase):1768 fixer = "next"1769 def test_1(self):1770 b = """it.next()"""1771 a = """next(it)"""1772 self.check(b, a)1773 def test_2(self):1774 b = """a.b.c.d.next()"""1775 a = """next(a.b.c.d)"""1776 self.check(b, a)1777 def test_3(self):1778 b = """(a + b).next()"""1779 a = """next((a + b))"""1780 self.check(b, a)1781 def test_4(self):1782 b = """a().next()"""1783 a = """next(a())"""1784 self.check(b, a)1785 def test_5(self):1786 b = """a().next() + b"""1787 a = """next(a()) + b"""1788 self.check(b, a)1789 def test_6(self):1790 b = """c( a().next() + b)"""1791 a = """c( next(a()) + b)"""1792 self.check(b, a)1793 def test_prefix_preservation_1(self):1794 b = """1795 for a in b:1796 foo(a)1797 a.next()1798 """1799 a = """1800 for a in b:1801 foo(a)1802 next(a)1803 """1804 self.check(b, a)1805 def test_prefix_preservation_2(self):1806 b = """1807 for a in b:1808 foo(a) # abc1809 # def1810 a.next()1811 """1812 a = """1813 for a in b:1814 foo(a) # abc1815 # def1816 next(a)1817 """1818 self.check(b, a)1819 def test_prefix_preservation_3(self):1820 b = """1821 next = 51822 for a in b:1823 foo(a)1824 a.next()1825 """1826 a = """1827 next = 51828 for a in b:1829 foo(a)1830 a.__next__()1831 """1832 self.check(b, a, ignore_warnings=True)1833 def test_prefix_preservation_4(self):1834 b = """1835 next = 51836 for a in b:1837 foo(a) # abc1838 # def1839 a.next()1840 """1841 a = """1842 next = 51843 for a in b:1844 foo(a) # abc1845 # def1846 a.__next__()1847 """1848 self.check(b, a, ignore_warnings=True)1849 def test_prefix_preservation_5(self):1850 b = """1851 next = 51852 for a in b:1853 foo(foo(a), # abc1854 a.next())1855 """1856 a = """1857 next = 51858 for a in b:1859 foo(foo(a), # abc1860 a.__next__())1861 """1862 self.check(b, a, ignore_warnings=True)1863 def test_prefix_preservation_6(self):1864 b = """1865 for a in b:1866 foo(foo(a), # abc1867 a.next())1868 """1869 a = """1870 for a in b:1871 foo(foo(a), # abc1872 next(a))1873 """1874 self.check(b, a)1875 def test_method_1(self):1876 b = """1877 class A:1878 def next(self):1879 pass1880 """1881 a = """1882 class A:1883 def __next__(self):1884 pass1885 """1886 self.check(b, a)1887 def test_method_2(self):1888 b = """1889 class A(object):1890 def next(self):1891 pass1892 """1893 a = """1894 class A(object):1895 def __next__(self):1896 pass1897 """1898 self.check(b, a)1899 def test_method_3(self):1900 b = """1901 class A:1902 def next(x):1903 pass1904 """1905 a = """1906 class A:1907 def __next__(x):1908 pass1909 """1910 self.check(b, a)1911 def test_method_4(self):1912 b = """1913 class A:1914 def __init__(self, foo):1915 self.foo = foo1916 def next(self):1917 pass1918 def __iter__(self):1919 return self1920 """1921 a = """1922 class A:1923 def __init__(self, foo):1924 self.foo = foo1925 def __next__(self):1926 pass1927 def __iter__(self):1928 return self1929 """1930 self.check(b, a)1931 def test_method_unchanged(self):1932 s = """1933 class A:1934 def next(self, a, b):1935 pass1936 """1937 self.unchanged(s)1938 def test_shadowing_assign_simple(self):1939 s = """1940 next = foo1941 class A:1942 def next(self, a, b):1943 pass1944 """1945 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")1946 def test_shadowing_assign_tuple_1(self):1947 s = """1948 (next, a) = foo1949 class A:1950 def next(self, a, b):1951 pass1952 """1953 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")1954 def test_shadowing_assign_tuple_2(self):1955 s = """1956 (a, (b, (next, c)), a) = foo1957 class A:1958 def next(self, a, b):1959 pass1960 """1961 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")1962 def test_shadowing_assign_list_1(self):1963 s = """1964 [next, a] = foo1965 class A:1966 def next(self, a, b):1967 pass1968 """1969 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")1970 def test_shadowing_assign_list_2(self):1971 s = """1972 [a, [b, [next, c]], a] = foo1973 class A:1974 def next(self, a, b):1975 pass1976 """1977 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")1978 def test_builtin_assign(self):1979 s = """1980 def foo():1981 __builtin__.next = foo1982 class A:1983 def next(self, a, b):1984 pass1985 """1986 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")1987 def test_builtin_assign_in_tuple(self):1988 s = """1989 def foo():1990 (a, __builtin__.next) = foo1991 class A:1992 def next(self, a, b):1993 pass1994 """1995 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")1996 def test_builtin_assign_in_list(self):1997 s = """1998 def foo():1999 [a, __builtin__.next] = foo2000 class A:2001 def next(self, a, b):2002 pass2003 """2004 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2005 def test_assign_to_next(self):2006 s = """2007 def foo():2008 A.next = foo2009 class A:2010 def next(self, a, b):2011 pass2012 """2013 self.unchanged(s)2014 def test_assign_to_next_in_tuple(self):2015 s = """2016 def foo():2017 (a, A.next) = foo2018 class A:2019 def next(self, a, b):2020 pass2021 """2022 self.unchanged(s)2023 def test_assign_to_next_in_list(self):2024 s = """2025 def foo():2026 [a, A.next] = foo2027 class A:2028 def next(self, a, b):2029 pass2030 """2031 self.unchanged(s)2032 def test_shadowing_import_1(self):2033 s = """2034 import foo.bar as next2035 class A:2036 def next(self, a, b):2037 pass2038 """2039 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2040 def test_shadowing_import_2(self):2041 s = """2042 import bar, bar.foo as next2043 class A:2044 def next(self, a, b):2045 pass2046 """2047 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2048 def test_shadowing_import_3(self):2049 s = """2050 import bar, bar.foo as next, baz2051 class A:2052 def next(self, a, b):2053 pass2054 """2055 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2056 def test_shadowing_import_from_1(self):2057 s = """2058 from x import next2059 class A:2060 def next(self, a, b):2061 pass2062 """2063 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2064 def test_shadowing_import_from_2(self):2065 s = """2066 from x.a import next2067 class A:2068 def next(self, a, b):2069 pass2070 """2071 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2072 def test_shadowing_import_from_3(self):2073 s = """2074 from x import a, next, b2075 class A:2076 def next(self, a, b):2077 pass2078 """2079 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2080 def test_shadowing_import_from_4(self):2081 s = """2082 from x.a import a, next, b2083 class A:2084 def next(self, a, b):2085 pass2086 """2087 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2088 def test_shadowing_funcdef_1(self):2089 s = """2090 def next(a):2091 pass2092 class A:2093 def next(self, a, b):2094 pass2095 """2096 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2097 def test_shadowing_funcdef_2(self):2098 b = """2099 def next(a):2100 pass2101 class A:2102 def next(self):2103 pass2104 it.next()2105 """2106 a = """2107 def next(a):2108 pass2109 class A:2110 def __next__(self):2111 pass2112 it.__next__()2113 """2114 self.warns(b, a, "Calls to builtin next() possibly shadowed")2115 def test_shadowing_global_1(self):2116 s = """2117 def f():2118 global next2119 next = 52120 """2121 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2122 def test_shadowing_global_2(self):2123 s = """2124 def f():2125 global a, next, b2126 next = 52127 """2128 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2129 def test_shadowing_for_simple(self):2130 s = """2131 for next in it():2132 pass2133 b = 52134 c = 62135 """2136 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2137 def test_shadowing_for_tuple_1(self):2138 s = """2139 for next, b in it():2140 pass2141 b = 52142 c = 62143 """2144 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2145 def test_shadowing_for_tuple_2(self):2146 s = """2147 for a, (next, c), b in it():2148 pass2149 b = 52150 c = 62151 """2152 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")2153 def test_noncall_access_1(self):2154 b = """gnext = g.next"""2155 a = """gnext = g.__next__"""2156 self.check(b, a)2157 def test_noncall_access_2(self):2158 b = """f(g.next + 5)"""2159 a = """f(g.__next__ + 5)"""2160 self.check(b, a)2161 def test_noncall_access_3(self):2162 b = """f(g().next + 5)"""2163 a = """f(g().__next__ + 5)"""2164 self.check(b, a)2165class Test_nonzero(FixerTestCase):2166 fixer = "nonzero"2167 def test_1(self):2168 b = """2169 class A:2170 def __nonzero__(self):2171 pass2172 """2173 a = """2174 class A:2175 def __bool__(self):2176 pass2177 """2178 self.check(b, a)2179 def test_2(self):2180 b = """2181 class A(object):2182 def __nonzero__(self):2183 pass2184 """2185 a = """2186 class A(object):2187 def __bool__(self):2188 pass2189 """2190 self.check(b, a)2191 def test_unchanged_1(self):2192 s = """2193 class A(object):2194 def __bool__(self):2195 pass2196 """2197 self.unchanged(s)2198 def test_unchanged_2(self):2199 s = """2200 class A(object):2201 def __nonzero__(self, a):2202 pass2203 """2204 self.unchanged(s)2205 def test_unchanged_func(self):2206 s = """2207 def __nonzero__(self):2208 pass2209 """2210 self.unchanged(s)2211class Test_numliterals(FixerTestCase):2212 fixer = "numliterals"2213 def test_octal_1(self):2214 b = """0755"""2215 a = """0o755"""2216 self.check(b, a)2217 def test_long_int_1(self):2218 b = """a = 12L"""2219 a = """a = 12"""2220 self.check(b, a)2221 def test_long_int_2(self):2222 b = """a = 12l"""2223 a = """a = 12"""2224 self.check(b, a)2225 def test_long_hex(self):2226 b = """b = 0x12l"""2227 a = """b = 0x12"""2228 self.check(b, a)2229 def test_comments_and_spacing(self):2230 b = """b = 0x12L"""2231 a = """b = 0x12"""2232 self.check(b, a)2233 b = """b = 0755 # spam"""2234 a = """b = 0o755 # spam"""2235 self.check(b, a)2236 def test_unchanged_int(self):2237 s = """5"""2238 self.unchanged(s)2239 def test_unchanged_float(self):2240 s = """5.0"""2241 self.unchanged(s)2242 def test_unchanged_octal(self):2243 s = """0o755"""2244 self.unchanged(s)2245 def test_unchanged_hex(self):2246 s = """0xABC"""2247 self.unchanged(s)2248 def test_unchanged_exp(self):2249 s = """5.0e10"""2250 self.unchanged(s)2251 def test_unchanged_complex_int(self):2252 s = """5 + 4j"""2253 self.unchanged(s)2254 def test_unchanged_complex_float(self):2255 s = """5.4 + 4.9j"""2256 self.unchanged(s)2257 def test_unchanged_complex_bare(self):2258 s = """4j"""2259 self.unchanged(s)2260 s = """4.4j"""2261 self.unchanged(s)2262class Test_renames(FixerTestCase):2263 fixer = "renames"2264 modules = {"sys": ("maxint", "maxsize"),2265 }2266 def test_import_from(self):2267 for mod, (old, new) in list(self.modules.items()):2268 b = "from %s import %s" % (mod, old)2269 a = "from %s import %s" % (mod, new)2270 self.check(b, a)2271 s = "from foo import %s" % old2272 self.unchanged(s)2273 def test_import_from_as(self):2274 for mod, (old, new) in list(self.modules.items()):2275 b = "from %s import %s as foo_bar" % (mod, old)2276 a = "from %s import %s as foo_bar" % (mod, new)2277 self.check(b, a)2278 def test_import_module_usage(self):2279 for mod, (old, new) in list(self.modules.items()):2280 b = """2281 import %s2282 foo(%s, %s.%s)2283 """ % (mod, mod, mod, old)2284 a = """2285 import %s2286 foo(%s, %s.%s)2287 """ % (mod, mod, mod, new)2288 self.check(b, a)2289 def XXX_test_from_import_usage(self):2290 # not implemented yet2291 for mod, (old, new) in list(self.modules.items()):2292 b = """2293 from %s import %s2294 foo(%s, %s)2295 """ % (mod, old, mod, old)2296 a = """2297 from %s import %s2298 foo(%s, %s)2299 """ % (mod, new, mod, new)2300 self.check(b, a)2301class Test_unicode(FixerTestCase):2302 fixer = "unicode"2303 def test_whitespace(self):2304 b = """unicode( x)"""2305 a = """str( x)"""2306 self.check(b, a)2307 b = """ unicode(x )"""2308 a = """ str(x )"""2309 self.check(b, a)2310 b = """ u'h'"""2311 a = """ 'h'"""2312 self.check(b, a)2313 def test_unicode_call(self):2314 b = """unicode(x, y, z)"""2315 a = """str(x, y, z)"""2316 self.check(b, a)2317 def test_unichr(self):2318 b = """unichr(u'h')"""2319 a = """chr('h')"""2320 self.check(b, a)2321 def test_unicode_literal_1(self):2322 b = '''u"x"'''2323 a = '''"x"'''2324 self.check(b, a)2325 def test_unicode_literal_2(self):2326 b = """ur'x'"""2327 a = """r'x'"""2328 self.check(b, a)2329 def test_unicode_literal_3(self):2330 b = """UR'''x''' """2331 a = """R'''x''' """2332 self.check(b, a)2333 def test_native_literal_escape_u(self):2334 b = r"""'\\\u20ac\U0001d121\\u20ac'"""2335 a = r"""'\\\\u20ac\\U0001d121\\u20ac'"""2336 self.check(b, a)2337 b = r"""r'\\\u20ac\U0001d121\\u20ac'"""2338 a = r"""r'\\\u20ac\U0001d121\\u20ac'"""2339 self.check(b, a)2340 def test_bytes_literal_escape_u(self):2341 b = r"""b'\\\u20ac\U0001d121\\u20ac'"""2342 a = r"""b'\\\u20ac\U0001d121\\u20ac'"""2343 self.check(b, a)2344 b = r"""br'\\\u20ac\U0001d121\\u20ac'"""2345 a = r"""br'\\\u20ac\U0001d121\\u20ac'"""2346 self.check(b, a)2347 def test_unicode_literal_escape_u(self):2348 b = r"""u'\\\u20ac\U0001d121\\u20ac'"""2349 a = r"""'\\\u20ac\U0001d121\\u20ac'"""2350 self.check(b, a)2351 b = r"""ur'\\\u20ac\U0001d121\\u20ac'"""2352 a = r"""r'\\\u20ac\U0001d121\\u20ac'"""2353 self.check(b, a)2354 def test_native_unicode_literal_escape_u(self):2355 f = 'from __future__ import unicode_literals\n'2356 b = f + r"""'\\\u20ac\U0001d121\\u20ac'"""2357 a = f + r"""'\\\u20ac\U0001d121\\u20ac'"""2358 self.check(b, a)2359 b = f + r"""r'\\\u20ac\U0001d121\\u20ac'"""2360 a = f + r"""r'\\\u20ac\U0001d121\\u20ac'"""2361 self.check(b, a)2362class Test_filter(FixerTestCase):2363 fixer = "filter"2364 def test_prefix_preservation(self):2365 b = """x = filter( foo, 'abc' )"""2366 a = """x = list(filter( foo, 'abc' ))"""2367 self.check(b, a)2368 b = """x = filter( None , 'abc' )"""2369 a = """x = [_f for _f in 'abc' if _f]"""2370 self.check(b, a)2371 def test_filter_basic(self):2372 b = """x = filter(None, 'abc')"""2373 a = """x = [_f for _f in 'abc' if _f]"""2374 self.check(b, a)2375 b = """x = len(filter(f, 'abc'))"""2376 a = """x = len(list(filter(f, 'abc')))"""2377 self.check(b, a)2378 b = """x = filter(lambda x: x%2 == 0, range(10))"""2379 a = """x = [x for x in range(10) if x%2 == 0]"""2380 self.check(b, a)2381 # Note the parens around x2382 b = """x = filter(lambda (x): x%2 == 0, range(10))"""2383 a = """x = [x for x in range(10) if x%2 == 0]"""2384 self.check(b, a)2385 def test_filter_trailers(self):2386 b = """x = filter(None, 'abc')[0]"""2387 a = """x = [_f for _f in 'abc' if _f][0]"""2388 self.check(b, a)2389 b = """x = len(filter(f, 'abc')[0])"""2390 a = """x = len(list(filter(f, 'abc'))[0])"""2391 self.check(b, a)2392 b = """x = filter(lambda x: x%2 == 0, range(10))[0]"""2393 a = """x = [x for x in range(10) if x%2 == 0][0]"""2394 self.check(b, a)2395 # Note the parens around x2396 b = """x = filter(lambda (x): x%2 == 0, range(10))[0]"""2397 a = """x = [x for x in range(10) if x%2 == 0][0]"""2398 self.check(b, a)2399 def test_filter_nochange(self):2400 a = """b.join(filter(f, 'abc'))"""2401 self.unchanged(a)2402 a = """(a + foo(5)).join(filter(f, 'abc'))"""2403 self.unchanged(a)2404 a = """iter(filter(f, 'abc'))"""2405 self.unchanged(a)2406 a = """list(filter(f, 'abc'))"""2407 self.unchanged(a)2408 a = """list(filter(f, 'abc'))[0]"""2409 self.unchanged(a)2410 a = """set(filter(f, 'abc'))"""2411 self.unchanged(a)2412 a = """set(filter(f, 'abc')).pop()"""2413 self.unchanged(a)2414 a = """tuple(filter(f, 'abc'))"""2415 self.unchanged(a)2416 a = """any(filter(f, 'abc'))"""2417 self.unchanged(a)2418 a = """all(filter(f, 'abc'))"""2419 self.unchanged(a)2420 a = """sum(filter(f, 'abc'))"""2421 self.unchanged(a)2422 a = """sorted(filter(f, 'abc'))"""2423 self.unchanged(a)2424 a = """sorted(filter(f, 'abc'), key=blah)"""2425 self.unchanged(a)2426 a = """sorted(filter(f, 'abc'), key=blah)[0]"""2427 self.unchanged(a)2428 a = """enumerate(filter(f, 'abc'))"""2429 self.unchanged(a)2430 a = """enumerate(filter(f, 'abc'), start=1)"""2431 self.unchanged(a)2432 a = """for i in filter(f, 'abc'): pass"""2433 self.unchanged(a)2434 a = """[x for x in filter(f, 'abc')]"""2435 self.unchanged(a)2436 a = """(x for x in filter(f, 'abc'))"""2437 self.unchanged(a)2438 def test_future_builtins(self):2439 a = "from future_builtins import spam, filter; filter(f, 'ham')"2440 self.unchanged(a)2441 b = """from future_builtins import spam; x = filter(f, 'abc')"""2442 a = """from future_builtins import spam; x = list(filter(f, 'abc'))"""2443 self.check(b, a)2444 a = "from future_builtins import *; filter(f, 'ham')"2445 self.unchanged(a)2446class Test_map(FixerTestCase):2447 fixer = "map"2448 def check(self, b, a):2449 self.unchanged("from future_builtins import map; " + b, a)2450 super(Test_map, self).check(b, a)2451 def test_prefix_preservation(self):2452 b = """x = map( f, 'abc' )"""2453 a = """x = list(map( f, 'abc' ))"""2454 self.check(b, a)2455 def test_map_trailers(self):2456 b = """x = map(f, 'abc')[0]"""2457 a = """x = list(map(f, 'abc'))[0]"""2458 self.check(b, a)2459 b = """x = map(None, l)[0]"""2460 a = """x = list(l)[0]"""2461 self.check(b, a)2462 b = """x = map(lambda x:x, l)[0]"""2463 a = """x = [x for x in l][0]"""2464 self.check(b, a)2465 b = """x = map(f, 'abc')[0][1]"""2466 a = """x = list(map(f, 'abc'))[0][1]"""2467 self.check(b, a)2468 def test_trailing_comment(self):2469 b = """x = map(f, 'abc') # foo"""2470 a = """x = list(map(f, 'abc')) # foo"""2471 self.check(b, a)2472 def test_None_with_multiple_arguments(self):2473 s = """x = map(None, a, b, c)"""2474 self.warns_unchanged(s, "cannot convert map(None, ...) with "2475 "multiple arguments")2476 def test_map_basic(self):2477 b = """x = map(f, 'abc')"""2478 a = """x = list(map(f, 'abc'))"""2479 self.check(b, a)2480 b = """x = len(map(f, 'abc', 'def'))"""2481 a = """x = len(list(map(f, 'abc', 'def')))"""2482 self.check(b, a)2483 b = """x = map(None, 'abc')"""2484 a = """x = list('abc')"""2485 self.check(b, a)2486 b = """x = map(lambda x: x+1, range(4))"""2487 a = """x = [x+1 for x in range(4)]"""2488 self.check(b, a)2489 # Note the parens around x2490 b = """x = map(lambda (x): x+1, range(4))"""2491 a = """x = [x+1 for x in range(4)]"""2492 self.check(b, a)2493 b = """2494 foo()2495 # foo2496 map(f, x)2497 """2498 a = """2499 foo()2500 # foo2501 list(map(f, x))2502 """2503 self.warns(b, a, "You should use a for loop here")2504 def test_map_nochange(self):2505 a = """b.join(map(f, 'abc'))"""2506 self.unchanged(a)2507 a = """(a + foo(5)).join(map(f, 'abc'))"""2508 self.unchanged(a)2509 a = """iter(map(f, 'abc'))"""2510 self.unchanged(a)2511 a = """list(map(f, 'abc'))"""2512 self.unchanged(a)2513 a = """list(map(f, 'abc'))[0]"""2514 self.unchanged(a)2515 a = """set(map(f, 'abc'))"""2516 self.unchanged(a)2517 a = """set(map(f, 'abc')).pop()"""2518 self.unchanged(a)2519 a = """tuple(map(f, 'abc'))"""2520 self.unchanged(a)2521 a = """any(map(f, 'abc'))"""2522 self.unchanged(a)2523 a = """all(map(f, 'abc'))"""2524 self.unchanged(a)2525 a = """sum(map(f, 'abc'))"""2526 self.unchanged(a)2527 a = """sorted(map(f, 'abc'))"""2528 self.unchanged(a)2529 a = """sorted(map(f, 'abc'), key=blah)"""2530 self.unchanged(a)2531 a = """sorted(map(f, 'abc'), key=blah)[0]"""2532 self.unchanged(a)2533 a = """enumerate(map(f, 'abc'))"""2534 self.unchanged(a)2535 a = """enumerate(map(f, 'abc'), start=1)"""2536 self.unchanged(a)2537 a = """for i in map(f, 'abc'): pass"""2538 self.unchanged(a)2539 a = """[x for x in map(f, 'abc')]"""2540 self.unchanged(a)2541 a = """(x for x in map(f, 'abc'))"""2542 self.unchanged(a)2543 def test_future_builtins(self):2544 a = "from future_builtins import spam, map, eggs; map(f, 'ham')"2545 self.unchanged(a)2546 b = """from future_builtins import spam, eggs; x = map(f, 'abc')"""2547 a = """from future_builtins import spam, eggs; x = list(map(f, 'abc'))"""2548 self.check(b, a)2549 a = "from future_builtins import *; map(f, 'ham')"2550 self.unchanged(a)2551class Test_zip(FixerTestCase):2552 fixer = "zip"2553 def check(self, b, a):2554 self.unchanged("from future_builtins import zip; " + b, a)2555 super(Test_zip, self).check(b, a)2556 def test_zip_basic(self):2557 b = """x = zip()"""2558 a = """x = list(zip())"""2559 self.check(b, a)2560 b = """x = zip(a, b, c)"""2561 a = """x = list(zip(a, b, c))"""2562 self.check(b, a)2563 b = """x = len(zip(a, b))"""2564 a = """x = len(list(zip(a, b)))"""2565 self.check(b, a)2566 def test_zip_trailers(self):2567 b = """x = zip(a, b, c)[0]"""2568 a = """x = list(zip(a, b, c))[0]"""2569 self.check(b, a)2570 b = """x = zip(a, b, c)[0][1]"""2571 a = """x = list(zip(a, b, c))[0][1]"""2572 self.check(b, a)2573 def test_zip_nochange(self):2574 a = """b.join(zip(a, b))"""2575 self.unchanged(a)2576 a = """(a + foo(5)).join(zip(a, b))"""2577 self.unchanged(a)2578 a = """iter(zip(a, b))"""2579 self.unchanged(a)2580 a = """list(zip(a, b))"""2581 self.unchanged(a)2582 a = """list(zip(a, b))[0]"""2583 self.unchanged(a)2584 a = """set(zip(a, b))"""2585 self.unchanged(a)2586 a = """set(zip(a, b)).pop()"""2587 self.unchanged(a)2588 a = """tuple(zip(a, b))"""2589 self.unchanged(a)2590 a = """any(zip(a, b))"""2591 self.unchanged(a)2592 a = """all(zip(a, b))"""2593 self.unchanged(a)2594 a = """sum(zip(a, b))"""2595 self.unchanged(a)2596 a = """sorted(zip(a, b))"""2597 self.unchanged(a)2598 a = """sorted(zip(a, b), key=blah)"""2599 self.unchanged(a)2600 a = """sorted(zip(a, b), key=blah)[0]"""2601 self.unchanged(a)2602 a = """enumerate(zip(a, b))"""2603 self.unchanged(a)2604 a = """enumerate(zip(a, b), start=1)"""2605 self.unchanged(a)2606 a = """for i in zip(a, b): pass"""2607 self.unchanged(a)2608 a = """[x for x in zip(a, b)]"""2609 self.unchanged(a)2610 a = """(x for x in zip(a, b))"""2611 self.unchanged(a)2612 def test_future_builtins(self):2613 a = "from future_builtins import spam, zip, eggs; zip(a, b)"2614 self.unchanged(a)2615 b = """from future_builtins import spam, eggs; x = zip(a, b)"""2616 a = """from future_builtins import spam, eggs; x = list(zip(a, b))"""2617 self.check(b, a)2618 a = "from future_builtins import *; zip(a, b)"2619 self.unchanged(a)2620class Test_standarderror(FixerTestCase):2621 fixer = "standarderror"2622 def test(self):2623 b = """x = StandardError()"""2624 a = """x = Exception()"""2625 self.check(b, a)2626 b = """x = StandardError(a, b, c)"""2627 a = """x = Exception(a, b, c)"""2628 self.check(b, a)2629 b = """f(2 + StandardError(a, b, c))"""2630 a = """f(2 + Exception(a, b, c))"""2631 self.check(b, a)2632class Test_types(FixerTestCase):2633 fixer = "types"2634 def test_basic_types_convert(self):2635 b = """types.StringType"""2636 a = """bytes"""2637 self.check(b, a)2638 b = """types.DictType"""2639 a = """dict"""2640 self.check(b, a)2641 b = """types . IntType"""2642 a = """int"""2643 self.check(b, a)2644 b = """types.ListType"""2645 a = """list"""2646 self.check(b, a)2647 b = """types.LongType"""2648 a = """int"""2649 self.check(b, a)2650 b = """types.NoneType"""2651 a = """type(None)"""2652 self.check(b, a)2653 b = "types.StringTypes"2654 a = "(str,)"2655 self.check(b, a)2656class Test_idioms(FixerTestCase):2657 fixer = "idioms"2658 def test_while(self):2659 b = """while 1: foo()"""2660 a = """while True: foo()"""2661 self.check(b, a)2662 b = """while 1: foo()"""2663 a = """while True: foo()"""2664 self.check(b, a)2665 b = """2666 while 1:2667 foo()2668 """2669 a = """2670 while True:2671 foo()2672 """2673 self.check(b, a)2674 def test_while_unchanged(self):2675 s = """while 11: foo()"""2676 self.unchanged(s)2677 s = """while 0: foo()"""2678 self.unchanged(s)2679 s = """while foo(): foo()"""2680 self.unchanged(s)2681 s = """while []: foo()"""2682 self.unchanged(s)2683 def test_eq_simple(self):2684 b = """type(x) == T"""2685 a = """isinstance(x, T)"""2686 self.check(b, a)2687 b = """if type(x) == T: pass"""2688 a = """if isinstance(x, T): pass"""2689 self.check(b, a)2690 def test_eq_reverse(self):2691 b = """T == type(x)"""2692 a = """isinstance(x, T)"""2693 self.check(b, a)2694 b = """if T == type(x): pass"""2695 a = """if isinstance(x, T): pass"""2696 self.check(b, a)2697 def test_eq_expression(self):2698 b = """type(x+y) == d.get('T')"""2699 a = """isinstance(x+y, d.get('T'))"""2700 self.check(b, a)2701 b = """type( x + y) == d.get('T')"""2702 a = """isinstance(x + y, d.get('T'))"""2703 self.check(b, a)2704 def test_is_simple(self):2705 b = """type(x) is T"""2706 a = """isinstance(x, T)"""2707 self.check(b, a)2708 b = """if type(x) is T: pass"""2709 a = """if isinstance(x, T): pass"""2710 self.check(b, a)2711 def test_is_reverse(self):2712 b = """T is type(x)"""2713 a = """isinstance(x, T)"""2714 self.check(b, a)2715 b = """if T is type(x): pass"""2716 a = """if isinstance(x, T): pass"""2717 self.check(b, a)2718 def test_is_expression(self):2719 b = """type(x+y) is d.get('T')"""2720 a = """isinstance(x+y, d.get('T'))"""2721 self.check(b, a)2722 b = """type( x + y) is d.get('T')"""2723 a = """isinstance(x + y, d.get('T'))"""2724 self.check(b, a)2725 def test_is_not_simple(self):2726 b = """type(x) is not T"""2727 a = """not isinstance(x, T)"""2728 self.check(b, a)2729 b = """if type(x) is not T: pass"""2730 a = """if not isinstance(x, T): pass"""2731 self.check(b, a)2732 def test_is_not_reverse(self):2733 b = """T is not type(x)"""2734 a = """not isinstance(x, T)"""2735 self.check(b, a)2736 b = """if T is not type(x): pass"""2737 a = """if not isinstance(x, T): pass"""2738 self.check(b, a)2739 def test_is_not_expression(self):2740 b = """type(x+y) is not d.get('T')"""2741 a = """not isinstance(x+y, d.get('T'))"""2742 self.check(b, a)2743 b = """type( x + y) is not d.get('T')"""2744 a = """not isinstance(x + y, d.get('T'))"""2745 self.check(b, a)2746 def test_ne_simple(self):2747 b = """type(x) != T"""2748 a = """not isinstance(x, T)"""2749 self.check(b, a)2750 b = """if type(x) != T: pass"""2751 a = """if not isinstance(x, T): pass"""2752 self.check(b, a)2753 def test_ne_reverse(self):2754 b = """T != type(x)"""2755 a = """not isinstance(x, T)"""2756 self.check(b, a)2757 b = """if T != type(x): pass"""2758 a = """if not isinstance(x, T): pass"""2759 self.check(b, a)2760 def test_ne_expression(self):2761 b = """type(x+y) != d.get('T')"""2762 a = """not isinstance(x+y, d.get('T'))"""2763 self.check(b, a)2764 b = """type( x + y) != d.get('T')"""2765 a = """not isinstance(x + y, d.get('T'))"""2766 self.check(b, a)2767 def test_type_unchanged(self):2768 a = """type(x).__name__"""2769 self.unchanged(a)2770 def test_sort_list_call(self):2771 b = """2772 v = list(t)2773 v.sort()2774 foo(v)2775 """2776 a = """2777 v = sorted(t)2778 foo(v)2779 """2780 self.check(b, a)2781 b = """2782 v = list(foo(b) + d)2783 v.sort()2784 foo(v)2785 """2786 a = """2787 v = sorted(foo(b) + d)2788 foo(v)2789 """2790 self.check(b, a)2791 b = """2792 while x:2793 v = list(t)2794 v.sort()2795 foo(v)2796 """2797 a = """2798 while x:2799 v = sorted(t)2800 foo(v)2801 """2802 self.check(b, a)2803 b = """2804 v = list(t)2805 # foo2806 v.sort()2807 foo(v)2808 """2809 a = """2810 v = sorted(t)2811 # foo2812 foo(v)2813 """2814 self.check(b, a)2815 b = r"""2816 v = list( t)2817 v.sort()2818 foo(v)2819 """2820 a = r"""2821 v = sorted( t)2822 foo(v)2823 """2824 self.check(b, a)2825 b = r"""2826 try:2827 m = list(s)2828 m.sort()2829 except: pass2830 """2831 a = r"""2832 try:2833 m = sorted(s)2834 except: pass2835 """2836 self.check(b, a)2837 b = r"""2838 try:2839 m = list(s)2840 # foo2841 m.sort()2842 except: pass2843 """2844 a = r"""2845 try:2846 m = sorted(s)2847 # foo2848 except: pass2849 """2850 self.check(b, a)2851 b = r"""2852 m = list(s)2853 # more comments2854 m.sort()"""2855 a = r"""2856 m = sorted(s)2857 # more comments"""2858 self.check(b, a)2859 def test_sort_simple_expr(self):2860 b = """2861 v = t2862 v.sort()2863 foo(v)2864 """2865 a = """2866 v = sorted(t)2867 foo(v)2868 """2869 self.check(b, a)2870 b = """2871 v = foo(b)2872 v.sort()2873 foo(v)2874 """2875 a = """2876 v = sorted(foo(b))2877 foo(v)2878 """2879 self.check(b, a)2880 b = """2881 v = b.keys()2882 v.sort()2883 foo(v)2884 """2885 a = """2886 v = sorted(b.keys())2887 foo(v)2888 """2889 self.check(b, a)2890 b = """2891 v = foo(b) + d2892 v.sort()2893 foo(v)2894 """2895 a = """2896 v = sorted(foo(b) + d)2897 foo(v)2898 """2899 self.check(b, a)2900 b = """2901 while x:2902 v = t2903 v.sort()2904 foo(v)2905 """2906 a = """2907 while x:2908 v = sorted(t)2909 foo(v)2910 """2911 self.check(b, a)2912 b = """2913 v = t2914 # foo2915 v.sort()2916 foo(v)2917 """2918 a = """2919 v = sorted(t)2920 # foo2921 foo(v)2922 """2923 self.check(b, a)2924 b = r"""2925 v = t2926 v.sort()2927 foo(v)2928 """2929 a = r"""2930 v = sorted(t)2931 foo(v)2932 """2933 self.check(b, a)2934 def test_sort_unchanged(self):2935 s = """2936 v = list(t)2937 w.sort()2938 foo(w)2939 """2940 self.unchanged(s)2941 s = """2942 v = list(t)2943 v.sort(u)2944 foo(v)2945 """2946 self.unchanged(s)2947class Test_basestring(FixerTestCase):2948 fixer = "basestring"2949 def test_basestring(self):2950 b = """isinstance(x, basestring)"""2951 a = """isinstance(x, str)"""2952 self.check(b, a)2953class Test_buffer(FixerTestCase):2954 fixer = "buffer"2955 def test_buffer(self):2956 b = """x = buffer(y)"""2957 a = """x = memoryview(y)"""2958 self.check(b, a)2959 def test_slicing(self):2960 b = """buffer(y)[4:5]"""2961 a = """memoryview(y)[4:5]"""2962 self.check(b, a)2963class Test_future(FixerTestCase):2964 fixer = "future"2965 def test_future(self):2966 b = """from __future__ import braces"""2967 a = """"""2968 self.check(b, a)2969 b = """# comment\nfrom __future__ import braces"""2970 a = """# comment\n"""2971 self.check(b, a)2972 b = """from __future__ import braces\n# comment"""2973 a = """\n# comment"""2974 self.check(b, a)2975 def test_run_order(self):2976 self.assert_runs_after('print')2977class Test_itertools(FixerTestCase):2978 fixer = "itertools"2979 def checkall(self, before, after):2980 # Because we need to check with and without the itertools prefix2981 # and on each of the three functions, these loops make it all2982 # much easier2983 for i in ('itertools.', ''):2984 for f in ('map', 'filter', 'zip'):2985 b = before %(i+'i'+f)2986 a = after %(f)2987 self.check(b, a)2988 def test_0(self):2989 # A simple example -- test_1 covers exactly the same thing,2990 # but it's not quite as clear.2991 b = "itertools.izip(a, b)"2992 a = "zip(a, b)"2993 self.check(b, a)2994 def test_1(self):2995 b = """%s(f, a)"""2996 a = """%s(f, a)"""2997 self.checkall(b, a)2998 def test_qualified(self):2999 b = """itertools.ifilterfalse(a, b)"""3000 a = """itertools.filterfalse(a, b)"""3001 self.check(b, a)3002 b = """itertools.izip_longest(a, b)"""3003 a = """itertools.zip_longest(a, b)"""3004 self.check(b, a)3005 def test_2(self):3006 b = """ifilterfalse(a, b)"""3007 a = """filterfalse(a, b)"""3008 self.check(b, a)3009 b = """izip_longest(a, b)"""3010 a = """zip_longest(a, b)"""3011 self.check(b, a)3012 def test_space_1(self):3013 b = """ %s(f, a)"""3014 a = """ %s(f, a)"""3015 self.checkall(b, a)3016 def test_space_2(self):3017 b = """ itertools.ifilterfalse(a, b)"""3018 a = """ itertools.filterfalse(a, b)"""3019 self.check(b, a)3020 b = """ itertools.izip_longest(a, b)"""3021 a = """ itertools.zip_longest(a, b)"""3022 self.check(b, a)3023 def test_run_order(self):3024 self.assert_runs_after('map', 'zip', 'filter')3025class Test_itertools_imports(FixerTestCase):3026 fixer = 'itertools_imports'3027 def test_reduced(self):3028 b = "from itertools import imap, izip, foo"3029 a = "from itertools import foo"3030 self.check(b, a)3031 b = "from itertools import bar, imap, izip, foo"3032 a = "from itertools import bar, foo"3033 self.check(b, a)3034 b = "from itertools import chain, imap, izip"3035 a = "from itertools import chain"3036 self.check(b, a)3037 def test_comments(self):3038 b = "#foo\nfrom itertools import imap, izip"3039 a = "#foo\n"3040 self.check(b, a)3041 def test_none(self):3042 b = "from itertools import imap, izip"3043 a = ""3044 self.check(b, a)3045 b = "from itertools import izip"3046 a = ""3047 self.check(b, a)3048 def test_import_as(self):3049 b = "from itertools import izip, bar as bang, imap"3050 a = "from itertools import bar as bang"3051 self.check(b, a)3052 b = "from itertools import izip as _zip, imap, bar"3053 a = "from itertools import bar"3054 self.check(b, a)3055 b = "from itertools import imap as _map"3056 a = ""3057 self.check(b, a)3058 b = "from itertools import imap as _map, izip as _zip"3059 a = ""3060 self.check(b, a)3061 s = "from itertools import bar as bang"3062 self.unchanged(s)3063 def test_ifilter_and_zip_longest(self):3064 for name in "filterfalse", "zip_longest":3065 b = "from itertools import i%s" % (name,)3066 a = "from itertools import %s" % (name,)3067 self.check(b, a)3068 b = "from itertools import imap, i%s, foo" % (name,)3069 a = "from itertools import %s, foo" % (name,)3070 self.check(b, a)3071 b = "from itertools import bar, i%s, foo" % (name,)3072 a = "from itertools import bar, %s, foo" % (name,)3073 self.check(b, a)3074 def test_import_star(self):3075 s = "from itertools import *"3076 self.unchanged(s)3077 def test_unchanged(self):3078 s = "from itertools import foo"3079 self.unchanged(s)3080class Test_import(FixerTestCase):3081 fixer = "import"3082 def setUp(self):3083 super(Test_import, self).setUp()3084 # Need to replace fix_import's exists method3085 # so we can check that it's doing the right thing3086 self.files_checked = []3087 self.present_files = set()3088 self.always_exists = True3089 def fake_exists(name):3090 self.files_checked.append(name)3091 return self.always_exists or (name in self.present_files)3092 from lib2to3.fixes import fix_import3093 fix_import.exists = fake_exists3094 def tearDown(self):3095 from lib2to3.fixes import fix_import3096 fix_import.exists = os.path.exists3097 def check_both(self, b, a):3098 self.always_exists = True3099 super(Test_import, self).check(b, a)3100 self.always_exists = False3101 super(Test_import, self).unchanged(b)3102 def test_files_checked(self):3103 def p(path):3104 # Takes a unix path and returns a path with correct separators3105 return os.path.pathsep.join(path.split("/"))3106 self.always_exists = False3107 self.present_files = set(['__init__.py'])3108 expected_extensions = ('.py', os.path.sep, '.pyc', '.so', '.sl', '.pyd')3109 names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))3110 for name in names_to_test:3111 self.files_checked = []3112 self.filename = name3113 self.unchanged("import jam")3114 if os.path.dirname(name):3115 name = os.path.dirname(name) + '/jam'3116 else:3117 name = 'jam'3118 expected_checks = set(name + ext for ext in expected_extensions)3119 expected_checks.add("__init__.py")3120 self.assertEqual(set(self.files_checked), expected_checks)3121 def test_not_in_package(self):3122 s = "import bar"3123 self.always_exists = False3124 self.present_files = set(["bar.py"])3125 self.unchanged(s)3126 def test_with_absolute_import_enabled(self):3127 s = "from __future__ import absolute_import\nimport bar"3128 self.always_exists = False3129 self.present_files = set(["__init__.py", "bar.py"])3130 self.unchanged(s)3131 def test_in_package(self):3132 b = "import bar"3133 a = "from . import bar"3134 self.always_exists = False3135 self.present_files = set(["__init__.py", "bar.py"])3136 self.check(b, a)3137 def test_import_from_package(self):3138 b = "import bar"3139 a = "from . import bar"3140 self.always_exists = False3141 self.present_files = set(["__init__.py", "bar" + os.path.sep])3142 self.check(b, a)3143 def test_already_relative_import(self):3144 s = "from . import bar"3145 self.unchanged(s)3146 def test_comments_and_indent(self):3147 b = "import bar # Foo"3148 a = "from . import bar # Foo"3149 self.check(b, a)3150 def test_from(self):3151 b = "from foo import bar, baz"3152 a = "from .foo import bar, baz"3153 self.check_both(b, a)3154 b = "from foo import bar"3155 a = "from .foo import bar"3156 self.check_both(b, a)3157 b = "from foo import (bar, baz)"3158 a = "from .foo import (bar, baz)"3159 self.check_both(b, a)3160 def test_dotted_from(self):3161 b = "from green.eggs import ham"3162 a = "from .green.eggs import ham"3163 self.check_both(b, a)3164 def test_from_as(self):3165 b = "from green.eggs import ham as spam"3166 a = "from .green.eggs import ham as spam"3167 self.check_both(b, a)3168 def test_import(self):3169 b = "import foo"3170 a = "from . import foo"3171 self.check_both(b, a)3172 b = "import foo, bar"3173 a = "from . import foo, bar"3174 self.check_both(b, a)3175 b = "import foo, bar, x"3176 a = "from . import foo, bar, x"3177 self.check_both(b, a)3178 b = "import x, y, z"3179 a = "from . import x, y, z"3180 self.check_both(b, a)3181 def test_import_as(self):3182 b = "import foo as x"3183 a = "from . import foo as x"3184 self.check_both(b, a)3185 b = "import a as b, b as c, c as d"3186 a = "from . import a as b, b as c, c as d"3187 self.check_both(b, a)3188 def test_local_and_absolute(self):3189 self.always_exists = False3190 self.present_files = set(["foo.py", "__init__.py"])3191 s = "import foo, bar"3192 self.warns_unchanged(s, "absolute and local imports together")3193 def test_dotted_import(self):3194 b = "import foo.bar"3195 a = "from . import foo.bar"3196 self.check_both(b, a)3197 def test_dotted_import_as(self):3198 b = "import foo.bar as bang"3199 a = "from . import foo.bar as bang"3200 self.check_both(b, a)3201 def test_prefix(self):3202 b = """3203 # prefix3204 import foo.bar3205 """3206 a = """3207 # prefix3208 from . import foo.bar3209 """3210 self.check_both(b, a)3211class Test_set_literal(FixerTestCase):3212 fixer = "set_literal"3213 def test_basic(self):3214 b = """set([1, 2, 3])"""3215 a = """{1, 2, 3}"""3216 self.check(b, a)3217 b = """set((1, 2, 3))"""3218 a = """{1, 2, 3}"""3219 self.check(b, a)3220 b = """set((1,))"""3221 a = """{1}"""3222 self.check(b, a)3223 b = """set([1])"""3224 self.check(b, a)3225 b = """set((a, b))"""3226 a = """{a, b}"""3227 self.check(b, a)3228 b = """set([a, b])"""3229 self.check(b, a)3230 b = """set((a*234, f(args=23)))"""3231 a = """{a*234, f(args=23)}"""3232 self.check(b, a)3233 b = """set([a*23, f(23)])"""3234 a = """{a*23, f(23)}"""3235 self.check(b, a)3236 b = """set([a-234**23])"""3237 a = """{a-234**23}"""3238 self.check(b, a)3239 def test_listcomps(self):3240 b = """set([x for x in y])"""3241 a = """{x for x in y}"""3242 self.check(b, a)3243 b = """set([x for x in y if x == m])"""3244 a = """{x for x in y if x == m}"""3245 self.check(b, a)3246 b = """set([x for x in y for a in b])"""3247 a = """{x for x in y for a in b}"""3248 self.check(b, a)3249 b = """set([f(x) - 23 for x in y])"""3250 a = """{f(x) - 23 for x in y}"""3251 self.check(b, a)3252 def test_whitespace(self):3253 b = """set( [1, 2])"""3254 a = """{1, 2}"""3255 self.check(b, a)3256 b = """set([1 , 2])"""3257 a = """{1 , 2}"""3258 self.check(b, a)3259 b = """set([ 1 ])"""3260 a = """{ 1 }"""3261 self.check(b, a)3262 b = """set( [1] )"""3263 a = """{1}"""3264 self.check(b, a)3265 b = """set([ 1, 2 ])"""3266 a = """{ 1, 2 }"""3267 self.check(b, a)3268 b = """set([x for x in y ])"""3269 a = """{x for x in y }"""3270 self.check(b, a)3271 b = """set(3272 [1, 2]3273 )3274 """3275 a = """{1, 2}\n"""3276 self.check(b, a)3277 def test_comments(self):3278 b = """set((1, 2)) # Hi"""3279 a = """{1, 2} # Hi"""3280 self.check(b, a)3281 # This isn't optimal behavior, but the fixer is optional.3282 b = """3283 # Foo3284 set( # Bar3285 (1, 2)3286 )3287 """3288 a = """3289 # Foo3290 {1, 2}3291 """3292 self.check(b, a)3293 def test_unchanged(self):3294 s = """set()"""3295 self.unchanged(s)3296 s = """set(a)"""3297 self.unchanged(s)3298 s = """set(a, b, c)"""3299 self.unchanged(s)3300 # Don't transform generators because they might have to be lazy.3301 s = """set(x for x in y)"""3302 self.unchanged(s)3303 s = """set(x for x in y if z)"""3304 self.unchanged(s)3305 s = """set(a*823-23**2 + f(23))"""3306 self.unchanged(s)3307class Test_sys_exc(FixerTestCase):3308 fixer = "sys_exc"3309 def test_0(self):3310 b = "sys.exc_type"3311 a = "sys.exc_info()[0]"3312 self.check(b, a)3313 def test_1(self):3314 b = "sys.exc_value"3315 a = "sys.exc_info()[1]"3316 self.check(b, a)3317 def test_2(self):3318 b = "sys.exc_traceback"3319 a = "sys.exc_info()[2]"3320 self.check(b, a)3321 def test_3(self):3322 b = "sys.exc_type # Foo"3323 a = "sys.exc_info()[0] # Foo"3324 self.check(b, a)3325 def test_4(self):3326 b = "sys. exc_type"3327 a = "sys. exc_info()[0]"3328 self.check(b, a)3329 def test_5(self):3330 b = "sys .exc_type"3331 a = "sys .exc_info()[0]"3332 self.check(b, a)3333class Test_paren(FixerTestCase):3334 fixer = "paren"3335 def test_0(self):3336 b = """[i for i in 1, 2 ]"""3337 a = """[i for i in (1, 2) ]"""3338 self.check(b, a)3339 def test_1(self):3340 b = """[i for i in 1, 2, ]"""3341 a = """[i for i in (1, 2,) ]"""3342 self.check(b, a)3343 def test_2(self):3344 b = """[i for i in 1, 2 ]"""3345 a = """[i for i in (1, 2) ]"""3346 self.check(b, a)3347 def test_3(self):3348 b = """[i for i in 1, 2 if i]"""3349 a = """[i for i in (1, 2) if i]"""3350 self.check(b, a)3351 def test_4(self):3352 b = """[i for i in 1, 2 ]"""3353 a = """[i for i in (1, 2) ]"""3354 self.check(b, a)3355 def test_5(self):3356 b = """(i for i in 1, 2)"""3357 a = """(i for i in (1, 2))"""3358 self.check(b, a)3359 def test_6(self):3360 b = """(i for i in 1 ,2 if i)"""3361 a = """(i for i in (1 ,2) if i)"""3362 self.check(b, a)3363 def test_unchanged_0(self):3364 s = """[i for i in (1, 2)]"""3365 self.unchanged(s)3366 def test_unchanged_1(self):3367 s = """[i for i in foo()]"""3368 self.unchanged(s)3369 def test_unchanged_2(self):3370 s = """[i for i in (1, 2) if nothing]"""3371 self.unchanged(s)3372 def test_unchanged_3(self):3373 s = """(i for i in (1, 2))"""3374 self.unchanged(s)3375 def test_unchanged_4(self):3376 s = """[i for i in m]"""3377 self.unchanged(s)3378class Test_metaclass(FixerTestCase):3379 fixer = 'metaclass'3380 def test_unchanged(self):3381 self.unchanged("class X(): pass")3382 self.unchanged("class X(object): pass")3383 self.unchanged("class X(object1, object2): pass")3384 self.unchanged("class X(object1, object2, object3): pass")3385 self.unchanged("class X(metaclass=Meta): pass")3386 self.unchanged("class X(b, arg=23, metclass=Meta): pass")3387 self.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass")3388 s = """3389 class X:3390 def __metaclass__(self): pass3391 """3392 self.unchanged(s)3393 s = """3394 class X:3395 a[23] = 743396 """3397 self.unchanged(s)3398 def test_comments(self):3399 b = """3400 class X:3401 # hi3402 __metaclass__ = AppleMeta3403 """3404 a = """3405 class X(metaclass=AppleMeta):3406 # hi3407 pass3408 """3409 self.check(b, a)3410 b = """3411 class X:3412 __metaclass__ = Meta3413 # Bedtime!3414 """3415 a = """3416 class X(metaclass=Meta):3417 pass3418 # Bedtime!3419 """3420 self.check(b, a)3421 def test_meta(self):3422 # no-parent class, odd body3423 b = """3424 class X():3425 __metaclass__ = Q3426 pass3427 """3428 a = """3429 class X(metaclass=Q):3430 pass3431 """3432 self.check(b, a)3433 # one parent class, no body3434 b = """class X(object): __metaclass__ = Q"""3435 a = """class X(object, metaclass=Q): pass"""3436 self.check(b, a)3437 # one parent, simple body3438 b = """3439 class X(object):3440 __metaclass__ = Meta3441 bar = 73442 """3443 a = """3444 class X(object, metaclass=Meta):3445 bar = 73446 """3447 self.check(b, a)3448 b = """3449 class X:3450 __metaclass__ = Meta; x = 4; g = 233451 """3452 a = """3453 class X(metaclass=Meta):3454 x = 4; g = 233455 """3456 self.check(b, a)3457 # one parent, simple body, __metaclass__ last3458 b = """3459 class X(object):3460 bar = 73461 __metaclass__ = Meta3462 """3463 a = """3464 class X(object, metaclass=Meta):3465 bar = 73466 """3467 self.check(b, a)3468 # redefining __metaclass__3469 b = """3470 class X():3471 __metaclass__ = A3472 __metaclass__ = B3473 bar = 73474 """3475 a = """3476 class X(metaclass=B):3477 bar = 73478 """3479 self.check(b, a)3480 # multiple inheritance, simple body3481 b = """3482 class X(clsA, clsB):3483 __metaclass__ = Meta3484 bar = 73485 """3486 a = """3487 class X(clsA, clsB, metaclass=Meta):3488 bar = 73489 """3490 self.check(b, a)3491 # keywords in the class statement3492 b = """class m(a, arg=23): __metaclass__ = Meta"""3493 a = """class m(a, arg=23, metaclass=Meta): pass"""3494 self.check(b, a)3495 b = """3496 class X(expression(2 + 4)):3497 __metaclass__ = Meta3498 """3499 a = """3500 class X(expression(2 + 4), metaclass=Meta):3501 pass3502 """3503 self.check(b, a)3504 b = """3505 class X(expression(2 + 4), x**4):3506 __metaclass__ = Meta3507 """3508 a = """3509 class X(expression(2 + 4), x**4, metaclass=Meta):3510 pass3511 """3512 self.check(b, a)3513 b = """3514 class X:3515 __metaclass__ = Meta3516 save.py = 233517 """3518 a = """3519 class X(metaclass=Meta):3520 save.py = 233521 """3522 self.check(b, a)3523class Test_getcwdu(FixerTestCase):3524 fixer = 'getcwdu'3525 def test_basic(self):3526 b = """os.getcwdu"""3527 a = """os.getcwd"""3528 self.check(b, a)3529 b = """os.getcwdu()"""3530 a = """os.getcwd()"""3531 self.check(b, a)3532 b = """meth = os.getcwdu"""3533 a = """meth = os.getcwd"""3534 self.check(b, a)3535 b = """os.getcwdu(args)"""3536 a = """os.getcwd(args)"""3537 self.check(b, a)3538 def test_comment(self):3539 b = """os.getcwdu() # Foo"""3540 a = """os.getcwd() # Foo"""3541 self.check(b, a)3542 def test_unchanged(self):3543 s = """os.getcwd()"""3544 self.unchanged(s)3545 s = """getcwdu()"""3546 self.unchanged(s)3547 s = """os.getcwdb()"""3548 self.unchanged(s)3549 def test_indentation(self):3550 b = """3551 if 1:3552 os.getcwdu()3553 """3554 a = """3555 if 1:3556 os.getcwd()3557 """3558 self.check(b, a)3559 def test_multilation(self):3560 b = """os .getcwdu()"""3561 a = """os .getcwd()"""3562 self.check(b, a)3563 b = """os. getcwdu"""3564 a = """os. getcwd"""3565 self.check(b, a)3566 b = """os.getcwdu ( )"""3567 a = """os.getcwd ( )"""3568 self.check(b, a)3569class Test_operator(FixerTestCase):3570 fixer = "operator"3571 def test_operator_isCallable(self):3572 b = "operator.isCallable(x)"3573 a = "callable(x)"3574 self.check(b, a)3575 def test_operator_sequenceIncludes(self):3576 b = "operator.sequenceIncludes(x, y)"3577 a = "operator.contains(x, y)"3578 self.check(b, a)3579 b = "operator .sequenceIncludes(x, y)"3580 a = "operator .contains(x, y)"3581 self.check(b, a)3582 b = "operator. sequenceIncludes(x, y)"3583 a = "operator. contains(x, y)"3584 self.check(b, a)3585 def test_operator_isSequenceType(self):3586 b = "operator.isSequenceType(x)"3587 a = "import collections.abc\nisinstance(x, collections.abc.Sequence)"3588 self.check(b, a)3589 def test_operator_isMappingType(self):3590 b = "operator.isMappingType(x)"3591 a = "import collections.abc\nisinstance(x, collections.abc.Mapping)"3592 self.check(b, a)3593 def test_operator_isNumberType(self):3594 b = "operator.isNumberType(x)"3595 a = "import numbers\nisinstance(x, numbers.Number)"3596 self.check(b, a)3597 def test_operator_repeat(self):3598 b = "operator.repeat(x, n)"3599 a = "operator.mul(x, n)"3600 self.check(b, a)3601 b = "operator .repeat(x, n)"3602 a = "operator .mul(x, n)"3603 self.check(b, a)3604 b = "operator. repeat(x, n)"3605 a = "operator. mul(x, n)"3606 self.check(b, a)3607 def test_operator_irepeat(self):3608 b = "operator.irepeat(x, n)"3609 a = "operator.imul(x, n)"3610 self.check(b, a)3611 b = "operator .irepeat(x, n)"3612 a = "operator .imul(x, n)"3613 self.check(b, a)3614 b = "operator. irepeat(x, n)"3615 a = "operator. imul(x, n)"3616 self.check(b, a)3617 def test_bare_isCallable(self):3618 s = "isCallable(x)"3619 t = "You should use 'callable(x)' here."3620 self.warns_unchanged(s, t)3621 def test_bare_sequenceIncludes(self):3622 s = "sequenceIncludes(x, y)"3623 t = "You should use 'operator.contains(x, y)' here."3624 self.warns_unchanged(s, t)3625 def test_bare_operator_isSequenceType(self):3626 s = "isSequenceType(z)"3627 t = "You should use 'isinstance(z, collections.abc.Sequence)' here."3628 self.warns_unchanged(s, t)3629 def test_bare_operator_isMappingType(self):3630 s = "isMappingType(x)"3631 t = "You should use 'isinstance(x, collections.abc.Mapping)' here."3632 self.warns_unchanged(s, t)3633 def test_bare_operator_isNumberType(self):3634 s = "isNumberType(y)"3635 t = "You should use 'isinstance(y, numbers.Number)' here."3636 self.warns_unchanged(s, t)3637 def test_bare_operator_repeat(self):3638 s = "repeat(x, n)"3639 t = "You should use 'operator.mul(x, n)' here."3640 self.warns_unchanged(s, t)3641 def test_bare_operator_irepeat(self):3642 s = "irepeat(y, 187)"3643 t = "You should use 'operator.imul(y, 187)' here."3644 self.warns_unchanged(s, t)3645class Test_exitfunc(FixerTestCase):3646 fixer = "exitfunc"3647 def test_simple(self):3648 b = """3649 import sys3650 sys.exitfunc = my_atexit3651 """3652 a = """3653 import sys3654 import atexit3655 atexit.register(my_atexit)3656 """3657 self.check(b, a)3658 def test_names_import(self):3659 b = """3660 import sys, crumbs3661 sys.exitfunc = my_func3662 """3663 a = """3664 import sys, crumbs, atexit3665 atexit.register(my_func)3666 """3667 self.check(b, a)3668 def test_complex_expression(self):3669 b = """3670 import sys3671 sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression3672 """3673 a = """3674 import sys3675 import atexit3676 atexit.register(do(d)/a()+complex(f=23, g=23)*expression)3677 """3678 self.check(b, a)3679 def test_comments(self):3680 b = """3681 import sys # Foo3682 sys.exitfunc = f # Blah3683 """3684 a = """3685 import sys3686 import atexit # Foo3687 atexit.register(f) # Blah3688 """3689 self.check(b, a)3690 b = """3691 import apples, sys, crumbs, larry # Pleasant comments3692 sys.exitfunc = func3693 """3694 a = """3695 import apples, sys, crumbs, larry, atexit # Pleasant comments3696 atexit.register(func)3697 """3698 self.check(b, a)3699 def test_in_a_function(self):3700 b = """3701 import sys3702 def f():3703 sys.exitfunc = func3704 """3705 a = """3706 import sys3707 import atexit3708 def f():3709 atexit.register(func)3710 """3711 self.check(b, a)3712 def test_no_sys_import(self):3713 b = """sys.exitfunc = f"""3714 a = """atexit.register(f)"""3715 msg = ("Can't find sys import; Please add an atexit import at the "3716 "top of your file.")3717 self.warns(b, a, msg)3718 def test_unchanged(self):3719 s = """f(sys.exitfunc)"""3720 self.unchanged(s)3721class Test_asserts(FixerTestCase):3722 fixer = "asserts"3723 def test_deprecated_names(self):3724 tests = [3725 ('self.assert_(True)', 'self.assertTrue(True)'),3726 ('self.assertEquals(2, 2)', 'self.assertEqual(2, 2)'),3727 ('self.assertNotEquals(2, 3)', 'self.assertNotEqual(2, 3)'),3728 ('self.assertAlmostEquals(2, 3)', 'self.assertAlmostEqual(2, 3)'),3729 ('self.assertNotAlmostEquals(2, 8)', 'self.assertNotAlmostEqual(2, 8)'),3730 ('self.failUnlessEqual(2, 2)', 'self.assertEqual(2, 2)'),3731 ('self.failIfEqual(2, 3)', 'self.assertNotEqual(2, 3)'),3732 ('self.failUnlessAlmostEqual(2, 3)', 'self.assertAlmostEqual(2, 3)'),3733 ('self.failIfAlmostEqual(2, 8)', 'self.assertNotAlmostEqual(2, 8)'),3734 ('self.failUnless(True)', 'self.assertTrue(True)'),3735 ('self.failUnlessRaises(foo)', 'self.assertRaises(foo)'),3736 ('self.failIf(False)', 'self.assertFalse(False)'),3737 ]3738 for b, a in tests:3739 self.check(b, a)3740 def test_variants(self):3741 b = 'eq = self.assertEquals'3742 a = 'eq = self.assertEqual'3743 self.check(b, a)3744 b = 'self.assertEquals(2, 3, msg="fail")'3745 a = 'self.assertEqual(2, 3, msg="fail")'3746 self.check(b, a)3747 b = 'self.assertEquals(2, 3, msg="fail") # foo'3748 a = 'self.assertEqual(2, 3, msg="fail") # foo'3749 self.check(b, a)3750 b = 'self.assertEquals (2, 3)'3751 a = 'self.assertEqual (2, 3)'3752 self.check(b, a)3753 b = ' self.assertEquals (2, 3)'3754 a = ' self.assertEqual (2, 3)'3755 self.check(b, a)3756 b = 'with self.failUnlessRaises(Explosion): explode()'3757 a = 'with self.assertRaises(Explosion): explode()'3758 self.check(b, a)3759 b = 'with self.failUnlessRaises(Explosion) as cm: explode()'3760 a = 'with self.assertRaises(Explosion) as cm: explode()'3761 self.check(b, a)3762 def test_unchanged(self):3763 self.unchanged('self.assertEqualsOnSaturday')...

Full Screen

Full Screen

explain_binary_size_delta_unittest.py

Source:explain_binary_size_delta_unittest.py Github

copy

Full Screen

1#!/usr/bin/env python2# Copyright 2014 The Chromium Authors. All rights reserved.3# Use of this source code is governed by a BSD-style license that can be4# found in the LICENSE file.5"""Check that explain_binary_size_delta seems to work."""6import cStringIO7import sys8import unittest9import explain_binary_size_delta10class ExplainBinarySizeDeltaTest(unittest.TestCase):11 def testCompare(self):12 # List entries have form: symbol_name, symbol_type, symbol_size, file_path13 symbol_list1 = (14 # File with one symbol, left as-is.15 ( 'unchanged', 't', 1000, '/file_unchanged' ),16 # File with one symbol, changed.17 ( 'changed', 't', 1000, '/file_all_changed' ),18 # File with one symbol, deleted.19 ( 'removed', 't', 1000, '/file_all_deleted' ),20 # File with two symbols, one unchanged, one changed, same bucket21 ( 'unchanged', 't', 1000, '/file_pair_unchanged_changed' ),22 ( 'changed', 't', 1000, '/file_pair_unchanged_changed' ),23 # File with two symbols, one unchanged, one deleted, same bucket24 ( 'unchanged', 't', 1000, '/file_pair_unchanged_removed' ),25 ( 'removed', 't', 1000, '/file_pair_unchanged_removed' ),26 # File with two symbols, one unchanged, one added, same bucket27 ( 'unchanged', 't', 1000, '/file_pair_unchanged_added' ),28 # File with two symbols, one unchanged, one changed, different bucket29 ( 'unchanged', 't', 1000, '/file_pair_unchanged_diffbuck_changed' ),30 ( 'changed', '@', 1000, '/file_pair_unchanged_diffbuck_changed' ),31 # File with two symbols, one unchanged, one deleted, different bucket32 ( 'unchanged', 't', 1000, '/file_pair_unchanged_diffbuck_removed' ),33 ( 'removed', '@', 1000, '/file_pair_unchanged_diffbuck_removed' ),34 # File with two symbols, one unchanged, one added, different bucket35 ( 'unchanged', 't', 1000, '/file_pair_unchanged_diffbuck_added' ),36 # File with four symbols, one added, one removed,37 # one changed, one unchanged38 ( 'size_changed', 't', 1000, '/file_tetra' ),39 ( 'removed', 't', 1000, '/file_tetra' ),40 ( 'unchanged', 't', 1000, '/file_tetra' ),41 )42 symbol_list2 = (43 # File with one symbol, left as-is.44 ( 'unchanged', 't', 1000, '/file_unchanged' ),45 # File with one symbol, changed.46 ( 'changed', 't', 2000, '/file_all_changed' ),47 # File with two symbols, one unchanged, one changed, same bucket48 ( 'unchanged', 't', 1000, '/file_pair_unchanged_changed' ),49 ( 'changed', 't', 2000, '/file_pair_unchanged_changed' ),50 # File with two symbols, one unchanged, one deleted, same bucket51 ( 'unchanged', 't', 1000, '/file_pair_unchanged_removed' ),52 # File with two symbols, one unchanged, one added, same bucket53 ( 'unchanged', 't', 1000, '/file_pair_unchanged_added' ),54 ( 'added', 't', 1000, '/file_pair_unchanged_added' ),55 # File with two symbols, one unchanged, one changed, different bucket56 ( 'unchanged', 't', 1000, '/file_pair_unchanged_diffbuck_changed' ),57 ( 'changed', '@', 2000, '/file_pair_unchanged_diffbuck_changed' ),58 # File with two symbols, one unchanged, one deleted, different bucket59 ( 'unchanged', 't', 1000, '/file_pair_unchanged_diffbuck_removed' ),60 # File with two symbols, one unchanged, one added, different bucket61 ( 'unchanged', 't', 1000, '/file_pair_unchanged_diffbuck_added' ),62 ( 'added', '@', 1000, '/file_pair_unchanged_diffbuck_added' ),63 # File with four symbols, one added, one removed,64 # one changed, one unchanged65 ( 'size_changed', 't', 2000, '/file_tetra' ),66 ( 'unchanged', 't', 1000, '/file_tetra' ),67 ( 'added', 't', 1000, '/file_tetra' ),68 # New file with one symbol added69 ( 'added', 't', 1000, '/file_new' ),70 )71 # Here we go72 (added, removed, changed, unchanged) = \73 explain_binary_size_delta.Compare(symbol_list1, symbol_list2)74 # File with one symbol, left as-is.75 assert ('/file_unchanged', 't', 'unchanged', 1000, 1000) in unchanged76 # File with one symbol, changed.77 assert ('/file_all_changed', 't', 'changed', 1000, 2000) in changed78 # File with one symbol, deleted.79 assert ('/file_all_deleted', 't', 'removed', 1000, None) in removed80 # New file with one symbol added81 assert ('/file_new', 't', 'added', None, 1000) in added82 # File with two symbols, one unchanged, one changed, same bucket83 assert ('/file_pair_unchanged_changed',84 't', 'unchanged', 1000, 1000) in unchanged85 assert ('/file_pair_unchanged_changed',86 't', 'changed', 1000, 2000) in changed87 # File with two symbols, one unchanged, one removed, same bucket88 assert ('/file_pair_unchanged_removed',89 't', 'unchanged', 1000, 1000) in unchanged90 assert ('/file_pair_unchanged_removed',91 't', 'removed', 1000, None) in removed92 # File with two symbols, one unchanged, one added, same bucket93 assert ('/file_pair_unchanged_added',94 't', 'unchanged', 1000, 1000) in unchanged95 assert ('/file_pair_unchanged_added',96 't', 'added', None, 1000) in added97 # File with two symbols, one unchanged, one changed, different bucket98 assert ('/file_pair_unchanged_diffbuck_changed',99 't', 'unchanged', 1000, 1000) in unchanged100 assert ('/file_pair_unchanged_diffbuck_changed',101 '@', 'changed', 1000, 2000) in changed102 # File with two symbols, one unchanged, one removed, different bucket103 assert ('/file_pair_unchanged_diffbuck_removed',104 't', 'unchanged', 1000, 1000) in unchanged105 assert ('/file_pair_unchanged_diffbuck_removed',106 '@', 'removed', 1000, None) in removed107 # File with two symbols, one unchanged, one added, different bucket108 assert ('/file_pair_unchanged_diffbuck_added',109 't', 'unchanged', 1000, 1000) in unchanged110 assert ('/file_pair_unchanged_diffbuck_added',111 '@', 'added', None, 1000) in added112 # File with four symbols, one added, one removed, one changed, one unchanged113 assert ('/file_tetra', 't', 'size_changed', 1000, 2000) in changed114 assert ('/file_tetra', 't', 'unchanged', 1000, 1000) in unchanged115 assert ('/file_tetra', 't', 'added', None, 1000) in added116 assert ('/file_tetra', 't', 'removed', 1000, None) in removed117 # Now check final stats.118 orig_stdout = sys.stdout119 output_collector = cStringIO.StringIO()120 sys.stdout = output_collector121 try:122 explain_binary_size_delta.CrunchStats(added, removed, changed,123 unchanged, True, True)124 finally:125 sys.stdout = orig_stdout126 result = output_collector.getvalue()127 expected_output = """\128Symbol statistics:129 4 added, totalling 4000 bytes across 4 sources130 4 removed, totalling 4000 bytes removed across 4 sources131 4 changed, resulting in a net change of 4000 bytes \132(4000 bytes before, 8000 bytes after) across 4 sources133 8 unchanged, totalling 8000 bytes134Source stats:135 11 sources encountered.136 1 completely new.137 1 removed completely.138 8 partially changed.139 1 completely unchanged.140Per-source Analysis:141 Source: /file_all_changed142 Change: 1000 bytes (gained 1000, lost 0)143 Changed symbols:144 changed type=t, delta=1000 bytes (was 1000 bytes, now 2000 bytes)145 Source: /file_all_deleted146 Change: -1000 bytes (gained 0, lost 1000)147 Removed symbols:148 removed type=t, size=1000 bytes149 Source: /file_new150 Change: 1000 bytes (gained 1000, lost 0)151 New symbols:152 added type=t, size=1000 bytes153 Source: /file_pair_unchanged_added154 Change: 1000 bytes (gained 1000, lost 0)155 New symbols:156 added type=t, size=1000 bytes157 Source: /file_pair_unchanged_changed158 Change: 1000 bytes (gained 1000, lost 0)159 Changed symbols:160 changed type=t, delta=1000 bytes (was 1000 bytes, now 2000 bytes)161 Source: /file_pair_unchanged_diffbuck_added162 Change: 1000 bytes (gained 1000, lost 0)163 New symbols:164 added type=@, size=1000 bytes165 Source: /file_pair_unchanged_diffbuck_changed166 Change: 1000 bytes (gained 1000, lost 0)167 Changed symbols:168 changed type=@, delta=1000 bytes (was 1000 bytes, now 2000 bytes)169 Source: /file_pair_unchanged_diffbuck_removed170 Change: -1000 bytes (gained 0, lost 1000)171 Removed symbols:172 removed type=@, size=1000 bytes173 Source: /file_pair_unchanged_removed174 Change: -1000 bytes (gained 0, lost 1000)175 Removed symbols:176 removed type=t, size=1000 bytes177 Source: /file_tetra178 Change: 1000 bytes (gained 2000, lost 1000)179 New symbols:180 added type=t, size=1000 bytes181 Removed symbols:182 removed type=t, size=1000 bytes183 Changed symbols:184 size_changed type=t, delta=1000 bytes (was 1000 bytes, now 2000 bytes)185"""186 self.maxDiff = None187 self.assertMultiLineEqual(expected_output, result)188 print "explain_binary_size_delta_unittest: All tests passed"189if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful