1 """ Test suite for the fixer modules """
6 from itertools
import chain
7 from operator
import itemgetter
10 from lib2to3
import pygram
, pytree
, refactor
, fixer_util
11 from lib2to3
.tests
import support
14 class FixerTestCase(support
.TestCase
):
16 # Other test cases can subclass this class and replace "fixer_pkg" with
18 def setUp(self
, fix_list
=None, fixer_pkg
="lib2to3", options
=None):
20 fix_list
= [self
.fixer
]
21 self
.refactor
= support
.get_refactorer(fixer_pkg
, fix_list
, options
)
23 self
.filename
= u
"<string>"
25 for fixer
in chain(self
.refactor
.pre_order
,
26 self
.refactor
.post_order
):
27 fixer
.log
= self
.fixer_log
29 def _check(self
, before
, after
):
30 before
= support
.reformat(before
)
31 after
= support
.reformat(after
)
32 tree
= self
.refactor
.refactor_string(before
, self
.filename
)
33 self
.assertEqual(after
, unicode(tree
))
36 def check(self
, before
, after
, ignore_warnings
=False):
37 tree
= self
._check
(before
, after
)
38 self
.assertTrue(tree
.was_changed
)
39 if not ignore_warnings
:
40 self
.assertEqual(self
.fixer_log
, [])
42 def warns(self
, before
, after
, message
, unchanged
=False):
43 tree
= self
._check
(before
, after
)
44 self
.assertTrue(message
in "".join(self
.fixer_log
))
46 self
.assertTrue(tree
.was_changed
)
48 def warns_unchanged(self
, before
, message
):
49 self
.warns(before
, before
, message
, unchanged
=True)
51 def unchanged(self
, before
, ignore_warnings
=False):
52 self
._check
(before
, before
)
53 if not ignore_warnings
:
54 self
.assertEqual(self
.fixer_log
, [])
56 def assert_runs_after(self
, *names
):
59 r
= support
.get_refactorer("lib2to3", fixes
)
60 (pre
, post
) = r
.get_fixers()
61 n
= "fix_" + self
.fixer
62 if post
and post
[-1].__class
__.__module
__.endswith(n
):
63 # We're the last fixer to run
65 if pre
and pre
[-1].__class
__.__module
__.endswith(n
) and not post
:
66 # We're the last in pre and post is empty
68 self
.fail("Fixer run order (%s) is incorrect; %s should be last."\
69 %(", ".join([x
.__class
__.__module
__ for x
in (pre
+post
)]), n
))
71 class Test_ne(FixerTestCase
):
82 def test_no_spaces(self
):
90 def test_chained(self
):
98 class Test_has_key(FixerTestCase
):
102 b
= """x = d.has_key("x") or d.has_key("y")"""
103 a
= """x = "x" in d or "y" in d"""
107 b
= """x = a.b.c.d.has_key("x") ** 3"""
108 a
= """x = ("x" in a.b.c.d) ** 3"""
112 b
= """x = a.b.has_key(1 + 2).__repr__()"""
113 a
= """x = (1 + 2 in a.b).__repr__()"""
117 b
= """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4"""
118 a
= """x = (1 + 2 in a.b).__repr__() ** -3 ** 4"""
122 b
= """x = a.has_key(f or g)"""
123 a
= """x = (f or g) in a"""
127 b
= """x = a + b.has_key(c)"""
128 a
= """x = a + (c in b)"""
132 b
= """x = a.has_key(lambda: 12)"""
133 a
= """x = (lambda: 12) in a"""
137 b
= """x = a.has_key(a for a in b)"""
138 a
= """x = (a for a in b) in a"""
142 b
= """if not a.has_key(b): pass"""
143 a
= """if b not in a: pass"""
147 b
= """if not a.has_key(b).__repr__(): pass"""
148 a
= """if not (b in a).__repr__(): pass"""
152 b
= """if not a.has_key(b) ** 2: pass"""
153 a
= """if not (b in a) ** 2: pass"""
156 class Test_apply(FixerTestCase
):
160 b
= """x = apply(f, g + h)"""
161 a
= """x = f(*g + h)"""
165 b
= """y = apply(f, g, h)"""
166 a
= """y = f(*g, **h)"""
170 b
= """z = apply(fs[0], g or h, h or g)"""
171 a
= """z = fs[0](*g or h, **h or g)"""
175 b
= """apply(f, (x, y) + t)"""
176 a
= """f(*(x, y) + t)"""
180 b
= """apply(f, args,)"""
185 b
= """apply(f, args, kwds,)"""
186 a
= """f(*args, **kwds)"""
189 # Test that complex functions are parenthesized
191 def test_complex_1(self
):
192 b
= """x = apply(f+g, args)"""
193 a
= """x = (f+g)(*args)"""
196 def test_complex_2(self
):
197 b
= """x = apply(f*g, args)"""
198 a
= """x = (f*g)(*args)"""
201 def test_complex_3(self
):
202 b
= """x = apply(f**g, args)"""
203 a
= """x = (f**g)(*args)"""
206 # But dotted names etc. not
208 def test_dotted_name(self
):
209 b
= """x = apply(f.g, args)"""
210 a
= """x = f.g(*args)"""
213 def test_subscript(self
):
214 b
= """x = apply(f[x], args)"""
215 a
= """x = f[x](*args)"""
219 b
= """x = apply(f(), args)"""
220 a
= """x = f()(*args)"""
224 def test_extreme(self
):
225 b
= """x = apply(a.b.c.d.e.f, args, kwds)"""
226 a
= """x = a.b.c.d.e.f(*args, **kwds)"""
229 # XXX Comments in weird places still get lost
230 def test_weird_comments(self
):
237 # These should *not* be touched
239 def test_unchanged_1(self
):
243 def test_unchanged_2(self
):
247 def test_unchanged_3(self
):
251 def test_unchanged_4(self
):
252 s
= """apply(f, args, kwds, extras)"""
255 def test_unchanged_5(self
):
256 s
= """apply(f, *args, **kwds)"""
259 def test_unchanged_6(self
):
260 s
= """apply(f, *args)"""
263 def test_unchanged_7(self
):
264 s
= """apply(func=f, args=args, kwds=kwds)"""
267 def test_unchanged_8(self
):
268 s
= """apply(f, args=args, kwds=kwds)"""
271 def test_unchanged_9(self
):
272 s
= """apply(f, args, kwds=kwds)"""
275 def test_space_1(self
):
276 a
= """apply( f, args, kwds)"""
277 b
= """f(*args, **kwds)"""
280 def test_space_2(self
):
281 a
= """apply( f ,args,kwds )"""
282 b
= """f(*args, **kwds)"""
285 class Test_intern(FixerTestCase
):
288 def test_prefix_preservation(self
):
289 b
= """x = intern( a )"""
290 a
= """import sys\nx = sys.intern( a )"""
293 b
= """y = intern("b" # test
295 a
= """import sys\ny = sys.intern("b" # test
299 b
= """z = intern(a+b+c.d, )"""
300 a
= """import sys\nz = sys.intern(a+b+c.d, )"""
304 b
= """x = intern(a)"""
305 a
= """import sys\nx = sys.intern(a)"""
308 b
= """z = intern(a+b+c.d,)"""
309 a
= """import sys\nz = sys.intern(a+b+c.d,)"""
312 b
= """intern("y%s" % 5).replace("y", "")"""
313 a
= """import sys\nsys.intern("y%s" % 5).replace("y", "")"""
316 # These should not be refactored
318 def test_unchanged(self
):
319 s
= """intern(a=1)"""
322 s
= """intern(f, g)"""
328 s
= """intern(**i)"""
334 class Test_reduce(FixerTestCase
):
337 def test_simple_call(self
):
338 b
= "reduce(a, b, c)"
339 a
= "from functools import reduce\nreduce(a, b, c)"
342 def test_bug_7253(self
):
343 # fix_tuple_params was being bad and orphaning nodes in the tree.
344 b
= "def x(arg): reduce(sum, [])"
345 a
= "from functools import reduce\ndef x(arg): reduce(sum, [])"
348 def test_call_with_lambda(self
):
349 b
= "reduce(lambda x, y: x + y, seq)"
350 a
= "from functools import reduce\nreduce(lambda x, y: x + y, seq)"
353 def test_unchanged(self
):
357 s
= "reduce(a, b=42)"
360 s
= "reduce(a, b, c, d)"
369 class Test_print(FixerTestCase
):
372 def test_prefix_preservation(self
):
373 b
= """print 1, 1+1, 1+1+1"""
374 a
= """print(1, 1+1, 1+1+1)"""
377 def test_idempotency(self
):
384 def test_idempotency_print_as_function(self
):
385 self
.refactor
.driver
.grammar
= pygram
.python_grammar_no_print_statement
386 s
= """print(1, 1+1, 1+1+1)"""
396 b
= """print 1, 1+1, 1+1+1"""
397 a
= """print(1, 1+1, 1+1+1)"""
402 a
= """print(1, 2)"""
412 b
= """print whatever; print"""
413 a
= """print(whatever); print()"""
417 b
= """print; print whatever;"""
418 a
= """print(); print(whatever);"""
421 def test_tuple(self
):
422 b
= """print (a, b, c)"""
423 a
= """print((a, b, c))"""
428 def test_trailing_comma_1(self
):
429 b
= """print 1, 2, 3,"""
430 a
= """print(1, 2, 3, end=' ')"""
433 def test_trailing_comma_2(self
):
434 b
= """print 1, 2,"""
435 a
= """print(1, 2, end=' ')"""
438 def test_trailing_comma_3(self
):
440 a
= """print(1, end=' ')"""
445 def test_vargs_without_trailing_comma(self
):
446 b
= """print >>sys.stderr, 1, 2, 3"""
447 a
= """print(1, 2, 3, file=sys.stderr)"""
450 def test_with_trailing_comma(self
):
451 b
= """print >>sys.stderr, 1, 2,"""
452 a
= """print(1, 2, end=' ', file=sys.stderr)"""
455 def test_no_trailing_comma(self
):
456 b
= """print >>sys.stderr, 1+1"""
457 a
= """print(1+1, file=sys.stderr)"""
460 def test_spaces_before_file(self
):
461 b
= """print >> sys.stderr"""
462 a
= """print(file=sys.stderr)"""
465 def test_with_future_print_function(self
):
466 s
= "from __future__ import print_function\n" \
467 "print('Hai!', end=' ')"
470 b
= "print 'Hello, world!'"
471 a
= "print('Hello, world!')"
475 class Test_exec(FixerTestCase
):
478 def test_prefix_preservation(self
):
479 b
= """ exec code in ns1, ns2"""
480 a
= """ exec(code, ns1, ns2)"""
483 def test_basic(self
):
488 def test_with_globals(self
):
489 b
= """exec code in ns"""
490 a
= """exec(code, ns)"""
493 def test_with_globals_locals(self
):
494 b
= """exec code in ns1, ns2"""
495 a
= """exec(code, ns1, ns2)"""
498 def test_complex_1(self
):
499 b
= """exec (a.b()) in ns"""
500 a
= """exec((a.b()), ns)"""
503 def test_complex_2(self
):
504 b
= """exec a.b() + c in ns"""
505 a
= """exec(a.b() + c, ns)"""
508 # These should not be touched
510 def test_unchanged_1(self
):
514 def test_unchanged_2(self
):
515 s
= """exec (code)"""
518 def test_unchanged_3(self
):
519 s
= """exec(code, ns)"""
522 def test_unchanged_4(self
):
523 s
= """exec(code, ns1, ns2)"""
526 class Test_repr(FixerTestCase
):
529 def test_prefix_preservation(self
):
530 b
= """x = `1 + 2`"""
531 a
= """x = repr(1 + 2)"""
534 def test_simple_1(self
):
535 b
= """x = `1 + 2`"""
536 a
= """x = repr(1 + 2)"""
539 def test_simple_2(self
):
541 a
= """y = repr(x)"""
544 def test_complex(self
):
545 b
= """z = `y`.__repr__()"""
546 a
= """z = repr(y).__repr__()"""
549 def test_tuple(self
):
550 b
= """x = `1, 2, 3`"""
551 a
= """x = repr((1, 2, 3))"""
554 def test_nested(self
):
555 b
= """x = `1 + `2``"""
556 a
= """x = repr(1 + repr(2))"""
559 def test_nested_tuples(self
):
560 b
= """x = `1, 2 + `3, 4``"""
561 a
= """x = repr((1, 2 + repr((3, 4))))"""
564 class Test_except(FixerTestCase
):
567 def test_prefix_preservation(self
):
571 except (RuntimeError, ImportError), e:
576 except (RuntimeError, ImportError) as e:
580 def test_simple(self
):
593 def test_simple_no_space_before_target(self
):
606 def test_tuple_unpack(self
):
611 except Exception, (f, e):
613 except ImportError, e:
620 except Exception as xxx_todo_changeme:
621 (f, e) = xxx_todo_changeme.args
623 except ImportError as e:
627 def test_multi_class(self
):
631 except (RuntimeError, ImportError), e:
637 except (RuntimeError, ImportError) as e:
641 def test_list_unpack(self
):
645 except Exception, [a, b]:
651 except Exception as xxx_todo_changeme:
652 [a, b] = xxx_todo_changeme.args
656 def test_weird_target_1(self
):
660 except Exception, d[5]:
666 except Exception as xxx_todo_changeme:
667 d[5] = xxx_todo_changeme
671 def test_weird_target_2(self
):
675 except Exception, a.foo:
681 except Exception as xxx_todo_changeme:
682 a.foo = xxx_todo_changeme
686 def test_weird_target_3(self
):
690 except Exception, a().foo:
696 except Exception as xxx_todo_changeme:
697 a().foo = xxx_todo_changeme
701 def test_bare_except(self
):
713 except Exception as a:
719 def test_bare_except_and_else_finally(self
):
735 except Exception as a:
745 def test_multi_fixed_excepts_before_bare_except(self
):
759 except TypeError as b:
761 except Exception as a:
767 def test_one_line_suites(self
):
775 except TypeError as e:
782 except TypeError, e: pass
787 except TypeError as e: pass
792 except TypeError, e: pass
796 except TypeError as e: pass
801 except TypeError, e: pass
807 except TypeError as e: pass
813 # These should not be touched:
815 def test_unchanged_1(self
):
823 def test_unchanged_2(self
):
831 def test_unchanged_3(self
):
835 except (Exception, SystemExit):
839 class Test_raise(FixerTestCase
):
842 def test_basic(self
):
843 b
= """raise Exception, 5"""
844 a
= """raise Exception(5)"""
847 def test_prefix_preservation(self
):
848 b
= """raise Exception,5"""
849 a
= """raise Exception(5)"""
852 b
= """raise Exception, 5"""
853 a
= """raise Exception(5)"""
856 def test_with_comments(self
):
857 b
= """raise Exception, 5 # foo"""
858 a
= """raise Exception(5) # foo"""
861 b
= """raise E, (5, 6) % (a, b) # foo"""
862 a
= """raise E((5, 6) % (a, b)) # foo"""
866 raise Exception, 5, 6 # foo"""
868 raise Exception(5).with_traceback(6) # foo"""
871 def test_None_value(self
):
872 b
= """raise Exception(5), None, tb"""
873 a
= """raise Exception(5).with_traceback(tb)"""
876 def test_tuple_value(self
):
877 b
= """raise Exception, (5, 6, 7)"""
878 a
= """raise Exception(5, 6, 7)"""
881 def test_tuple_detection(self
):
882 b
= """raise E, (5, 6) % (a, b)"""
883 a
= """raise E((5, 6) % (a, b))"""
886 def test_tuple_exc_1(self
):
887 b
= """raise (((E1, E2), E3), E4), V"""
888 a
= """raise E1(V)"""
891 def test_tuple_exc_2(self
):
892 b
= """raise (E1, (E2, E3), E4), V"""
893 a
= """raise E1(V)"""
896 # These should produce a warning
898 def test_string_exc(self
):
899 s
= """raise 'foo'"""
900 self
.warns_unchanged(s
, "Python 3 does not support string exceptions")
902 def test_string_exc_val(self
):
903 s
= """raise "foo", 5"""
904 self
.warns_unchanged(s
, "Python 3 does not support string exceptions")
906 def test_string_exc_val_tb(self
):
907 s
= """raise "foo", 5, 6"""
908 self
.warns_unchanged(s
, "Python 3 does not support string exceptions")
910 # These should result in traceback-assignment
914 raise Exception, 5, 6"""
916 raise Exception(5).with_traceback(6)"""
922 raise Exception, 5, 6
926 raise Exception(5).with_traceback(6)
932 raise Exception,5,6"""
934 raise Exception(5).with_traceback(6)"""
944 raise Exception(5).with_traceback(6)
950 raise Exception, (5, 6, 7), 6"""
952 raise Exception(5, 6, 7).with_traceback(6)"""
958 raise Exception, (5, 6, 7), 6
962 raise Exception(5, 6, 7).with_traceback(6)
966 class Test_throw(FixerTestCase
):
970 b
= """g.throw(Exception, 5)"""
971 a
= """g.throw(Exception(5))"""
975 b
= """g.throw(Exception,5)"""
976 a
= """g.throw(Exception(5))"""
980 b
= """g.throw(Exception, (5, 6, 7))"""
981 a
= """g.throw(Exception(5, 6, 7))"""
985 b
= """5 + g.throw(Exception, 5)"""
986 a
= """5 + g.throw(Exception(5))"""
989 # These should produce warnings
991 def test_warn_1(self
):
992 s
= """g.throw("foo")"""
993 self
.warns_unchanged(s
, "Python 3 does not support string exceptions")
995 def test_warn_2(self
):
996 s
= """g.throw("foo", 5)"""
997 self
.warns_unchanged(s
, "Python 3 does not support string exceptions")
999 def test_warn_3(self
):
1000 s
= """g.throw("foo", 5, 6)"""
1001 self
.warns_unchanged(s
, "Python 3 does not support string exceptions")
1003 # These should not be touched
1005 def test_untouched_1(self
):
1006 s
= """g.throw(Exception)"""
1009 def test_untouched_2(self
):
1010 s
= """g.throw(Exception(5, 6))"""
1013 def test_untouched_3(self
):
1014 s
= """5 + g.throw(Exception(5, 6))"""
1017 # These should result in traceback-assignment
1019 def test_tb_1(self
):
1021 g.throw(Exception, 5, 6)"""
1023 g.throw(Exception(5).with_traceback(6))"""
1026 def test_tb_2(self
):
1029 g.throw(Exception, 5, 6)
1033 g.throw(Exception(5).with_traceback(6))
1037 def test_tb_3(self
):
1039 g.throw(Exception,5,6)"""
1041 g.throw(Exception(5).with_traceback(6))"""
1044 def test_tb_4(self
):
1047 g.throw(Exception,5,6)
1051 g.throw(Exception(5).with_traceback(6))
1055 def test_tb_5(self
):
1057 g.throw(Exception, (5, 6, 7), 6)"""
1059 g.throw(Exception(5, 6, 7).with_traceback(6))"""
1062 def test_tb_6(self
):
1065 g.throw(Exception, (5, 6, 7), 6)
1069 g.throw(Exception(5, 6, 7).with_traceback(6))
1073 def test_tb_7(self
):
1075 a + g.throw(Exception, 5, 6)"""
1077 a + g.throw(Exception(5).with_traceback(6))"""
1080 def test_tb_8(self
):
1083 a + g.throw(Exception, 5, 6)
1087 a + g.throw(Exception(5).with_traceback(6))
1091 class Test_long(FixerTestCase
):
1095 b
= """x = long(x)"""
1096 a
= """x = int(x)"""
1100 b
= """y = isinstance(x, long)"""
1101 a
= """y = isinstance(x, int)"""
1105 b
= """z = type(x) in (int, long)"""
1106 a
= """z = type(x) in (int, int)"""
1109 def test_unchanged(self
):
1110 s
= """long = True"""
1113 s
= """s.long = True"""
1116 s
= """def long(): pass"""
1119 s
= """class long(): pass"""
1122 s
= """def f(long): pass"""
1125 s
= """def f(g, long): pass"""
1128 s
= """def f(x, long=True): pass"""
1131 def test_prefix_preservation(self
):
1132 b
= """x = long( x )"""
1133 a
= """x = int( x )"""
1137 class Test_execfile(FixerTestCase
):
1140 def test_conversion(self
):
1141 b
= """execfile("fn")"""
1142 a
= """exec(compile(open("fn").read(), "fn", 'exec'))"""
1145 b
= """execfile("fn", glob)"""
1146 a
= """exec(compile(open("fn").read(), "fn", 'exec'), glob)"""
1149 b
= """execfile("fn", glob, loc)"""
1150 a
= """exec(compile(open("fn").read(), "fn", 'exec'), glob, loc)"""
1153 b
= """execfile("fn", globals=glob)"""
1154 a
= """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob)"""
1157 b
= """execfile("fn", locals=loc)"""
1158 a
= """exec(compile(open("fn").read(), "fn", 'exec'), locals=loc)"""
1161 b
= """execfile("fn", globals=glob, locals=loc)"""
1162 a
= """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob, locals=loc)"""
1165 def test_spacing(self
):
1166 b
= """execfile( "fn" )"""
1167 a
= """exec(compile(open( "fn" ).read(), "fn", 'exec'))"""
1170 b
= """execfile("fn", globals = glob)"""
1171 a
= """exec(compile(open("fn").read(), "fn", 'exec'), globals = glob)"""
1175 class Test_isinstance(FixerTestCase
):
1176 fixer
= "isinstance"
1178 def test_remove_multiple_items(self
):
1179 b
= """isinstance(x, (int, int, int))"""
1180 a
= """isinstance(x, int)"""
1183 b
= """isinstance(x, (int, float, int, int, float))"""
1184 a
= """isinstance(x, (int, float))"""
1187 b
= """isinstance(x, (int, float, int, int, float, str))"""
1188 a
= """isinstance(x, (int, float, str))"""
1191 b
= """isinstance(foo() + bar(), (x(), y(), x(), int, int))"""
1192 a
= """isinstance(foo() + bar(), (x(), y(), x(), int))"""
1195 def test_prefix_preservation(self
):
1196 b
= """if isinstance( foo(), ( bar, bar, baz )) : pass"""
1197 a
= """if isinstance( foo(), ( bar, baz )) : pass"""
1200 def test_unchanged(self
):
1201 self
.unchanged("isinstance(x, (str, int))")
1203 class Test_dict(FixerTestCase
):
1206 def test_prefix_preservation(self
):
1207 b
= "if d. keys ( ) : pass"
1208 a
= "if list(d. keys ( )) : pass"
1211 b
= "if d. items ( ) : pass"
1212 a
= "if list(d. items ( )) : pass"
1215 b
= "if d. iterkeys ( ) : pass"
1216 a
= "if iter(d. keys ( )) : pass"
1219 b
= "[i for i in d. iterkeys( ) ]"
1220 a
= "[i for i in d. keys( ) ]"
1223 b
= "if d. viewkeys ( ) : pass"
1224 a
= "if d. keys ( ) : pass"
1227 b
= "[i for i in d. viewkeys( ) ]"
1228 a
= "[i for i in d. keys( ) ]"
1231 def test_trailing_comment(self
):
1232 b
= "d.keys() # foo"
1233 a
= "list(d.keys()) # foo"
1236 b
= "d.items() # foo"
1237 a
= "list(d.items()) # foo"
1240 b
= "d.iterkeys() # foo"
1241 a
= "iter(d.keys()) # foo"
1244 b
= """[i for i in d.iterkeys() # foo
1246 a
= """[i for i in d.keys() # foo
1250 b
= """[i for i in d.iterkeys() # foo
1252 a
= """[i for i in d.keys() # foo
1256 b
= "d.viewitems() # foo"
1257 a
= "d.items() # foo"
1260 def test_unchanged(self
):
1261 for wrapper
in fixer_util
.consuming_calls
:
1262 s
= "s = %s(d.keys())" % wrapper
1265 s
= "s = %s(d.values())" % wrapper
1268 s
= "s = %s(d.items())" % wrapper
1273 a
= "list(d.keys())"
1276 b
= "a[0].foo().keys()"
1277 a
= "list(a[0].foo().keys())"
1282 a
= "list(d.items())"
1287 a
= "list(d.values())"
1292 a
= "iter(d.keys())"
1297 a
= "iter(d.items())"
1301 b
= "d.itervalues()"
1302 a
= "iter(d.values())"
1306 s
= "list(d.keys())"
1310 s
= "sorted(d.keys())"
1314 b
= "iter(d.keys())"
1315 a
= "iter(list(d.keys()))"
1320 a
= "foo(list(d.keys()))"
1324 b
= "for i in d.keys(): print i"
1325 a
= "for i in list(d.keys()): print i"
1329 b
= "for i in d.iterkeys(): print i"
1330 a
= "for i in d.keys(): print i"
1334 b
= "[i for i in d.keys()]"
1335 a
= "[i for i in list(d.keys())]"
1339 b
= "[i for i in d.iterkeys()]"
1340 a
= "[i for i in d.keys()]"
1344 b
= "(i for i in d.keys())"
1345 a
= "(i for i in list(d.keys()))"
1349 b
= "(i for i in d.iterkeys())"
1350 a
= "(i for i in d.keys())"
1354 b
= "iter(d.iterkeys())"
1355 a
= "iter(d.keys())"
1359 b
= "list(d.iterkeys())"
1360 a
= "list(d.keys())"
1364 b
= "sorted(d.iterkeys())"
1365 a
= "sorted(d.keys())"
1369 b
= "foo(d.iterkeys())"
1370 a
= "foo(iter(d.keys()))"
1374 b
= "print h.iterkeys().next()"
1375 a
= "print iter(h.keys()).next()"
1379 b
= "print h.keys()[0]"
1380 a
= "print list(h.keys())[0]"
1384 b
= "print list(h.iterkeys().next())"
1385 a
= "print list(iter(h.keys()).next())"
1389 b
= "for x in h.keys()[0]: print x"
1390 a
= "for x in list(h.keys())[0]: print x"
1404 b
= "d.viewvalues()"
1409 b
= "[i for i in d.viewkeys()]"
1410 a
= "[i for i in d.keys()]"
1414 b
= "(i for i in d.viewkeys())"
1415 a
= "(i for i in d.keys())"
1419 b
= "iter(d.viewkeys())"
1420 a
= "iter(d.keys())"
1424 b
= "list(d.viewkeys())"
1425 a
= "list(d.keys())"
1429 b
= "sorted(d.viewkeys())"
1430 a
= "sorted(d.keys())"
1433 class Test_xrange(FixerTestCase
):
1436 def test_prefix_preservation(self
):
1437 b
= """x = xrange( 10 )"""
1438 a
= """x = range( 10 )"""
1441 b
= """x = xrange( 1 , 10 )"""
1442 a
= """x = range( 1 , 10 )"""
1445 b
= """x = xrange( 0 , 10 , 2 )"""
1446 a
= """x = range( 0 , 10 , 2 )"""
1449 def test_single_arg(self
):
1450 b
= """x = xrange(10)"""
1451 a
= """x = range(10)"""
1454 def test_two_args(self
):
1455 b
= """x = xrange(1, 10)"""
1456 a
= """x = range(1, 10)"""
1459 def test_three_args(self
):
1460 b
= """x = xrange(0, 10, 2)"""
1461 a
= """x = range(0, 10, 2)"""
1464 def test_wrap_in_list(self
):
1465 b
= """x = range(10, 3, 9)"""
1466 a
= """x = list(range(10, 3, 9))"""
1469 b
= """x = foo(range(10, 3, 9))"""
1470 a
= """x = foo(list(range(10, 3, 9)))"""
1473 b
= """x = range(10, 3, 9) + [4]"""
1474 a
= """x = list(range(10, 3, 9)) + [4]"""
1477 b
= """x = range(10)[::-1]"""
1478 a
= """x = list(range(10))[::-1]"""
1481 b
= """x = range(10) [3]"""
1482 a
= """x = list(range(10)) [3]"""
1485 def test_xrange_in_for(self
):
1486 b
= """for i in xrange(10):\n j=i"""
1487 a
= """for i in range(10):\n j=i"""
1490 b
= """[i for i in xrange(10)]"""
1491 a
= """[i for i in range(10)]"""
1494 def test_range_in_for(self
):
1495 self
.unchanged("for i in range(10): pass")
1496 self
.unchanged("[i for i in range(10)]")
1498 def test_in_contains_test(self
):
1499 self
.unchanged("x in range(10, 3, 9)")
1501 def test_in_consuming_context(self
):
1502 for call
in fixer_util
.consuming_calls
:
1503 self
.unchanged("a = %s(range(10))" % call
)
1505 class Test_xrange_with_reduce(FixerTestCase
):
1508 super(Test_xrange_with_reduce
, self
).setUp(["xrange", "reduce"])
1510 def test_double_transform(self
):
1511 b
= """reduce(x, xrange(5))"""
1512 a
= """from functools import reduce
1513 reduce(x, range(5))"""
1516 class Test_raw_input(FixerTestCase
):
1519 def test_prefix_preservation(self
):
1520 b
= """x = raw_input( )"""
1521 a
= """x = input( )"""
1524 b
= """x = raw_input( '' )"""
1525 a
= """x = input( '' )"""
1529 b
= """x = raw_input()"""
1530 a
= """x = input()"""
1534 b
= """x = raw_input('')"""
1535 a
= """x = input('')"""
1539 b
= """x = raw_input('prompt')"""
1540 a
= """x = input('prompt')"""
1544 b
= """x = raw_input(foo(a) + 6)"""
1545 a
= """x = input(foo(a) + 6)"""
1549 b
= """x = raw_input(invite).split()"""
1550 a
= """x = input(invite).split()"""
1554 b
= """x = raw_input(invite) . split ()"""
1555 a
= """x = input(invite) . split ()"""
1559 b
= "x = int(raw_input())"
1560 a
= "x = int(input())"
1563 class Test_funcattrs(FixerTestCase
):
1566 attrs
= ["closure", "doc", "name", "defaults", "code", "globals", "dict"]
1569 for attr
in self
.attrs
:
1570 b
= "a.func_%s" % attr
1571 a
= "a.__%s__" % attr
1574 b
= "self.foo.func_%s.foo_bar" % attr
1575 a
= "self.foo.__%s__.foo_bar" % attr
1578 def test_unchanged(self
):
1579 for attr
in self
.attrs
:
1580 s
= "foo(func_%s + 5)" % attr
1583 s
= "f(foo.__%s__)" % attr
1586 s
= "f(foo.__%s__.foo)" % attr
1589 class Test_xreadlines(FixerTestCase
):
1590 fixer
= "xreadlines"
1592 def test_call(self
):
1593 b
= "for x in f.xreadlines(): pass"
1594 a
= "for x in f: pass"
1597 b
= "for x in foo().xreadlines(): pass"
1598 a
= "for x in foo(): pass"
1601 b
= "for x in (5 + foo()).xreadlines(): pass"
1602 a
= "for x in (5 + foo()): pass"
1605 def test_attr_ref(self
):
1606 b
= "foo(f.xreadlines + 5)"
1607 a
= "foo(f.__iter__ + 5)"
1610 b
= "foo(f().xreadlines + 5)"
1611 a
= "foo(f().__iter__ + 5)"
1614 b
= "foo((5 + f()).xreadlines + 5)"
1615 a
= "foo((5 + f()).__iter__ + 5)"
1618 def test_unchanged(self
):
1619 s
= "for x in f.xreadlines(5): pass"
1622 s
= "for x in f.xreadlines(k=5): pass"
1625 s
= "for x in f.xreadlines(*k, **v): pass"
1628 s
= "foo(xreadlines)"
1632 class ImportsFixerTests
:
1634 def test_import_module(self
):
1635 for old
, new
in self
.modules
.items():
1636 b
= "import %s" % old
1637 a
= "import %s" % new
1640 b
= "import foo, %s, bar" % old
1641 a
= "import foo, %s, bar" % new
1644 def test_import_from(self
):
1645 for old
, new
in self
.modules
.items():
1646 b
= "from %s import foo" % old
1647 a
= "from %s import foo" % new
1650 b
= "from %s import foo, bar" % old
1651 a
= "from %s import foo, bar" % new
1654 b
= "from %s import (yes, no)" % old
1655 a
= "from %s import (yes, no)" % new
1658 def test_import_module_as(self
):
1659 for old
, new
in self
.modules
.items():
1660 b
= "import %s as foo_bar" % old
1661 a
= "import %s as foo_bar" % new
1664 b
= "import %s as foo_bar" % old
1665 a
= "import %s as foo_bar" % new
1668 def test_import_from_as(self
):
1669 for old
, new
in self
.modules
.items():
1670 b
= "from %s import foo as bar" % old
1671 a
= "from %s import foo as bar" % new
1674 def test_star(self
):
1675 for old
, new
in self
.modules
.items():
1676 b
= "from %s import *" % old
1677 a
= "from %s import *" % new
1680 def test_import_module_usage(self
):
1681 for old
, new
in self
.modules
.items():
1712 """ % (old
, old
, old
)
1716 """ % (new
, new
, new
)
1730 class Test_imports(FixerTestCase
, ImportsFixerTests
):
1732 from ..fixes
.fix_imports
import MAPPING
as modules
1734 def test_multiple_imports(self
):
1735 b
= """import urlparse, cStringIO"""
1736 a
= """import urllib.parse, io"""
1739 def test_multiple_imports_as(self
):
1741 import copy_reg as bar, HTMLParser as foo, urlparse
1742 s = urlparse.spam(bar.foo())
1745 import copyreg as bar, html.parser as foo, urllib.parse
1746 s = urllib.parse.spam(bar.foo())
1751 class Test_imports2(FixerTestCase
, ImportsFixerTests
):
1753 from ..fixes
.fix_imports2
import MAPPING
as modules
1756 class Test_imports_fixer_order(FixerTestCase
, ImportsFixerTests
):
1759 super(Test_imports_fixer_order
, self
).setUp(['imports', 'imports2'])
1760 from ..fixes
.fix_imports2
import MAPPING
as mapping2
1761 self
.modules
= mapping2
.copy()
1762 from ..fixes
.fix_imports
import MAPPING
as mapping1
1763 for key
in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'):
1764 self
.modules
[key
] = mapping1
[key
]
1766 def test_after_local_imports_refactoring(self
):
1767 for fix
in ("imports", "imports2"):
1769 self
.assert_runs_after("import")
1772 class Test_urllib(FixerTestCase
):
1774 from ..fixes
.fix_urllib
import MAPPING
as modules
1776 def test_import_module(self
):
1777 for old
, changes
in self
.modules
.items():
1778 b
= "import %s" % old
1779 a
= "import %s" % ", ".join(map(itemgetter(0), changes
))
1782 def test_import_from(self
):
1783 for old
, changes
in self
.modules
.items():
1785 for new
, members
in changes
:
1786 for member
in members
:
1787 all_members
.append(member
)
1788 b
= "from %s import %s" % (old
, member
)
1789 a
= "from %s import %s" % (new
, member
)
1792 s
= "from foo import %s" % member
1795 b
= "from %s import %s" % (old
, ", ".join(members
))
1796 a
= "from %s import %s" % (new
, ", ".join(members
))
1799 s
= "from foo import %s" % ", ".join(members
)
1802 # test the breaking of a module into multiple replacements
1803 b
= "from %s import %s" % (old
, ", ".join(all_members
))
1804 a
= "\n".join(["from %s import %s" % (new
, ", ".join(members
))
1805 for (new
, members
) in changes
])
1808 def test_import_module_as(self
):
1809 for old
in self
.modules
:
1810 s
= "import %s as foo" % old
1811 self
.warns_unchanged(s
, "This module is now multiple modules")
1813 def test_import_from_as(self
):
1814 for old
, changes
in self
.modules
.items():
1815 for new
, members
in changes
:
1816 for member
in members
:
1817 b
= "from %s import %s as foo_bar" % (old
, member
)
1818 a
= "from %s import %s as foo_bar" % (new
, member
)
1820 b
= "from %s import %s as blah, %s" % (old
, member
, member
)
1821 a
= "from %s import %s as blah, %s" % (new
, member
, member
)
1824 def test_star(self
):
1825 for old
in self
.modules
:
1826 s
= "from %s import *" % old
1827 self
.warns_unchanged(s
, "Cannot handle star imports")
1829 def test_indented(self
):
1832 from urllib import urlencode, urlopen
1836 from urllib.parse import urlencode
1837 from urllib.request import urlopen
1844 from urllib import urlencode, urlopen
1849 from urllib.parse import urlencode
1850 from urllib.request import urlopen
1856 def test_import_module_usage(self
):
1857 for old
, changes
in self
.modules
.items():
1858 for new
, members
in changes
:
1859 for member
in members
:
1860 new_import
= ", ".join([n
for (n
, mems
)
1861 in self
.modules
[old
]])
1865 """ % (old
, old
, member
)
1869 """ % (new_import
, new
, member
)
1874 """ % (old
, old
, member
, old
, member
)
1878 """ % (new_import
, new
, member
, new
, member
)
1882 class Test_input(FixerTestCase
):
1885 def test_prefix_preservation(self
):
1886 b
= """x = input( )"""
1887 a
= """x = eval(input( ))"""
1890 b
= """x = input( '' )"""
1891 a
= """x = eval(input( '' ))"""
1894 def test_trailing_comment(self
):
1895 b
= """x = input() # foo"""
1896 a
= """x = eval(input()) # foo"""
1899 def test_idempotency(self
):
1900 s
= """x = eval(input())"""
1903 s
= """x = eval(input(''))"""
1906 s
= """x = eval(input(foo(5) + 9))"""
1910 b
= """x = input()"""
1911 a
= """x = eval(input())"""
1915 b
= """x = input('')"""
1916 a
= """x = eval(input(''))"""
1920 b
= """x = input('prompt')"""
1921 a
= """x = eval(input('prompt'))"""
1925 b
= """x = input(foo(5) + 9)"""
1926 a
= """x = eval(input(foo(5) + 9))"""
1929 class Test_tuple_params(FixerTestCase
):
1930 fixer
= "tuple_params"
1932 def test_unchanged_1(self
):
1933 s
= """def foo(): pass"""
1936 def test_unchanged_2(self
):
1937 s
= """def foo(a, b, c): pass"""
1940 def test_unchanged_3(self
):
1941 s
= """def foo(a=3, b=4, c=5): pass"""
1946 def foo(((a, b), c)):
1950 def foo(xxx_todo_changeme):
1951 ((a, b), c) = xxx_todo_changeme
1957 def foo(((a, b), c), d):
1961 def foo(xxx_todo_changeme, d):
1962 ((a, b), c) = xxx_todo_changeme
1968 def foo(((a, b), c), d) -> e:
1972 def foo(xxx_todo_changeme, d) -> e:
1973 ((a, b), c) = xxx_todo_changeme
1977 def test_semicolon(self
):
1979 def foo(((a, b), c)): x = 5; y = 7"""
1982 def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme; x = 5; y = 7"""
1985 def test_keywords(self
):
1987 def foo(((a, b), c), d, e=5) -> z:
1991 def foo(xxx_todo_changeme, d, e=5) -> z:
1992 ((a, b), c) = xxx_todo_changeme
1996 def test_varargs(self
):
1998 def foo(((a, b), c), d, *vargs, **kwargs) -> z:
2002 def foo(xxx_todo_changeme, d, *vargs, **kwargs) -> z:
2003 ((a, b), c) = xxx_todo_changeme
2007 def test_multi_1(self
):
2009 def foo(((a, b), c), (d, e, f)) -> z:
2013 def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
2014 ((a, b), c) = xxx_todo_changeme
2015 (d, e, f) = xxx_todo_changeme1
2019 def test_multi_2(self
):
2021 def foo(x, ((a, b), c), d, (e, f, g), y) -> z:
2025 def foo(x, xxx_todo_changeme, d, xxx_todo_changeme1, y) -> z:
2026 ((a, b), c) = xxx_todo_changeme
2027 (e, f, g) = xxx_todo_changeme1
2031 def test_docstring(self
):
2033 def foo(((a, b), c), (d, e, f)) -> z:
2038 def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
2040 ((a, b), c) = xxx_todo_changeme
2041 (d, e, f) = xxx_todo_changeme1
2045 def test_lambda_no_change(self
):
2046 s
= """lambda x: x + 5"""
2049 def test_lambda_parens_single_arg(self
):
2050 b
= """lambda (x): x + 5"""
2051 a
= """lambda x: x + 5"""
2054 b
= """lambda(x): x + 5"""
2055 a
= """lambda x: x + 5"""
2058 b
= """lambda ((((x)))): x + 5"""
2059 a
= """lambda x: x + 5"""
2062 b
= """lambda((((x)))): x + 5"""
2063 a
= """lambda x: x + 5"""
2066 def test_lambda_simple(self
):
2067 b
= """lambda (x, y): x + f(y)"""
2068 a
= """lambda x_y: x_y[0] + f(x_y[1])"""
2071 b
= """lambda(x, y): x + f(y)"""
2072 a
= """lambda x_y: x_y[0] + f(x_y[1])"""
2075 b
= """lambda (((x, y))): x + f(y)"""
2076 a
= """lambda x_y: x_y[0] + f(x_y[1])"""
2079 b
= """lambda(((x, y))): x + f(y)"""
2080 a
= """lambda x_y: x_y[0] + f(x_y[1])"""
2083 def test_lambda_one_tuple(self
):
2084 b
= """lambda (x,): x + f(x)"""
2085 a
= """lambda x1: x1[0] + f(x1[0])"""
2088 b
= """lambda (((x,))): x + f(x)"""
2089 a
= """lambda x1: x1[0] + f(x1[0])"""
2092 def test_lambda_simple_multi_use(self
):
2093 b
= """lambda (x, y): x + x + f(x) + x"""
2094 a
= """lambda x_y: x_y[0] + x_y[0] + f(x_y[0]) + x_y[0]"""
2097 def test_lambda_simple_reverse(self
):
2098 b
= """lambda (x, y): y + x"""
2099 a
= """lambda x_y: x_y[1] + x_y[0]"""
2102 def test_lambda_nested(self
):
2103 b
= """lambda (x, (y, z)): x + y + z"""
2104 a
= """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
2107 b
= """lambda (((x, (y, z)))): x + y + z"""
2108 a
= """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
2111 def test_lambda_nested_multi_use(self
):
2112 b
= """lambda (x, (y, z)): x + y + f(y)"""
2113 a
= """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + f(x_y_z[1][0])"""
2116 class Test_methodattrs(FixerTestCase
):
2117 fixer
= "methodattrs"
2119 attrs
= ["func", "self", "class"]
2122 for attr
in self
.attrs
:
2123 b
= "a.im_%s" % attr
2125 a
= "a.__self__.__class__"
2127 a
= "a.__%s__" % attr
2130 b
= "self.foo.im_%s.foo_bar" % attr
2132 a
= "self.foo.__self__.__class__.foo_bar"
2134 a
= "self.foo.__%s__.foo_bar" % attr
2137 def test_unchanged(self
):
2138 for attr
in self
.attrs
:
2139 s
= "foo(im_%s + 5)" % attr
2142 s
= "f(foo.__%s__)" % attr
2145 s
= "f(foo.__%s__.foo)" % attr
2148 class Test_next(FixerTestCase
):
2157 b
= """a.b.c.d.next()"""
2158 a
= """next(a.b.c.d)"""
2162 b
= """(a + b).next()"""
2163 a
= """next((a + b))"""
2167 b
= """a().next()"""
2172 b
= """a().next() + b"""
2173 a
= """next(a()) + b"""
2177 b
= """c( a().next() + b)"""
2178 a
= """c( next(a()) + b)"""
2181 def test_prefix_preservation_1(self
):
2194 def test_prefix_preservation_2(self
):
2209 def test_prefix_preservation_3(self
):
2222 self
.check(b
, a
, ignore_warnings
=True)
2224 def test_prefix_preservation_4(self
):
2239 self
.check(b
, a
, ignore_warnings
=True)
2241 def test_prefix_preservation_5(self
):
2254 self
.check(b
, a
, ignore_warnings
=True)
2256 def test_prefix_preservation_6(self
):
2269 def test_method_1(self
):
2282 def test_method_2(self
):
2295 def test_method_3(self
):
2308 def test_method_4(self
):
2311 def __init__(self, foo):
2322 def __init__(self, foo):
2333 def test_method_unchanged(self
):
2336 def next(self, a, b):
2341 def test_shadowing_assign_simple(self
):
2346 def next(self, a, b):
2349 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2351 def test_shadowing_assign_tuple_1(self
):
2356 def next(self, a, b):
2359 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2361 def test_shadowing_assign_tuple_2(self
):
2363 (a, (b, (next, c)), a) = foo
2366 def next(self, a, b):
2369 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2371 def test_shadowing_assign_list_1(self
):
2376 def next(self, a, b):
2379 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2381 def test_shadowing_assign_list_2(self
):
2383 [a, [b, [next, c]], a] = foo
2386 def next(self, a, b):
2389 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2391 def test_builtin_assign(self
):
2394 __builtin__.next = foo
2397 def next(self, a, b):
2400 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2402 def test_builtin_assign_in_tuple(self
):
2405 (a, __builtin__.next) = foo
2408 def next(self, a, b):
2411 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2413 def test_builtin_assign_in_list(self
):
2416 [a, __builtin__.next] = foo
2419 def next(self, a, b):
2422 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2424 def test_assign_to_next(self
):
2430 def next(self, a, b):
2435 def test_assign_to_next_in_tuple(self
):
2441 def next(self, a, b):
2446 def test_assign_to_next_in_list(self
):
2452 def next(self, a, b):
2457 def test_shadowing_import_1(self
):
2459 import foo.bar as next
2462 def next(self, a, b):
2465 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2467 def test_shadowing_import_2(self
):
2469 import bar, bar.foo as next
2472 def next(self, a, b):
2475 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2477 def test_shadowing_import_3(self
):
2479 import bar, bar.foo as next, baz
2482 def next(self, a, b):
2485 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2487 def test_shadowing_import_from_1(self
):
2492 def next(self, a, b):
2495 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2497 def test_shadowing_import_from_2(self
):
2499 from x.a import next
2502 def next(self, a, b):
2505 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2507 def test_shadowing_import_from_3(self
):
2509 from x import a, next, b
2512 def next(self, a, b):
2515 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2517 def test_shadowing_import_from_4(self
):
2519 from x.a import a, next, b
2522 def next(self, a, b):
2525 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2527 def test_shadowing_funcdef_1(self
):
2533 def next(self, a, b):
2536 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2538 def test_shadowing_funcdef_2(self
):
2559 self
.warns(b
, a
, "Calls to builtin next() possibly shadowed")
2561 def test_shadowing_global_1(self
):
2567 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2569 def test_shadowing_global_2(self
):
2575 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2577 def test_shadowing_for_simple(self
):
2585 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2587 def test_shadowing_for_tuple_1(self
):
2589 for next, b in it():
2595 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2597 def test_shadowing_for_tuple_2(self
):
2599 for a, (next, c), b in it():
2605 self
.warns_unchanged(s
, "Calls to builtin next() possibly shadowed")
2607 def test_noncall_access_1(self
):
2608 b
= """gnext = g.next"""
2609 a
= """gnext = g.__next__"""
2612 def test_noncall_access_2(self
):
2613 b
= """f(g.next + 5)"""
2614 a
= """f(g.__next__ + 5)"""
2617 def test_noncall_access_3(self
):
2618 b
= """f(g().next + 5)"""
2619 a
= """f(g().__next__ + 5)"""
2622 class Test_nonzero(FixerTestCase
):
2628 def __nonzero__(self):
2641 def __nonzero__(self):
2651 def test_unchanged_1(self
):
2659 def test_unchanged_2(self
):
2662 def __nonzero__(self, a):
2667 def test_unchanged_func(self
):
2669 def __nonzero__(self):
2674 class Test_numliterals(FixerTestCase
):
2675 fixer
= "numliterals"
2677 def test_octal_1(self
):
2682 def test_long_int_1(self
):
2687 def test_long_int_2(self
):
2692 def test_long_hex(self
):
2697 def test_comments_and_spacing(self
):
2702 b
= """b = 0755 # spam"""
2703 a
= """b = 0o755 # spam"""
2706 def test_unchanged_int(self
):
2710 def test_unchanged_float(self
):
2714 def test_unchanged_octal(self
):
2718 def test_unchanged_hex(self
):
2722 def test_unchanged_exp(self
):
2726 def test_unchanged_complex_int(self
):
2730 def test_unchanged_complex_float(self
):
2731 s
= """5.4 + 4.9j"""
2734 def test_unchanged_complex_bare(self
):
2740 class Test_renames(FixerTestCase
):
2743 modules
= {"sys": ("maxint", "maxsize"),
2746 def test_import_from(self
):
2747 for mod
, (old
, new
) in self
.modules
.items():
2748 b
= "from %s import %s" % (mod
, old
)
2749 a
= "from %s import %s" % (mod
, new
)
2752 s
= "from foo import %s" % old
2755 def test_import_from_as(self
):
2756 for mod
, (old
, new
) in self
.modules
.items():
2757 b
= "from %s import %s as foo_bar" % (mod
, old
)
2758 a
= "from %s import %s as foo_bar" % (mod
, new
)
2761 def test_import_module_usage(self
):
2762 for mod
, (old
, new
) in self
.modules
.items():
2766 """ % (mod
, mod
, mod
, old
)
2770 """ % (mod
, mod
, mod
, new
)
2773 def XXX_test_from_import_usage(self
):
2774 # not implemented yet
2775 for mod
, (old
, new
) in self
.modules
.items():
2779 """ % (mod
, old
, mod
, old
)
2783 """ % (mod
, new
, mod
, new
)
2786 class Test_unicode(FixerTestCase
):
2789 def test_whitespace(self
):
2790 b
= """unicode( x)"""
2794 b
= """ unicode(x )"""
2802 def test_unicode_call(self
):
2803 b
= """unicode(x, y, z)"""
2804 a
= """str(x, y, z)"""
2807 def test_unichr(self
):
2808 b
= """unichr(u'h')"""
2812 def test_unicode_literal_1(self
):
2817 def test_unicode_literal_2(self
):
2822 def test_unicode_literal_3(self
):
2823 b
= """UR'''x''' """
2827 class Test_callable(FixerTestCase
):
2830 def test_prefix_preservation(self
):
2831 b
= """callable( x)"""
2832 a
= """import collections\nisinstance( x, collections.Callable)"""
2835 b
= """if callable(x): pass"""
2836 a
= """import collections
2837 if isinstance(x, collections.Callable): pass"""
2840 def test_callable_call(self
):
2841 b
= """callable(x)"""
2842 a
= """import collections\nisinstance(x, collections.Callable)"""
2845 def test_global_import(self
):
2848 callable(foo)"""[1:]
2852 isinstance(foo, collections.Callable)"""[1:]
2858 callable(foo)"""[1:]
2859 # same output if it was already imported
2863 from collections import *
2865 callable(foo)"""[1:]
2867 from collections import *
2870 isinstance(foo, collections.Callable)"""[1:]
2875 do_some_other_stuff()
2876 assert callable(do_stuff)"""[1:]
2880 do_some_other_stuff()
2881 assert isinstance(do_stuff, collections.Callable)"""[1:]
2885 if isinstance(do_stuff, Callable):
2886 assert callable(do_stuff)
2888 if not callable(do_stuff):
2891 assert callable(do_stuff)
2893 assert not callable(do_stuff)"""[1:]
2896 if isinstance(do_stuff, Callable):
2897 assert isinstance(do_stuff, collections.Callable)
2899 if not isinstance(do_stuff, collections.Callable):
2902 assert isinstance(do_stuff, collections.Callable)
2904 assert not isinstance(do_stuff, collections.Callable)"""[1:]
2907 def test_callable_should_not_change(self
):
2908 a
= """callable(*x)"""
2911 a
= """callable(x, y)"""
2914 a
= """callable(x, kw=y)"""
2917 a
= """callable()"""
2920 class Test_filter(FixerTestCase
):
2923 def test_prefix_preservation(self
):
2924 b
= """x = filter( foo, 'abc' )"""
2925 a
= """x = list(filter( foo, 'abc' ))"""
2928 b
= """x = filter( None , 'abc' )"""
2929 a
= """x = [_f for _f in 'abc' if _f]"""
2932 def test_filter_basic(self
):
2933 b
= """x = filter(None, 'abc')"""
2934 a
= """x = [_f for _f in 'abc' if _f]"""
2937 b
= """x = len(filter(f, 'abc'))"""
2938 a
= """x = len(list(filter(f, 'abc')))"""
2941 b
= """x = filter(lambda x: x%2 == 0, range(10))"""
2942 a
= """x = [x for x in range(10) if x%2 == 0]"""
2945 # Note the parens around x
2946 b
= """x = filter(lambda (x): x%2 == 0, range(10))"""
2947 a
= """x = [x for x in range(10) if x%2 == 0]"""
2950 # XXX This (rare) case is not supported
2951 ## b = """x = filter(f, 'abc')[0]"""
2952 ## a = """x = list(filter(f, 'abc'))[0]"""
2955 def test_filter_nochange(self
):
2956 a
= """b.join(filter(f, 'abc'))"""
2958 a
= """(a + foo(5)).join(filter(f, 'abc'))"""
2960 a
= """iter(filter(f, 'abc'))"""
2962 a
= """list(filter(f, 'abc'))"""
2964 a
= """list(filter(f, 'abc'))[0]"""
2966 a
= """set(filter(f, 'abc'))"""
2968 a
= """set(filter(f, 'abc')).pop()"""
2970 a
= """tuple(filter(f, 'abc'))"""
2972 a
= """any(filter(f, 'abc'))"""
2974 a
= """all(filter(f, 'abc'))"""
2976 a
= """sum(filter(f, 'abc'))"""
2978 a
= """sorted(filter(f, 'abc'))"""
2980 a
= """sorted(filter(f, 'abc'), key=blah)"""
2982 a
= """sorted(filter(f, 'abc'), key=blah)[0]"""
2984 a
= """for i in filter(f, 'abc'): pass"""
2986 a
= """[x for x in filter(f, 'abc')]"""
2988 a
= """(x for x in filter(f, 'abc'))"""
2991 def test_future_builtins(self
):
2992 a
= "from future_builtins import spam, filter; filter(f, 'ham')"
2995 b
= """from future_builtins import spam; x = filter(f, 'abc')"""
2996 a
= """from future_builtins import spam; x = list(filter(f, 'abc'))"""
2999 a
= "from future_builtins import *; filter(f, 'ham')"
3002 class Test_map(FixerTestCase
):
3005 def check(self
, b
, a
):
3006 self
.unchanged("from future_builtins import map; " + b
, a
)
3007 super(Test_map
, self
).check(b
, a
)
3009 def test_prefix_preservation(self
):
3010 b
= """x = map( f, 'abc' )"""
3011 a
= """x = list(map( f, 'abc' ))"""
3014 def test_trailing_comment(self
):
3015 b
= """x = map(f, 'abc') # foo"""
3016 a
= """x = list(map(f, 'abc')) # foo"""
3019 def test_None_with_multiple_arguments(self
):
3020 s
= """x = map(None, a, b, c)"""
3021 self
.warns_unchanged(s
, "cannot convert map(None, ...) with "
3022 "multiple arguments")
3024 def test_map_basic(self
):
3025 b
= """x = map(f, 'abc')"""
3026 a
= """x = list(map(f, 'abc'))"""
3029 b
= """x = len(map(f, 'abc', 'def'))"""
3030 a
= """x = len(list(map(f, 'abc', 'def')))"""
3033 b
= """x = map(None, 'abc')"""
3034 a
= """x = list('abc')"""
3037 b
= """x = map(lambda x: x+1, range(4))"""
3038 a
= """x = [x+1 for x in range(4)]"""
3041 # Note the parens around x
3042 b
= """x = map(lambda (x): x+1, range(4))"""
3043 a
= """x = [x+1 for x in range(4)]"""
3056 self
.warns(b
, a
, "You should use a for loop here")
3058 # XXX This (rare) case is not supported
3059 ## b = """x = map(f, 'abc')[0]"""
3060 ## a = """x = list(map(f, 'abc'))[0]"""
3063 def test_map_nochange(self
):
3064 a
= """b.join(map(f, 'abc'))"""
3066 a
= """(a + foo(5)).join(map(f, 'abc'))"""
3068 a
= """iter(map(f, 'abc'))"""
3070 a
= """list(map(f, 'abc'))"""
3072 a
= """list(map(f, 'abc'))[0]"""
3074 a
= """set(map(f, 'abc'))"""
3076 a
= """set(map(f, 'abc')).pop()"""
3078 a
= """tuple(map(f, 'abc'))"""
3080 a
= """any(map(f, 'abc'))"""
3082 a
= """all(map(f, 'abc'))"""
3084 a
= """sum(map(f, 'abc'))"""
3086 a
= """sorted(map(f, 'abc'))"""
3088 a
= """sorted(map(f, 'abc'), key=blah)"""
3090 a
= """sorted(map(f, 'abc'), key=blah)[0]"""
3092 a
= """for i in map(f, 'abc'): pass"""
3094 a
= """[x for x in map(f, 'abc')]"""
3096 a
= """(x for x in map(f, 'abc'))"""
3099 def test_future_builtins(self
):
3100 a
= "from future_builtins import spam, map, eggs; map(f, 'ham')"
3103 b
= """from future_builtins import spam, eggs; x = map(f, 'abc')"""
3104 a
= """from future_builtins import spam, eggs; x = list(map(f, 'abc'))"""
3107 a
= "from future_builtins import *; map(f, 'ham')"
3110 class Test_zip(FixerTestCase
):
3113 def check(self
, b
, a
):
3114 self
.unchanged("from future_builtins import zip; " + b
, a
)
3115 super(Test_zip
, self
).check(b
, a
)
3117 def test_zip_basic(self
):
3118 b
= """x = zip(a, b, c)"""
3119 a
= """x = list(zip(a, b, c))"""
3122 b
= """x = len(zip(a, b))"""
3123 a
= """x = len(list(zip(a, b)))"""
3126 def test_zip_nochange(self
):
3127 a
= """b.join(zip(a, b))"""
3129 a
= """(a + foo(5)).join(zip(a, b))"""
3131 a
= """iter(zip(a, b))"""
3133 a
= """list(zip(a, b))"""
3135 a
= """list(zip(a, b))[0]"""
3137 a
= """set(zip(a, b))"""
3139 a
= """set(zip(a, b)).pop()"""
3141 a
= """tuple(zip(a, b))"""
3143 a
= """any(zip(a, b))"""
3145 a
= """all(zip(a, b))"""
3147 a
= """sum(zip(a, b))"""
3149 a
= """sorted(zip(a, b))"""
3151 a
= """sorted(zip(a, b), key=blah)"""
3153 a
= """sorted(zip(a, b), key=blah)[0]"""
3155 a
= """for i in zip(a, b): pass"""
3157 a
= """[x for x in zip(a, b)]"""
3159 a
= """(x for x in zip(a, b))"""
3162 def test_future_builtins(self
):
3163 a
= "from future_builtins import spam, zip, eggs; zip(a, b)"
3166 b
= """from future_builtins import spam, eggs; x = zip(a, b)"""
3167 a
= """from future_builtins import spam, eggs; x = list(zip(a, b))"""
3170 a
= "from future_builtins import *; zip(a, b)"
3173 class Test_standarderror(FixerTestCase
):
3174 fixer
= "standarderror"
3177 b
= """x = StandardError()"""
3178 a
= """x = Exception()"""
3181 b
= """x = StandardError(a, b, c)"""
3182 a
= """x = Exception(a, b, c)"""
3185 b
= """f(2 + StandardError(a, b, c))"""
3186 a
= """f(2 + Exception(a, b, c))"""
3189 class Test_types(FixerTestCase
):
3192 def test_basic_types_convert(self
):
3193 b
= """types.StringType"""
3197 b
= """types.DictType"""
3201 b
= """types . IntType"""
3205 b
= """types.ListType"""
3209 b
= """types.LongType"""
3213 b
= """types.NoneType"""
3214 a
= """type(None)"""
3217 class Test_idioms(FixerTestCase
):
3220 def test_while(self
):
3221 b
= """while 1: foo()"""
3222 a
= """while True: foo()"""
3225 b
= """while 1: foo()"""
3226 a
= """while True: foo()"""
3239 def test_while_unchanged(self
):
3240 s
= """while 11: foo()"""
3243 s
= """while 0: foo()"""
3246 s
= """while foo(): foo()"""
3249 s
= """while []: foo()"""
3252 def test_eq_simple(self
):
3253 b
= """type(x) == T"""
3254 a
= """isinstance(x, T)"""
3257 b
= """if type(x) == T: pass"""
3258 a
= """if isinstance(x, T): pass"""
3261 def test_eq_reverse(self
):
3262 b
= """T == type(x)"""
3263 a
= """isinstance(x, T)"""
3266 b
= """if T == type(x): pass"""
3267 a
= """if isinstance(x, T): pass"""
3270 def test_eq_expression(self
):
3271 b
= """type(x+y) == d.get('T')"""
3272 a
= """isinstance(x+y, d.get('T'))"""
3275 b
= """type( x + y) == d.get('T')"""
3276 a
= """isinstance(x + y, d.get('T'))"""
3279 def test_is_simple(self
):
3280 b
= """type(x) is T"""
3281 a
= """isinstance(x, T)"""
3284 b
= """if type(x) is T: pass"""
3285 a
= """if isinstance(x, T): pass"""
3288 def test_is_reverse(self
):
3289 b
= """T is type(x)"""
3290 a
= """isinstance(x, T)"""
3293 b
= """if T is type(x): pass"""
3294 a
= """if isinstance(x, T): pass"""
3297 def test_is_expression(self
):
3298 b
= """type(x+y) is d.get('T')"""
3299 a
= """isinstance(x+y, d.get('T'))"""
3302 b
= """type( x + y) is d.get('T')"""
3303 a
= """isinstance(x + y, d.get('T'))"""
3306 def test_is_not_simple(self
):
3307 b
= """type(x) is not T"""
3308 a
= """not isinstance(x, T)"""
3311 b
= """if type(x) is not T: pass"""
3312 a
= """if not isinstance(x, T): pass"""
3315 def test_is_not_reverse(self
):
3316 b
= """T is not type(x)"""
3317 a
= """not isinstance(x, T)"""
3320 b
= """if T is not type(x): pass"""
3321 a
= """if not isinstance(x, T): pass"""
3324 def test_is_not_expression(self
):
3325 b
= """type(x+y) is not d.get('T')"""
3326 a
= """not isinstance(x+y, d.get('T'))"""
3329 b
= """type( x + y) is not d.get('T')"""
3330 a
= """not isinstance(x + y, d.get('T'))"""
3333 def test_ne_simple(self
):
3334 b
= """type(x) != T"""
3335 a
= """not isinstance(x, T)"""
3338 b
= """if type(x) != T: pass"""
3339 a
= """if not isinstance(x, T): pass"""
3342 def test_ne_reverse(self
):
3343 b
= """T != type(x)"""
3344 a
= """not isinstance(x, T)"""
3347 b
= """if T != type(x): pass"""
3348 a
= """if not isinstance(x, T): pass"""
3351 def test_ne_expression(self
):
3352 b
= """type(x+y) != d.get('T')"""
3353 a
= """not isinstance(x+y, d.get('T'))"""
3356 b
= """type( x + y) != d.get('T')"""
3357 a
= """not isinstance(x + y, d.get('T'))"""
3360 def test_type_unchanged(self
):
3361 a
= """type(x).__name__"""
3364 def test_sort_list_call(self
):
3377 v = list(foo(b) + d)
3382 v = sorted(foo(b) + d)
3464 def test_sort_simple_expr(self
):
3493 v = sorted(b.keys())
3504 v = sorted(foo(b) + d)
3546 def test_sort_unchanged(self
):
3561 class Test_basestring(FixerTestCase
):
3562 fixer
= "basestring"
3564 def test_basestring(self
):
3565 b
= """isinstance(x, basestring)"""
3566 a
= """isinstance(x, str)"""
3569 class Test_buffer(FixerTestCase
):
3572 def test_buffer(self
):
3573 b
= """x = buffer(y)"""
3574 a
= """x = memoryview(y)"""
3577 def test_slicing(self
):
3578 b
= """buffer(y)[4:5]"""
3579 a
= """memoryview(y)[4:5]"""
3582 class Test_future(FixerTestCase
):
3585 def test_future(self
):
3586 b
= """from __future__ import braces"""
3590 b
= """# comment\nfrom __future__ import braces"""
3591 a
= """# comment\n"""
3594 b
= """from __future__ import braces\n# comment"""
3595 a
= """\n# comment"""
3598 def test_run_order(self
):
3599 self
.assert_runs_after('print')
3601 class Test_itertools(FixerTestCase
):
3604 def checkall(self
, before
, after
):
3605 # Because we need to check with and without the itertools prefix
3606 # and on each of the three functions, these loops make it all
3608 for i
in ('itertools.', ''):
3609 for f
in ('map', 'filter', 'zip'):
3610 b
= before
%(i
+'i'+f
)
3615 # A simple example -- test_1 covers exactly the same thing,
3616 # but it's not quite as clear.
3617 b
= "itertools.izip(a, b)"
3626 def test_qualified(self
):
3627 b
= """itertools.ifilterfalse(a, b)"""
3628 a
= """itertools.filterfalse(a, b)"""
3631 b
= """itertools.izip_longest(a, b)"""
3632 a
= """itertools.zip_longest(a, b)"""
3636 b
= """ifilterfalse(a, b)"""
3637 a
= """filterfalse(a, b)"""
3640 b
= """izip_longest(a, b)"""
3641 a
= """zip_longest(a, b)"""
3644 def test_space_1(self
):
3649 def test_space_2(self
):
3650 b
= """ itertools.ifilterfalse(a, b)"""
3651 a
= """ itertools.filterfalse(a, b)"""
3654 b
= """ itertools.izip_longest(a, b)"""
3655 a
= """ itertools.zip_longest(a, b)"""
3658 def test_run_order(self
):
3659 self
.assert_runs_after('map', 'zip', 'filter')
3662 class Test_itertools_imports(FixerTestCase
):
3663 fixer
= 'itertools_imports'
3665 def test_reduced(self
):
3666 b
= "from itertools import imap, izip, foo"
3667 a
= "from itertools import foo"
3670 b
= "from itertools import bar, imap, izip, foo"
3671 a
= "from itertools import bar, foo"
3674 b
= "from itertools import chain, imap, izip"
3675 a
= "from itertools import chain"
3678 def test_comments(self
):
3679 b
= "#foo\nfrom itertools import imap, izip"
3683 def test_none(self
):
3684 b
= "from itertools import imap, izip"
3688 b
= "from itertools import izip"
3692 def test_import_as(self
):
3693 b
= "from itertools import izip, bar as bang, imap"
3694 a
= "from itertools import bar as bang"
3697 b
= "from itertools import izip as _zip, imap, bar"
3698 a
= "from itertools import bar"
3701 b
= "from itertools import imap as _map"
3705 b
= "from itertools import imap as _map, izip as _zip"
3709 s
= "from itertools import bar as bang"
3712 def test_ifilter_and_zip_longest(self
):
3713 for name
in "filterfalse", "zip_longest":
3714 b
= "from itertools import i%s" % (name
,)
3715 a
= "from itertools import %s" % (name
,)
3718 b
= "from itertools import imap, i%s, foo" % (name
,)
3719 a
= "from itertools import %s, foo" % (name
,)
3722 b
= "from itertools import bar, i%s, foo" % (name
,)
3723 a
= "from itertools import bar, %s, foo" % (name
,)
3726 def test_import_star(self
):
3727 s
= "from itertools import *"
3731 def test_unchanged(self
):
3732 s
= "from itertools import foo"
3736 class Test_import(FixerTestCase
):
3740 super(Test_import
, self
).setUp()
3741 # Need to replace fix_import's exists method
3742 # so we can check that it's doing the right thing
3743 self
.files_checked
= []
3744 self
.present_files
= set()
3745 self
.always_exists
= True
3746 def fake_exists(name
):
3747 self
.files_checked
.append(name
)
3748 return self
.always_exists
or (name
in self
.present_files
)
3750 from lib2to3
.fixes
import fix_import
3751 fix_import
.exists
= fake_exists
3754 from lib2to3
.fixes
import fix_import
3755 fix_import
.exists
= os
.path
.exists
3757 def check_both(self
, b
, a
):
3758 self
.always_exists
= True
3759 super(Test_import
, self
).check(b
, a
)
3760 self
.always_exists
= False
3761 super(Test_import
, self
).unchanged(b
)
3763 def test_files_checked(self
):
3765 # Takes a unix path and returns a path with correct separators
3766 return os
.path
.pathsep
.join(path
.split("/"))
3768 self
.always_exists
= False
3769 self
.present_files
= set(['__init__.py'])
3770 expected_extensions
= ('.py', os
.path
.sep
, '.pyc', '.so', '.sl', '.pyd')
3771 names_to_test
= (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))
3773 for name
in names_to_test
:
3774 self
.files_checked
= []
3775 self
.filename
= name
3776 self
.unchanged("import jam")
3778 if os
.path
.dirname(name
):
3779 name
= os
.path
.dirname(name
) + '/jam'
3782 expected_checks
= set(name
+ ext
for ext
in expected_extensions
)
3783 expected_checks
.add("__init__.py")
3785 self
.assertEqual(set(self
.files_checked
), expected_checks
)
3787 def test_not_in_package(self
):
3789 self
.always_exists
= False
3790 self
.present_files
= set(["bar.py"])
3793 def test_with_absolute_import_enabled(self
):
3794 s
= "from __future__ import absolute_import\nimport bar"
3795 self
.always_exists
= False
3796 self
.present_files
= set(["__init__.py", "bar.py"])
3799 def test_in_package(self
):
3801 a
= "from . import bar"
3802 self
.always_exists
= False
3803 self
.present_files
= set(["__init__.py", "bar.py"])
3806 def test_import_from_package(self
):
3808 a
= "from . import bar"
3809 self
.always_exists
= False
3810 self
.present_files
= set(["__init__.py", "bar" + os
.path
.sep
])
3813 def test_already_relative_import(self
):
3814 s
= "from . import bar"
3817 def test_comments_and_indent(self
):
3818 b
= "import bar # Foo"
3819 a
= "from . import bar # Foo"
3822 def test_from(self
):
3823 b
= "from foo import bar, baz"
3824 a
= "from .foo import bar, baz"
3825 self
.check_both(b
, a
)
3827 b
= "from foo import bar"
3828 a
= "from .foo import bar"
3829 self
.check_both(b
, a
)
3831 b
= "from foo import (bar, baz)"
3832 a
= "from .foo import (bar, baz)"
3833 self
.check_both(b
, a
)
3835 def test_dotted_from(self
):
3836 b
= "from green.eggs import ham"
3837 a
= "from .green.eggs import ham"
3838 self
.check_both(b
, a
)
3840 def test_from_as(self
):
3841 b
= "from green.eggs import ham as spam"
3842 a
= "from .green.eggs import ham as spam"
3843 self
.check_both(b
, a
)
3845 def test_import(self
):
3847 a
= "from . import foo"
3848 self
.check_both(b
, a
)
3850 b
= "import foo, bar"
3851 a
= "from . import foo, bar"
3852 self
.check_both(b
, a
)
3854 b
= "import foo, bar, x"
3855 a
= "from . import foo, bar, x"
3856 self
.check_both(b
, a
)
3858 b
= "import x, y, z"
3859 a
= "from . import x, y, z"
3860 self
.check_both(b
, a
)
3862 def test_import_as(self
):
3863 b
= "import foo as x"
3864 a
= "from . import foo as x"
3865 self
.check_both(b
, a
)
3867 b
= "import a as b, b as c, c as d"
3868 a
= "from . import a as b, b as c, c as d"
3869 self
.check_both(b
, a
)
3871 def test_local_and_absolute(self
):
3872 self
.always_exists
= False
3873 self
.present_files
= set(["foo.py", "__init__.py"])
3875 s
= "import foo, bar"
3876 self
.warns_unchanged(s
, "absolute and local imports together")
3878 def test_dotted_import(self
):
3879 b
= "import foo.bar"
3880 a
= "from . import foo.bar"
3881 self
.check_both(b
, a
)
3883 def test_dotted_import_as(self
):
3884 b
= "import foo.bar as bang"
3885 a
= "from . import foo.bar as bang"
3886 self
.check_both(b
, a
)
3888 def test_prefix(self
):
3895 from . import foo.bar
3897 self
.check_both(b
, a
)
3900 class Test_set_literal(FixerTestCase
):
3902 fixer
= "set_literal"
3904 def test_basic(self
):
3905 b
= """set([1, 2, 3])"""
3909 b
= """set((1, 2, 3))"""
3920 b
= """set((a, b))"""
3924 b
= """set([a, b])"""
3927 b
= """set((a*234, f(args=23)))"""
3928 a
= """{a*234, f(args=23)}"""
3931 b
= """set([a*23, f(23)])"""
3932 a
= """{a*23, f(23)}"""
3935 b
= """set([a-234**23])"""
3936 a
= """{a-234**23}"""
3939 def test_listcomps(self
):
3940 b
= """set([x for x in y])"""
3941 a
= """{x for x in y}"""
3944 b
= """set([x for x in y if x == m])"""
3945 a
= """{x for x in y if x == m}"""
3948 b
= """set([x for x in y for a in b])"""
3949 a
= """{x for x in y for a in b}"""
3952 b
= """set([f(x) - 23 for x in y])"""
3953 a
= """{f(x) - 23 for x in y}"""
3956 def test_whitespace(self
):
3957 b
= """set( [1, 2])"""
3961 b
= """set([1 , 2])"""
3965 b
= """set([ 1 ])"""
3969 b
= """set( [1] )"""
3973 b
= """set([ 1, 2 ])"""
3977 b
= """set([x for x in y ])"""
3978 a
= """{x for x in y }"""
3988 def test_comments(self
):
3989 b
= """set((1, 2)) # Hi"""
3990 a
= """{1, 2} # Hi"""
3993 # This isn't optimal behavior, but the fixer is optional.
4006 def test_unchanged(self
):
4013 s
= """set(a, b, c)"""
4016 # Don't transform generators because they might have to be lazy.
4017 s
= """set(x for x in y)"""
4020 s
= """set(x for x in y if z)"""
4023 s
= """set(a*823-23**2 + f(23))"""
4027 class Test_sys_exc(FixerTestCase
):
4032 a
= "sys.exc_info()[0]"
4037 a
= "sys.exc_info()[1]"
4041 b
= "sys.exc_traceback"
4042 a
= "sys.exc_info()[2]"
4046 b
= "sys.exc_type # Foo"
4047 a
= "sys.exc_info()[0] # Foo"
4052 a
= "sys. exc_info()[0]"
4057 a
= "sys .exc_info()[0]"
4061 class Test_paren(FixerTestCase
):
4065 b
= """[i for i in 1, 2 ]"""
4066 a
= """[i for i in (1, 2) ]"""
4070 b
= """[i for i in 1, 2, ]"""
4071 a
= """[i for i in (1, 2,) ]"""
4075 b
= """[i for i in 1, 2 ]"""
4076 a
= """[i for i in (1, 2) ]"""
4080 b
= """[i for i in 1, 2 if i]"""
4081 a
= """[i for i in (1, 2) if i]"""
4085 b
= """[i for i in 1, 2 ]"""
4086 a
= """[i for i in (1, 2) ]"""
4090 b
= """(i for i in 1, 2)"""
4091 a
= """(i for i in (1, 2))"""
4095 b
= """(i for i in 1 ,2 if i)"""
4096 a
= """(i for i in (1 ,2) if i)"""
4099 def test_unchanged_0(self
):
4100 s
= """[i for i in (1, 2)]"""
4103 def test_unchanged_1(self
):
4104 s
= """[i for i in foo()]"""
4107 def test_unchanged_2(self
):
4108 s
= """[i for i in (1, 2) if nothing]"""
4111 def test_unchanged_3(self
):
4112 s
= """(i for i in (1, 2))"""
4115 def test_unchanged_4(self
):
4116 s
= """[i for i in m]"""
4119 class Test_metaclass(FixerTestCase
):
4123 def test_unchanged(self
):
4124 self
.unchanged("class X(): pass")
4125 self
.unchanged("class X(object): pass")
4126 self
.unchanged("class X(object1, object2): pass")
4127 self
.unchanged("class X(object1, object2, object3): pass")
4128 self
.unchanged("class X(metaclass=Meta): pass")
4129 self
.unchanged("class X(b, arg=23, metclass=Meta): pass")
4130 self
.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass")
4134 def __metaclass__(self): pass
4144 def test_comments(self
):
4148 __metaclass__ = AppleMeta
4151 class X(metaclass=AppleMeta):
4159 __metaclass__ = Meta
4163 class X(metaclass=Meta):
4169 def test_meta(self
):
4170 # no-parent class, odd body
4177 class X(metaclass=Q):
4182 # one parent class, no body
4183 b
= """class X(object): __metaclass__ = Q"""
4184 a
= """class X(object, metaclass=Q): pass"""
4188 # one parent, simple body
4191 __metaclass__ = Meta
4195 class X(object, metaclass=Meta):
4202 __metaclass__ = Meta; x = 4; g = 23
4205 class X(metaclass=Meta):
4210 # one parent, simple body, __metaclass__ last
4214 __metaclass__ = Meta
4217 class X(object, metaclass=Meta):
4222 # redefining __metaclass__
4230 class X(metaclass=B):
4235 # multiple inheritance, simple body
4237 class X(clsA, clsB):
4238 __metaclass__ = Meta
4242 class X(clsA, clsB, metaclass=Meta):
4247 # keywords in the class statement
4248 b
= """class m(a, arg=23): __metaclass__ = Meta"""
4249 a
= """class m(a, arg=23, metaclass=Meta): pass"""
4253 class X(expression(2 + 4)):
4254 __metaclass__ = Meta
4257 class X(expression(2 + 4), metaclass=Meta):
4263 class X(expression(2 + 4), x**4):
4264 __metaclass__ = Meta
4267 class X(expression(2 + 4), x**4, metaclass=Meta):
4274 __metaclass__ = Meta
4278 class X(metaclass=Meta):
4284 class Test_getcwdu(FixerTestCase
):
4288 def test_basic(self
):
4289 b
= """os.getcwdu"""
4293 b
= """os.getcwdu()"""
4294 a
= """os.getcwd()"""
4297 b
= """meth = os.getcwdu"""
4298 a
= """meth = os.getcwd"""
4301 b
= """os.getcwdu(args)"""
4302 a
= """os.getcwd(args)"""
4305 def test_comment(self
):
4306 b
= """os.getcwdu() # Foo"""
4307 a
= """os.getcwd() # Foo"""
4310 def test_unchanged(self
):
4311 s
= """os.getcwd()"""
4317 s
= """os.getcwdb()"""
4320 def test_indentation(self
):
4331 def test_multilation(self
):
4332 b
= """os .getcwdu()"""
4333 a
= """os .getcwd()"""
4336 b
= """os. getcwdu"""
4337 a
= """os. getcwd"""
4340 b
= """os.getcwdu ( )"""
4341 a
= """os.getcwd ( )"""
4345 class Test_operator(FixerTestCase
):
4349 def test_operator_isCallable(self
):
4350 b
= "operator.isCallable(x)"
4351 a
= "hasattr(x, '__call__')"
4354 def test_operator_sequenceIncludes(self
):
4355 b
= "operator.sequenceIncludes(x, y)"
4356 a
= "operator.contains(x, y)"
4359 b
= "operator .sequenceIncludes(x, y)"
4360 a
= "operator .contains(x, y)"
4363 b
= "operator. sequenceIncludes(x, y)"
4364 a
= "operator. contains(x, y)"
4367 def test_operator_isSequenceType(self
):
4368 b
= "operator.isSequenceType(x)"
4369 a
= "import collections\nisinstance(x, collections.Sequence)"
4372 def test_operator_isMappingType(self
):
4373 b
= "operator.isMappingType(x)"
4374 a
= "import collections\nisinstance(x, collections.Mapping)"
4377 def test_operator_isNumberType(self
):
4378 b
= "operator.isNumberType(x)"
4379 a
= "import numbers\nisinstance(x, numbers.Number)"
4382 def test_operator_repeat(self
):
4383 b
= "operator.repeat(x, n)"
4384 a
= "operator.mul(x, n)"
4387 b
= "operator .repeat(x, n)"
4388 a
= "operator .mul(x, n)"
4391 b
= "operator. repeat(x, n)"
4392 a
= "operator. mul(x, n)"
4395 def test_operator_irepeat(self
):
4396 b
= "operator.irepeat(x, n)"
4397 a
= "operator.imul(x, n)"
4400 b
= "operator .irepeat(x, n)"
4401 a
= "operator .imul(x, n)"
4404 b
= "operator. irepeat(x, n)"
4405 a
= "operator. imul(x, n)"
4408 def test_bare_isCallable(self
):
4410 t
= "You should use 'hasattr(x, '__call__')' here."
4411 self
.warns_unchanged(s
, t
)
4413 def test_bare_sequenceIncludes(self
):
4414 s
= "sequenceIncludes(x, y)"
4415 t
= "You should use 'operator.contains(x, y)' here."
4416 self
.warns_unchanged(s
, t
)
4418 def test_bare_operator_isSequenceType(self
):
4419 s
= "isSequenceType(z)"
4420 t
= "You should use 'isinstance(z, collections.Sequence)' here."
4421 self
.warns_unchanged(s
, t
)
4423 def test_bare_operator_isMappingType(self
):
4424 s
= "isMappingType(x)"
4425 t
= "You should use 'isinstance(x, collections.Mapping)' here."
4426 self
.warns_unchanged(s
, t
)
4428 def test_bare_operator_isNumberType(self
):
4429 s
= "isNumberType(y)"
4430 t
= "You should use 'isinstance(y, numbers.Number)' here."
4431 self
.warns_unchanged(s
, t
)
4433 def test_bare_operator_repeat(self
):
4435 t
= "You should use 'operator.mul(x, n)' here."
4436 self
.warns_unchanged(s
, t
)
4438 def test_bare_operator_irepeat(self
):
4439 s
= "irepeat(y, 187)"
4440 t
= "You should use 'operator.imul(y, 187)' here."
4441 self
.warns_unchanged(s
, t
)
4444 class Test_exitfunc(FixerTestCase
):
4448 def test_simple(self
):
4451 sys.exitfunc = my_atexit
4456 atexit.register(my_atexit)
4460 def test_names_import(self
):
4463 sys.exitfunc = my_func
4466 import sys, crumbs, atexit
4467 atexit.register(my_func)
4471 def test_complex_expression(self
):
4474 sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
4479 atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
4483 def test_comments(self
):
4486 sys.exitfunc = f # Blah
4491 atexit.register(f) # Blah
4496 import apples, sys, crumbs, larry # Pleasant comments
4500 import apples, sys, crumbs, larry, atexit # Pleasant comments
4501 atexit.register(func)
4505 def test_in_a_function(self
):
4515 atexit.register(func)
4519 def test_no_sys_import(self
):
4520 b
= """sys.exitfunc = f"""
4521 a
= """atexit.register(f)"""
4522 msg
= ("Can't find sys import; Please add an atexit import at the "
4523 "top of your file.")
4524 self
.warns(b
, a
, msg
)
4527 def test_unchanged(self
):
4528 s
= """f(sys.exitfunc)"""