1
#!/usr/bin/env python2.5
2
""" Test suite for the fixer modules """
3
# Author: Collin Winter
7
from tests import support
14
from itertools import chain
15
from operator import itemgetter
18
from lib2to3 import pygram, pytree, refactor, fixer_util
21
class FixerTestCase(support.TestCase):
22
def setUp(self, fix_list=None):
24
fix_list = [self.fixer]
25
options = {"print_function" : False}
26
self.refactor = support.get_refactorer(fix_list, options)
28
self.filename = "<string>"
30
for fixer in chain(self.refactor.pre_order,
31
self.refactor.post_order):
32
fixer.log = self.fixer_log
34
def _check(self, before, after):
35
before = support.reformat(before)
36
after = support.reformat(after)
37
tree = self.refactor.refactor_string(before, self.filename)
38
self.failUnlessEqual(after, str(tree))
41
def check(self, before, after, ignore_warnings=False):
42
tree = self._check(before, after)
43
self.failUnless(tree.was_changed)
44
if not ignore_warnings:
45
self.failUnlessEqual(self.fixer_log, [])
47
def warns(self, before, after, message, unchanged=False):
48
tree = self._check(before, after)
49
self.failUnless(message in "".join(self.fixer_log))
51
self.failUnless(tree.was_changed)
53
def warns_unchanged(self, before, message):
54
self.warns(before, before, message, unchanged=True)
56
def unchanged(self, before, ignore_warnings=False):
57
self._check(before, before)
58
if not ignore_warnings:
59
self.failUnlessEqual(self.fixer_log, [])
61
def assert_runs_after(self, *names):
64
options = {"print_function" : False}
65
r = support.get_refactorer(fixes, options)
66
(pre, post) = r.get_fixers()
67
n = "fix_" + self.fixer
68
if post and post[-1].__class__.__module__.endswith(n):
69
# We're the last fixer to run
71
if pre and pre[-1].__class__.__module__.endswith(n) and not post:
72
# We're the last in pre and post is empty
74
self.fail("Fixer run order (%s) is incorrect; %s should be last."\
75
%(", ".join([x.__class__.__module__ for x in (pre+post)]), n))
77
class Test_ne(FixerTestCase):
88
def test_no_spaces(self):
96
def test_chained(self):
104
class Test_has_key(FixerTestCase):
108
b = """x = d.has_key("x") or d.has_key("y")"""
109
a = """x = "x" in d or "y" in d"""
113
b = """x = a.b.c.d.has_key("x") ** 3"""
114
a = """x = ("x" in a.b.c.d) ** 3"""
118
b = """x = a.b.has_key(1 + 2).__repr__()"""
119
a = """x = (1 + 2 in a.b).__repr__()"""
123
b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4"""
124
a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4"""
128
b = """x = a.has_key(f or g)"""
129
a = """x = (f or g) in a"""
133
b = """x = a + b.has_key(c)"""
134
a = """x = a + (c in b)"""
138
b = """x = a.has_key(lambda: 12)"""
139
a = """x = (lambda: 12) in a"""
143
b = """x = a.has_key(a for a in b)"""
144
a = """x = (a for a in b) in a"""
148
b = """if not a.has_key(b): pass"""
149
a = """if b not in a: pass"""
153
b = """if not a.has_key(b).__repr__(): pass"""
154
a = """if not (b in a).__repr__(): pass"""
158
b = """if not a.has_key(b) ** 2: pass"""
159
a = """if not (b in a) ** 2: pass"""
162
class Test_apply(FixerTestCase):
166
b = """x = apply(f, g + h)"""
167
a = """x = f(*g + h)"""
171
b = """y = apply(f, g, h)"""
172
a = """y = f(*g, **h)"""
176
b = """z = apply(fs[0], g or h, h or g)"""
177
a = """z = fs[0](*g or h, **h or g)"""
181
b = """apply(f, (x, y) + t)"""
182
a = """f(*(x, y) + t)"""
186
b = """apply(f, args,)"""
191
b = """apply(f, args, kwds,)"""
192
a = """f(*args, **kwds)"""
195
# Test that complex functions are parenthesized
197
def test_complex_1(self):
198
b = """x = apply(f+g, args)"""
199
a = """x = (f+g)(*args)"""
202
def test_complex_2(self):
203
b = """x = apply(f*g, args)"""
204
a = """x = (f*g)(*args)"""
207
def test_complex_3(self):
208
b = """x = apply(f**g, args)"""
209
a = """x = (f**g)(*args)"""
212
# But dotted names etc. not
214
def test_dotted_name(self):
215
b = """x = apply(f.g, args)"""
216
a = """x = f.g(*args)"""
219
def test_subscript(self):
220
b = """x = apply(f[x], args)"""
221
a = """x = f[x](*args)"""
225
b = """x = apply(f(), args)"""
226
a = """x = f()(*args)"""
230
def test_extreme(self):
231
b = """x = apply(a.b.c.d.e.f, args, kwds)"""
232
a = """x = a.b.c.d.e.f(*args, **kwds)"""
235
# XXX Comments in weird places still get lost
236
def test_weird_comments(self):
243
# These should *not* be touched
245
def test_unchanged_1(self):
249
def test_unchanged_2(self):
253
def test_unchanged_3(self):
257
def test_unchanged_4(self):
258
s = """apply(f, args, kwds, extras)"""
261
def test_unchanged_5(self):
262
s = """apply(f, *args, **kwds)"""
265
def test_unchanged_6(self):
266
s = """apply(f, *args)"""
269
def test_unchanged_7(self):
270
s = """apply(func=f, args=args, kwds=kwds)"""
273
def test_unchanged_8(self):
274
s = """apply(f, args=args, kwds=kwds)"""
277
def test_unchanged_9(self):
278
s = """apply(f, args, kwds=kwds)"""
281
def test_space_1(self):
282
a = """apply( f, args, kwds)"""
283
b = """f(*args, **kwds)"""
286
def test_space_2(self):
287
a = """apply( f ,args,kwds )"""
288
b = """f(*args, **kwds)"""
291
class Test_intern(FixerTestCase):
294
def test_prefix_preservation(self):
295
b = """x = intern( a )"""
296
a = """x = sys.intern( a )"""
299
b = """y = intern("b" # test
301
a = """y = sys.intern("b" # test
305
b = """z = intern(a+b+c.d, )"""
306
a = """z = sys.intern(a+b+c.d, )"""
310
b = """x = intern(a)"""
311
a = """x = sys.intern(a)"""
314
b = """z = intern(a+b+c.d,)"""
315
a = """z = sys.intern(a+b+c.d,)"""
318
b = """intern("y%s" % 5).replace("y", "")"""
319
a = """sys.intern("y%s" % 5).replace("y", "")"""
322
# These should not be refactored
324
def test_unchanged(self):
325
s = """intern(a=1)"""
328
s = """intern(f, g)"""
334
s = """intern(**i)"""
340
class Test_print(FixerTestCase):
343
def test_prefix_preservation(self):
344
b = """print 1, 1+1, 1+1+1"""
345
a = """print(1, 1+1, 1+1+1)"""
348
def test_idempotency(self):
355
def test_idempotency_print_as_function(self):
356
print_stmt = pygram.python_grammar.keywords.pop("print")
358
s = """print(1, 1+1, 1+1+1)"""
367
pygram.python_grammar.keywords["print"] = print_stmt
370
b = """print 1, 1+1, 1+1+1"""
371
a = """print(1, 1+1, 1+1+1)"""
376
a = """print(1, 2)"""
386
b = """print whatever; print"""
387
a = """print(whatever); print()"""
391
b = """print; print whatever;"""
392
a = """print(); print(whatever);"""
394
def test_tuple(self):
395
b = """print (a, b, c)"""
396
a = """print((a, b, c))"""
401
def test_trailing_comma_1(self):
402
b = """print 1, 2, 3,"""
403
a = """print(1, 2, 3, end=' ')"""
406
def test_trailing_comma_2(self):
407
b = """print 1, 2,"""
408
a = """print(1, 2, end=' ')"""
411
def test_trailing_comma_3(self):
413
a = """print(1, end=' ')"""
418
def test_vargs_without_trailing_comma(self):
419
b = """print >>sys.stderr, 1, 2, 3"""
420
a = """print(1, 2, 3, file=sys.stderr)"""
423
def test_with_trailing_comma(self):
424
b = """print >>sys.stderr, 1, 2,"""
425
a = """print(1, 2, end=' ', file=sys.stderr)"""
428
def test_no_trailing_comma(self):
429
b = """print >>sys.stderr, 1+1"""
430
a = """print(1+1, file=sys.stderr)"""
433
def test_spaces_before_file(self):
434
b = """print >> sys.stderr"""
435
a = """print(file=sys.stderr)"""
438
# With from __future__ import print_function
439
def test_with_future_print_function(self):
440
# XXX: These tests won't actually do anything until the parser
441
# is fixed so it won't crash when it sees print(x=y).
442
# When #2412 is fixed, the try/except block can be taken
443
# out and the tests can be run like normal.
444
# MvL: disable entirely for now, so that it doesn't print to stdout
447
s = "from __future__ import print_function\n"\
448
"print('Hai!', end=' ')"
451
b = "print 'Hello, world!'"
452
a = "print('Hello, world!')"
455
s = "from __future__ import *\n"\
456
"print('Hai!', end=' ')"
461
self.assertFalse(True, "#2421 has been fixed -- printing tests "\
462
"need to be updated!")
464
class Test_exec(FixerTestCase):
467
def test_prefix_preservation(self):
468
b = """ exec code in ns1, ns2"""
469
a = """ exec(code, ns1, ns2)"""
472
def test_basic(self):
477
def test_with_globals(self):
478
b = """exec code in ns"""
479
a = """exec(code, ns)"""
482
def test_with_globals_locals(self):
483
b = """exec code in ns1, ns2"""
484
a = """exec(code, ns1, ns2)"""
487
def test_complex_1(self):
488
b = """exec (a.b()) in ns"""
489
a = """exec((a.b()), ns)"""
492
def test_complex_2(self):
493
b = """exec a.b() + c in ns"""
494
a = """exec(a.b() + c, ns)"""
497
# These should not be touched
499
def test_unchanged_1(self):
503
def test_unchanged_2(self):
504
s = """exec (code)"""
507
def test_unchanged_3(self):
508
s = """exec(code, ns)"""
511
def test_unchanged_4(self):
512
s = """exec(code, ns1, ns2)"""
515
class Test_repr(FixerTestCase):
518
def test_prefix_preservation(self):
519
b = """x = `1 + 2`"""
520
a = """x = repr(1 + 2)"""
523
def test_simple_1(self):
524
b = """x = `1 + 2`"""
525
a = """x = repr(1 + 2)"""
528
def test_simple_2(self):
530
a = """y = repr(x)"""
533
def test_complex(self):
534
b = """z = `y`.__repr__()"""
535
a = """z = repr(y).__repr__()"""
538
def test_tuple(self):
539
b = """x = `1, 2, 3`"""
540
a = """x = repr((1, 2, 3))"""
543
def test_nested(self):
544
b = """x = `1 + `2``"""
545
a = """x = repr(1 + repr(2))"""
548
def test_nested_tuples(self):
549
b = """x = `1, 2 + `3, 4``"""
550
a = """x = repr((1, 2 + repr((3, 4))))"""
553
class Test_except(FixerTestCase):
556
def test_prefix_preservation(self):
560
except (RuntimeError, ImportError), e:
565
except (RuntimeError, ImportError) as e:
569
def test_simple(self):
582
def test_simple_no_space_before_target(self):
595
def test_tuple_unpack(self):
600
except Exception, (f, e):
602
except ImportError, e:
609
except Exception as xxx_todo_changeme:
610
(f, e) = xxx_todo_changeme.args
612
except ImportError as e:
616
def test_multi_class(self):
620
except (RuntimeError, ImportError), e:
626
except (RuntimeError, ImportError) as e:
630
def test_list_unpack(self):
634
except Exception, [a, b]:
640
except Exception as xxx_todo_changeme:
641
[a, b] = xxx_todo_changeme.args
645
def test_weird_target_1(self):
649
except Exception, d[5]:
655
except Exception as xxx_todo_changeme:
656
d[5] = xxx_todo_changeme
660
def test_weird_target_2(self):
664
except Exception, a.foo:
670
except Exception as xxx_todo_changeme:
671
a.foo = xxx_todo_changeme
675
def test_weird_target_3(self):
679
except Exception, a().foo:
685
except Exception as xxx_todo_changeme:
686
a().foo = xxx_todo_changeme
690
def test_bare_except(self):
702
except Exception as a:
708
def test_bare_except_and_else_finally(self):
724
except Exception as a:
734
def test_multi_fixed_excepts_before_bare_except(self):
748
except TypeError as b:
750
except Exception as a:
756
# These should not be touched:
758
def test_unchanged_1(self):
766
def test_unchanged_2(self):
774
def test_unchanged_3(self):
778
except (Exception, SystemExit):
782
class Test_raise(FixerTestCase):
785
def test_basic(self):
786
b = """raise Exception, 5"""
787
a = """raise Exception(5)"""
790
def test_prefix_preservation(self):
791
b = """raise Exception,5"""
792
a = """raise Exception(5)"""
795
b = """raise Exception, 5"""
796
a = """raise Exception(5)"""
799
def test_with_comments(self):
800
b = """raise Exception, 5 # foo"""
801
a = """raise Exception(5) # foo"""
804
b = """raise E, (5, 6) % (a, b) # foo"""
805
a = """raise E((5, 6) % (a, b)) # foo"""
809
raise Exception, 5, 6 # foo"""
811
raise Exception(5).with_traceback(6) # foo"""
814
def test_tuple_value(self):
815
b = """raise Exception, (5, 6, 7)"""
816
a = """raise Exception(5, 6, 7)"""
819
def test_tuple_detection(self):
820
b = """raise E, (5, 6) % (a, b)"""
821
a = """raise E((5, 6) % (a, b))"""
824
def test_tuple_exc_1(self):
825
b = """raise (((E1, E2), E3), E4), V"""
826
a = """raise E1(V)"""
829
def test_tuple_exc_2(self):
830
b = """raise (E1, (E2, E3), E4), V"""
831
a = """raise E1(V)"""
834
# These should produce a warning
836
def test_string_exc(self):
837
s = """raise 'foo'"""
838
self.warns_unchanged(s, "Python 3 does not support string exceptions")
840
def test_string_exc_val(self):
841
s = """raise "foo", 5"""
842
self.warns_unchanged(s, "Python 3 does not support string exceptions")
844
def test_string_exc_val_tb(self):
845
s = """raise "foo", 5, 6"""
846
self.warns_unchanged(s, "Python 3 does not support string exceptions")
848
# These should result in traceback-assignment
852
raise Exception, 5, 6"""
854
raise Exception(5).with_traceback(6)"""
860
raise Exception, 5, 6
864
raise Exception(5).with_traceback(6)
870
raise Exception,5,6"""
872
raise Exception(5).with_traceback(6)"""
882
raise Exception(5).with_traceback(6)
888
raise Exception, (5, 6, 7), 6"""
890
raise Exception(5, 6, 7).with_traceback(6)"""
896
raise Exception, (5, 6, 7), 6
900
raise Exception(5, 6, 7).with_traceback(6)
904
class Test_throw(FixerTestCase):
908
b = """g.throw(Exception, 5)"""
909
a = """g.throw(Exception(5))"""
913
b = """g.throw(Exception,5)"""
914
a = """g.throw(Exception(5))"""
918
b = """g.throw(Exception, (5, 6, 7))"""
919
a = """g.throw(Exception(5, 6, 7))"""
923
b = """5 + g.throw(Exception, 5)"""
924
a = """5 + g.throw(Exception(5))"""
927
# These should produce warnings
929
def test_warn_1(self):
930
s = """g.throw("foo")"""
931
self.warns_unchanged(s, "Python 3 does not support string exceptions")
933
def test_warn_2(self):
934
s = """g.throw("foo", 5)"""
935
self.warns_unchanged(s, "Python 3 does not support string exceptions")
937
def test_warn_3(self):
938
s = """g.throw("foo", 5, 6)"""
939
self.warns_unchanged(s, "Python 3 does not support string exceptions")
941
# These should not be touched
943
def test_untouched_1(self):
944
s = """g.throw(Exception)"""
947
def test_untouched_2(self):
948
s = """g.throw(Exception(5, 6))"""
951
def test_untouched_3(self):
952
s = """5 + g.throw(Exception(5, 6))"""
955
# These should result in traceback-assignment
959
g.throw(Exception, 5, 6)"""
961
g.throw(Exception(5).with_traceback(6))"""
967
g.throw(Exception, 5, 6)
971
g.throw(Exception(5).with_traceback(6))
977
g.throw(Exception,5,6)"""
979
g.throw(Exception(5).with_traceback(6))"""
985
g.throw(Exception,5,6)
989
g.throw(Exception(5).with_traceback(6))
995
g.throw(Exception, (5, 6, 7), 6)"""
997
g.throw(Exception(5, 6, 7).with_traceback(6))"""
1000
def test_tb_6(self):
1003
g.throw(Exception, (5, 6, 7), 6)
1007
g.throw(Exception(5, 6, 7).with_traceback(6))
1011
def test_tb_7(self):
1013
a + g.throw(Exception, 5, 6)"""
1015
a + g.throw(Exception(5).with_traceback(6))"""
1018
def test_tb_8(self):
1021
a + g.throw(Exception, 5, 6)
1025
a + g.throw(Exception(5).with_traceback(6))
1029
class Test_long(FixerTestCase):
1033
b = """x = long(x)"""
1034
a = """x = int(x)"""
1038
b = """y = isinstance(x, long)"""
1039
a = """y = isinstance(x, int)"""
1043
b = """z = type(x) in (int, long)"""
1044
a = """z = type(x) in (int, int)"""
1057
def test_unchanged_1(self):
1061
def test_unchanged_2(self):
1065
def test_unchanged_3(self):
1069
def test_prefix_preservation(self):
1070
b = """x = long( x )"""
1071
a = """x = int( x )"""
1074
class Test_dict(FixerTestCase):
1077
def test_prefix_preservation(self):
1078
b = "if d. keys ( ) : pass"
1079
a = "if list(d. keys ( )) : pass"
1082
b = "if d. items ( ) : pass"
1083
a = "if list(d. items ( )) : pass"
1086
b = "if d. iterkeys ( ) : pass"
1087
a = "if iter(d. keys ( )) : pass"
1090
b = "[i for i in d. iterkeys( ) ]"
1091
a = "[i for i in d. keys( ) ]"
1094
def test_trailing_comment(self):
1095
b = "d.keys() # foo"
1096
a = "list(d.keys()) # foo"
1099
b = "d.items() # foo"
1100
a = "list(d.items()) # foo"
1103
b = "d.iterkeys() # foo"
1104
a = "iter(d.keys()) # foo"
1107
b = """[i for i in d.iterkeys() # foo
1109
a = """[i for i in d.keys() # foo
1113
def test_unchanged(self):
1114
for wrapper in fixer_util.consuming_calls:
1115
s = "s = %s(d.keys())" % wrapper
1118
s = "s = %s(d.values())" % wrapper
1121
s = "s = %s(d.items())" % wrapper
1126
a = "list(d.keys())"
1129
b = "a[0].foo().keys()"
1130
a = "list(a[0].foo().keys())"
1135
a = "list(d.items())"
1140
a = "list(d.values())"
1145
a = "iter(d.keys())"
1150
a = "iter(d.items())"
1154
b = "d.itervalues()"
1155
a = "iter(d.values())"
1159
s = "list(d.keys())"
1163
s = "sorted(d.keys())"
1167
b = "iter(d.keys())"
1168
a = "iter(list(d.keys()))"
1173
a = "foo(list(d.keys()))"
1177
b = "for i in d.keys(): print i"
1178
a = "for i in list(d.keys()): print i"
1182
b = "for i in d.iterkeys(): print i"
1183
a = "for i in d.keys(): print i"
1187
b = "[i for i in d.keys()]"
1188
a = "[i for i in list(d.keys())]"
1192
b = "[i for i in d.iterkeys()]"
1193
a = "[i for i in d.keys()]"
1197
b = "(i for i in d.keys())"
1198
a = "(i for i in list(d.keys()))"
1202
b = "(i for i in d.iterkeys())"
1203
a = "(i for i in d.keys())"
1207
b = "iter(d.iterkeys())"
1208
a = "iter(d.keys())"
1212
b = "list(d.iterkeys())"
1213
a = "list(d.keys())"
1217
b = "sorted(d.iterkeys())"
1218
a = "sorted(d.keys())"
1222
b = "foo(d.iterkeys())"
1223
a = "foo(iter(d.keys()))"
1227
b = "print h.iterkeys().next()"
1228
a = "print iter(h.keys()).next()"
1232
b = "print h.keys()[0]"
1233
a = "print list(h.keys())[0]"
1237
b = "print list(h.iterkeys().next())"
1238
a = "print list(iter(h.keys()).next())"
1242
b = "for x in h.keys()[0]: print x"
1243
a = "for x in list(h.keys())[0]: print x"
1246
class Test_xrange(FixerTestCase):
1249
def test_prefix_preservation(self):
1250
b = """x = xrange( 10 )"""
1251
a = """x = range( 10 )"""
1254
b = """x = xrange( 1 , 10 )"""
1255
a = """x = range( 1 , 10 )"""
1258
b = """x = xrange( 0 , 10 , 2 )"""
1259
a = """x = range( 0 , 10 , 2 )"""
1262
def test_single_arg(self):
1263
b = """x = xrange(10)"""
1264
a = """x = range(10)"""
1267
def test_two_args(self):
1268
b = """x = xrange(1, 10)"""
1269
a = """x = range(1, 10)"""
1272
def test_three_args(self):
1273
b = """x = xrange(0, 10, 2)"""
1274
a = """x = range(0, 10, 2)"""
1277
def test_wrap_in_list(self):
1278
b = """x = range(10, 3, 9)"""
1279
a = """x = list(range(10, 3, 9))"""
1282
b = """x = foo(range(10, 3, 9))"""
1283
a = """x = foo(list(range(10, 3, 9)))"""
1286
b = """x = range(10, 3, 9) + [4]"""
1287
a = """x = list(range(10, 3, 9)) + [4]"""
1290
def test_xrange_in_for(self):
1291
b = """for i in xrange(10):\n j=i"""
1292
a = """for i in range(10):\n j=i"""
1295
b = """[i for i in xrange(10)]"""
1296
a = """[i for i in range(10)]"""
1299
def test_range_in_for(self):
1300
self.unchanged("for i in range(10): pass")
1301
self.unchanged("[i for i in range(10)]")
1303
def test_in_contains_test(self):
1304
self.unchanged("x in range(10, 3, 9)")
1306
def test_in_consuming_context(self):
1307
for call in fixer_util.consuming_calls:
1308
self.unchanged("a = %s(range(10))" % call)
1310
class Test_raw_input(FixerTestCase):
1313
def test_prefix_preservation(self):
1314
b = """x = raw_input( )"""
1315
a = """x = input( )"""
1318
b = """x = raw_input( '' )"""
1319
a = """x = input( '' )"""
1323
b = """x = raw_input()"""
1324
a = """x = input()"""
1328
b = """x = raw_input('')"""
1329
a = """x = input('')"""
1333
b = """x = raw_input('prompt')"""
1334
a = """x = input('prompt')"""
1338
b = """x = raw_input(foo(a) + 6)"""
1339
a = """x = input(foo(a) + 6)"""
1343
b = """x = raw_input(invite).split()"""
1344
a = """x = input(invite).split()"""
1348
b = """x = raw_input(invite) . split ()"""
1349
a = """x = input(invite) . split ()"""
1353
b = "x = int(raw_input())"
1354
a = "x = int(input())"
1357
class Test_funcattrs(FixerTestCase):
1360
attrs = ["closure", "doc", "name", "defaults", "code", "globals", "dict"]
1363
for attr in self.attrs:
1364
b = "a.func_%s" % attr
1365
a = "a.__%s__" % attr
1368
b = "self.foo.func_%s.foo_bar" % attr
1369
a = "self.foo.__%s__.foo_bar" % attr
1372
def test_unchanged(self):
1373
for attr in self.attrs:
1374
s = "foo(func_%s + 5)" % attr
1377
s = "f(foo.__%s__)" % attr
1380
s = "f(foo.__%s__.foo)" % attr
1383
class Test_xreadlines(FixerTestCase):
1384
fixer = "xreadlines"
1386
def test_call(self):
1387
b = "for x in f.xreadlines(): pass"
1388
a = "for x in f: pass"
1391
b = "for x in foo().xreadlines(): pass"
1392
a = "for x in foo(): pass"
1395
b = "for x in (5 + foo()).xreadlines(): pass"
1396
a = "for x in (5 + foo()): pass"
1399
def test_attr_ref(self):
1400
b = "foo(f.xreadlines + 5)"
1401
a = "foo(f.__iter__ + 5)"
1404
b = "foo(f().xreadlines + 5)"
1405
a = "foo(f().__iter__ + 5)"
1408
b = "foo((5 + f()).xreadlines + 5)"
1409
a = "foo((5 + f()).__iter__ + 5)"
1412
def test_unchanged(self):
1413
s = "for x in f.xreadlines(5): pass"
1416
s = "for x in f.xreadlines(k=5): pass"
1419
s = "for x in f.xreadlines(*k, **v): pass"
1422
s = "foo(xreadlines)"
1425
class Test_imports(FixerTestCase):
1427
from ..fixes.fix_imports import MAPPING as modules
1429
def test_import_module(self):
1430
for old, new in self.modules.items():
1431
b = "import %s" % old
1432
a = "import %s" % new
1435
b = "import foo, %s, bar" % old
1436
a = "import foo, %s, bar" % new
1439
def test_import_from(self):
1440
for old, new in self.modules.items():
1441
b = "from %s import foo" % old
1442
a = "from %s import foo" % new
1445
b = "from %s import foo, bar" % old
1446
a = "from %s import foo, bar" % new
1449
b = "from %s import (yes, no)" % old
1450
a = "from %s import (yes, no)" % new
1453
def test_import_module_as(self):
1454
for old, new in self.modules.items():
1455
b = "import %s as foo_bar" % old
1456
a = "import %s as foo_bar" % new
1459
b = "import %s as foo_bar" % old
1460
a = "import %s as foo_bar" % new
1463
def test_import_from_as(self):
1464
for old, new in self.modules.items():
1465
b = "from %s import foo as bar" % old
1466
a = "from %s import foo as bar" % new
1469
def test_star(self):
1470
for old, new in self.modules.items():
1471
b = "from %s import *" % old
1472
a = "from %s import *" % new
1475
def test_import_module_usage(self):
1476
for old, new in self.modules.items():
1507
""" % (old, old, old)
1511
""" % (new, new, new)
1526
class Test_imports2(Test_imports):
1528
from ..fixes.fix_imports2 import MAPPING as modules
1531
class Test_imports_fixer_order(Test_imports):
1536
Test_imports.setUp(self, ['imports', 'imports2'])
1537
from ..fixes.fix_imports2 import MAPPING as mapping2
1538
self.modules = mapping2.copy()
1539
from ..fixes.fix_imports import MAPPING as mapping1
1540
for key in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'):
1541
self.modules[key] = mapping1[key]
1544
class Test_urllib(FixerTestCase):
1546
from ..fixes.fix_urllib import MAPPING as modules
1548
def test_import_module(self):
1549
for old, changes in self.modules.items():
1550
b = "import %s" % old
1551
a = "import %s" % ", ".join(map(itemgetter(0), changes))
1554
def test_import_from(self):
1555
for old, changes in self.modules.items():
1557
for new, members in changes:
1558
for member in members:
1559
all_members.append(member)
1560
b = "from %s import %s" % (old, member)
1561
a = "from %s import %s" % (new, member)
1564
s = "from foo import %s" % member
1567
b = "from %s import %s" % (old, ", ".join(members))
1568
a = "from %s import %s" % (new, ", ".join(members))
1571
s = "from foo import %s" % ", ".join(members)
1574
# test the breaking of a module into multiple replacements
1575
b = "from %s import %s" % (old, ", ".join(all_members))
1576
a = "\n".join(["from %s import %s" % (new, ", ".join(members))
1577
for (new, members) in changes])
1580
def test_import_module_as(self):
1581
for old in self.modules:
1582
s = "import %s as foo" % old
1583
self.warns_unchanged(s, "This module is now multiple modules")
1585
def test_import_from_as(self):
1586
for old, changes in self.modules.items():
1587
for new, members in changes:
1588
for member in members:
1589
b = "from %s import %s as foo_bar" % (old, member)
1590
a = "from %s import %s as foo_bar" % (new, member)
1593
def test_star(self):
1594
for old in self.modules:
1595
s = "from %s import *" % old
1596
self.warns_unchanged(s, "Cannot handle star imports")
1598
def test_import_module_usage(self):
1599
for old, changes in self.modules.items():
1600
for new, members in changes:
1601
for member in members:
1605
""" % (old, old, member)
1609
""" % (", ".join([n for (n, mems)
1610
in self.modules[old]]),
1615
class Test_input(FixerTestCase):
1618
def test_prefix_preservation(self):
1619
b = """x = input( )"""
1620
a = """x = eval(input( ))"""
1623
b = """x = input( '' )"""
1624
a = """x = eval(input( '' ))"""
1627
def test_trailing_comment(self):
1628
b = """x = input() # foo"""
1629
a = """x = eval(input()) # foo"""
1632
def test_idempotency(self):
1633
s = """x = eval(input())"""
1636
s = """x = eval(input(''))"""
1639
s = """x = eval(input(foo(5) + 9))"""
1643
b = """x = input()"""
1644
a = """x = eval(input())"""
1648
b = """x = input('')"""
1649
a = """x = eval(input(''))"""
1653
b = """x = input('prompt')"""
1654
a = """x = eval(input('prompt'))"""
1658
b = """x = input(foo(5) + 9)"""
1659
a = """x = eval(input(foo(5) + 9))"""
1662
class Test_tuple_params(FixerTestCase):
1663
fixer = "tuple_params"
1665
def test_unchanged_1(self):
1666
s = """def foo(): pass"""
1669
def test_unchanged_2(self):
1670
s = """def foo(a, b, c): pass"""
1673
def test_unchanged_3(self):
1674
s = """def foo(a=3, b=4, c=5): pass"""
1679
def foo(((a, b), c)):
1683
def foo(xxx_todo_changeme):
1684
((a, b), c) = xxx_todo_changeme
1690
def foo(((a, b), c), d):
1694
def foo(xxx_todo_changeme, d):
1695
((a, b), c) = xxx_todo_changeme
1701
def foo(((a, b), c), d) -> e:
1705
def foo(xxx_todo_changeme, d) -> e:
1706
((a, b), c) = xxx_todo_changeme
1710
def test_semicolon(self):
1712
def foo(((a, b), c)): x = 5; y = 7"""
1715
def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme; x = 5; y = 7"""
1718
def test_keywords(self):
1720
def foo(((a, b), c), d, e=5) -> z:
1724
def foo(xxx_todo_changeme, d, e=5) -> z:
1725
((a, b), c) = xxx_todo_changeme
1729
def test_varargs(self):
1731
def foo(((a, b), c), d, *vargs, **kwargs) -> z:
1735
def foo(xxx_todo_changeme, d, *vargs, **kwargs) -> z:
1736
((a, b), c) = xxx_todo_changeme
1740
def test_multi_1(self):
1742
def foo(((a, b), c), (d, e, f)) -> z:
1746
def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
1747
((a, b), c) = xxx_todo_changeme
1748
(d, e, f) = xxx_todo_changeme1
1752
def test_multi_2(self):
1754
def foo(x, ((a, b), c), d, (e, f, g), y) -> z:
1758
def foo(x, xxx_todo_changeme, d, xxx_todo_changeme1, y) -> z:
1759
((a, b), c) = xxx_todo_changeme
1760
(e, f, g) = xxx_todo_changeme1
1764
def test_docstring(self):
1766
def foo(((a, b), c), (d, e, f)) -> z:
1771
def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
1773
((a, b), c) = xxx_todo_changeme
1774
(d, e, f) = xxx_todo_changeme1
1778
def test_lambda_no_change(self):
1779
s = """lambda x: x + 5"""
1782
def test_lambda_parens_single_arg(self):
1783
b = """lambda (x): x + 5"""
1784
a = """lambda x: x + 5"""
1787
b = """lambda(x): x + 5"""
1788
a = """lambda x: x + 5"""
1791
b = """lambda ((((x)))): x + 5"""
1792
a = """lambda x: x + 5"""
1795
b = """lambda((((x)))): x + 5"""
1796
a = """lambda x: x + 5"""
1799
def test_lambda_simple(self):
1800
b = """lambda (x, y): x + f(y)"""
1801
a = """lambda x_y: x_y[0] + f(x_y[1])"""
1804
b = """lambda(x, y): x + f(y)"""
1805
a = """lambda x_y: x_y[0] + f(x_y[1])"""
1808
b = """lambda (((x, y))): x + f(y)"""
1809
a = """lambda x_y: x_y[0] + f(x_y[1])"""
1812
b = """lambda(((x, y))): x + f(y)"""
1813
a = """lambda x_y: x_y[0] + f(x_y[1])"""
1816
def test_lambda_one_tuple(self):
1817
b = """lambda (x,): x + f(x)"""
1818
a = """lambda x1: x1[0] + f(x1[0])"""
1821
b = """lambda (((x,))): x + f(x)"""
1822
a = """lambda x1: x1[0] + f(x1[0])"""
1825
def test_lambda_simple_multi_use(self):
1826
b = """lambda (x, y): x + x + f(x) + x"""
1827
a = """lambda x_y: x_y[0] + x_y[0] + f(x_y[0]) + x_y[0]"""
1830
def test_lambda_simple_reverse(self):
1831
b = """lambda (x, y): y + x"""
1832
a = """lambda x_y: x_y[1] + x_y[0]"""
1835
def test_lambda_nested(self):
1836
b = """lambda (x, (y, z)): x + y + z"""
1837
a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
1840
b = """lambda (((x, (y, z)))): x + y + z"""
1841
a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
1844
def test_lambda_nested_multi_use(self):
1845
b = """lambda (x, (y, z)): x + y + f(y)"""
1846
a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + f(x_y_z[1][0])"""
1849
class Test_methodattrs(FixerTestCase):
1850
fixer = "methodattrs"
1852
attrs = ["func", "self", "class"]
1855
for attr in self.attrs:
1856
b = "a.im_%s" % attr
1858
a = "a.__self__.__class__"
1860
a = "a.__%s__" % attr
1863
b = "self.foo.im_%s.foo_bar" % attr
1865
a = "self.foo.__self__.__class__.foo_bar"
1867
a = "self.foo.__%s__.foo_bar" % attr
1870
def test_unchanged(self):
1871
for attr in self.attrs:
1872
s = "foo(im_%s + 5)" % attr
1875
s = "f(foo.__%s__)" % attr
1878
s = "f(foo.__%s__.foo)" % attr
1881
class Test_next(FixerTestCase):
1890
b = """a.b.c.d.next()"""
1891
a = """next(a.b.c.d)"""
1895
b = """(a + b).next()"""
1896
a = """next((a + b))"""
1900
b = """a().next()"""
1905
b = """a().next() + b"""
1906
a = """next(a()) + b"""
1910
b = """c( a().next() + b)"""
1911
a = """c( next(a()) + b)"""
1914
def test_prefix_preservation_1(self):
1927
def test_prefix_preservation_2(self):
1942
def test_prefix_preservation_3(self):
1955
self.check(b, a, ignore_warnings=True)
1957
def test_prefix_preservation_4(self):
1972
self.check(b, a, ignore_warnings=True)
1974
def test_prefix_preservation_5(self):
1987
self.check(b, a, ignore_warnings=True)
1989
def test_prefix_preservation_6(self):
2002
def test_method_1(self):
2015
def test_method_2(self):
2028
def test_method_3(self):
2041
def test_method_4(self):
2044
def __init__(self, foo):
2055
def __init__(self, foo):
2066
def test_method_unchanged(self):
2069
def next(self, a, b):
2074
def test_shadowing_assign_simple(self):
2079
def next(self, a, b):
2082
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2084
def test_shadowing_assign_tuple_1(self):
2089
def next(self, a, b):
2092
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2094
def test_shadowing_assign_tuple_2(self):
2096
(a, (b, (next, c)), a) = foo
2099
def next(self, a, b):
2102
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2104
def test_shadowing_assign_list_1(self):
2109
def next(self, a, b):
2112
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2114
def test_shadowing_assign_list_2(self):
2116
[a, [b, [next, c]], a] = foo
2119
def next(self, a, b):
2122
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2124
def test_builtin_assign(self):
2127
__builtin__.next = foo
2130
def next(self, a, b):
2133
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2135
def test_builtin_assign_in_tuple(self):
2138
(a, __builtin__.next) = foo
2141
def next(self, a, b):
2144
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2146
def test_builtin_assign_in_list(self):
2149
[a, __builtin__.next] = foo
2152
def next(self, a, b):
2155
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2157
def test_assign_to_next(self):
2163
def next(self, a, b):
2168
def test_assign_to_next_in_tuple(self):
2174
def next(self, a, b):
2179
def test_assign_to_next_in_list(self):
2185
def next(self, a, b):
2190
def test_shadowing_import_1(self):
2192
import foo.bar as next
2195
def next(self, a, b):
2198
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2200
def test_shadowing_import_2(self):
2202
import bar, bar.foo as next
2205
def next(self, a, b):
2208
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2210
def test_shadowing_import_3(self):
2212
import bar, bar.foo as next, baz
2215
def next(self, a, b):
2218
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2220
def test_shadowing_import_from_1(self):
2225
def next(self, a, b):
2228
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2230
def test_shadowing_import_from_2(self):
2232
from x.a import next
2235
def next(self, a, b):
2238
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2240
def test_shadowing_import_from_3(self):
2242
from x import a, next, b
2245
def next(self, a, b):
2248
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2250
def test_shadowing_import_from_4(self):
2252
from x.a import a, next, b
2255
def next(self, a, b):
2258
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2260
def test_shadowing_funcdef_1(self):
2266
def next(self, a, b):
2269
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2271
def test_shadowing_funcdef_2(self):
2292
self.warns(b, a, "Calls to builtin next() possibly shadowed")
2294
def test_shadowing_global_1(self):
2300
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2302
def test_shadowing_global_2(self):
2308
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2310
def test_shadowing_for_simple(self):
2318
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2320
def test_shadowing_for_tuple_1(self):
2322
for next, b in it():
2328
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2330
def test_shadowing_for_tuple_2(self):
2332
for a, (next, c), b in it():
2338
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2340
def test_noncall_access_1(self):
2341
b = """gnext = g.next"""
2342
a = """gnext = g.__next__"""
2345
def test_noncall_access_2(self):
2346
b = """f(g.next + 5)"""
2347
a = """f(g.__next__ + 5)"""
2350
def test_noncall_access_3(self):
2351
b = """f(g().next + 5)"""
2352
a = """f(g().__next__ + 5)"""
2355
class Test_nonzero(FixerTestCase):
2361
def __nonzero__(self):
2374
def __nonzero__(self):
2384
def test_unchanged_1(self):
2392
def test_unchanged_2(self):
2395
def __nonzero__(self, a):
2400
def test_unchanged_func(self):
2402
def __nonzero__(self):
2407
class Test_numliterals(FixerTestCase):
2408
fixer = "numliterals"
2410
def test_octal_1(self):
2415
def test_long_int_1(self):
2420
def test_long_int_2(self):
2425
def test_long_hex(self):
2430
def test_comments_and_spacing(self):
2435
b = """b = 0755 # spam"""
2436
a = """b = 0o755 # spam"""
2439
def test_unchanged_int(self):
2443
def test_unchanged_float(self):
2447
def test_unchanged_octal(self):
2451
def test_unchanged_hex(self):
2455
def test_unchanged_exp(self):
2459
def test_unchanged_complex_int(self):
2463
def test_unchanged_complex_float(self):
2464
s = """5.4 + 4.9j"""
2467
def test_unchanged_complex_bare(self):
2473
class Test_renames(FixerTestCase):
2476
modules = {"sys": ("maxint", "maxsize"),
2479
def test_import_from(self):
2480
for mod, (old, new) in self.modules.items():
2481
b = "from %s import %s" % (mod, old)
2482
a = "from %s import %s" % (mod, new)
2485
s = "from foo import %s" % old
2488
def test_import_from_as(self):
2489
for mod, (old, new) in self.modules.items():
2490
b = "from %s import %s as foo_bar" % (mod, old)
2491
a = "from %s import %s as foo_bar" % (mod, new)
2494
def test_import_module_usage(self):
2495
for mod, (old, new) in self.modules.items():
2499
""" % (mod, mod, mod, old)
2503
""" % (mod, mod, mod, new)
2506
def XXX_test_from_import_usage(self):
2507
# not implemented yet
2508
for mod, (old, new) in self.modules.items():
2512
""" % (mod, old, mod, old)
2516
""" % (mod, new, mod, new)
2519
class Test_unicode(FixerTestCase):
2522
def test_unicode_call(self):
2523
b = """unicode(x, y, z)"""
2524
a = """str(x, y, z)"""
2527
def test_unicode_literal_1(self):
2532
def test_unicode_literal_2(self):
2537
def test_unicode_literal_3(self):
2542
class Test_callable(FixerTestCase):
2545
def test_prefix_preservation(self):
2546
b = """callable( x)"""
2547
a = """hasattr( x, '__call__')"""
2550
b = """if callable(x): pass"""
2551
a = """if hasattr(x, '__call__'): pass"""
2554
def test_callable_call(self):
2555
b = """callable(x)"""
2556
a = """hasattr(x, '__call__')"""
2559
def test_callable_should_not_change(self):
2560
a = """callable(*x)"""
2563
a = """callable(x, y)"""
2566
a = """callable(x, kw=y)"""
2569
a = """callable()"""
2572
class Test_filter(FixerTestCase):
2575
def test_prefix_preservation(self):
2576
b = """x = filter( foo, 'abc' )"""
2577
a = """x = list(filter( foo, 'abc' ))"""
2580
b = """x = filter( None , 'abc' )"""
2581
a = """x = [_f for _f in 'abc' if _f]"""
2584
def test_filter_basic(self):
2585
b = """x = filter(None, 'abc')"""
2586
a = """x = [_f for _f in 'abc' if _f]"""
2589
b = """x = len(filter(f, 'abc'))"""
2590
a = """x = len(list(filter(f, 'abc')))"""
2593
b = """x = filter(lambda x: x%2 == 0, range(10))"""
2594
a = """x = [x for x in range(10) if x%2 == 0]"""
2597
# Note the parens around x
2598
b = """x = filter(lambda (x): x%2 == 0, range(10))"""
2599
a = """x = [x for x in range(10) if x%2 == 0]"""
2602
# XXX This (rare) case is not supported
2603
## b = """x = filter(f, 'abc')[0]"""
2604
## a = """x = list(filter(f, 'abc'))[0]"""
2607
def test_filter_nochange(self):
2608
a = """b.join(filter(f, 'abc'))"""
2610
a = """(a + foo(5)).join(filter(f, 'abc'))"""
2612
a = """iter(filter(f, 'abc'))"""
2614
a = """list(filter(f, 'abc'))"""
2616
a = """list(filter(f, 'abc'))[0]"""
2618
a = """set(filter(f, 'abc'))"""
2620
a = """set(filter(f, 'abc')).pop()"""
2622
a = """tuple(filter(f, 'abc'))"""
2624
a = """any(filter(f, 'abc'))"""
2626
a = """all(filter(f, 'abc'))"""
2628
a = """sum(filter(f, 'abc'))"""
2630
a = """sorted(filter(f, 'abc'))"""
2632
a = """sorted(filter(f, 'abc'), key=blah)"""
2634
a = """sorted(filter(f, 'abc'), key=blah)[0]"""
2636
a = """for i in filter(f, 'abc'): pass"""
2638
a = """[x for x in filter(f, 'abc')]"""
2640
a = """(x for x in filter(f, 'abc'))"""
2643
def test_future_builtins(self):
2644
a = "from future_builtins import spam, filter; filter(f, 'ham')"
2647
b = """from future_builtins import spam; x = filter(f, 'abc')"""
2648
a = """from future_builtins import spam; x = list(filter(f, 'abc'))"""
2651
a = "from future_builtins import *; filter(f, 'ham')"
2654
class Test_map(FixerTestCase):
2657
def check(self, b, a):
2658
self.unchanged("from future_builtins import map; " + b, a)
2659
FixerTestCase.check(self, b, a)
2661
def test_prefix_preservation(self):
2662
b = """x = map( f, 'abc' )"""
2663
a = """x = list(map( f, 'abc' ))"""
2666
def test_trailing_comment(self):
2667
b = """x = map(f, 'abc') # foo"""
2668
a = """x = list(map(f, 'abc')) # foo"""
2671
def test_map_basic(self):
2672
b = """x = map(f, 'abc')"""
2673
a = """x = list(map(f, 'abc'))"""
2676
b = """x = len(map(f, 'abc', 'def'))"""
2677
a = """x = len(list(map(f, 'abc', 'def')))"""
2680
b = """x = map(None, 'abc')"""
2681
a = """x = list('abc')"""
2684
b = """x = map(None, 'abc', 'def')"""
2685
a = """x = list(map(None, 'abc', 'def'))"""
2688
b = """x = map(lambda x: x+1, range(4))"""
2689
a = """x = [x+1 for x in range(4)]"""
2692
# Note the parens around x
2693
b = """x = map(lambda (x): x+1, range(4))"""
2694
a = """x = [x+1 for x in range(4)]"""
2707
self.warns(b, a, "You should use a for loop here")
2709
# XXX This (rare) case is not supported
2710
## b = """x = map(f, 'abc')[0]"""
2711
## a = """x = list(map(f, 'abc'))[0]"""
2714
def test_map_nochange(self):
2715
a = """b.join(map(f, 'abc'))"""
2717
a = """(a + foo(5)).join(map(f, 'abc'))"""
2719
a = """iter(map(f, 'abc'))"""
2721
a = """list(map(f, 'abc'))"""
2723
a = """list(map(f, 'abc'))[0]"""
2725
a = """set(map(f, 'abc'))"""
2727
a = """set(map(f, 'abc')).pop()"""
2729
a = """tuple(map(f, 'abc'))"""
2731
a = """any(map(f, 'abc'))"""
2733
a = """all(map(f, 'abc'))"""
2735
a = """sum(map(f, 'abc'))"""
2737
a = """sorted(map(f, 'abc'))"""
2739
a = """sorted(map(f, 'abc'), key=blah)"""
2741
a = """sorted(map(f, 'abc'), key=blah)[0]"""
2743
a = """for i in map(f, 'abc'): pass"""
2745
a = """[x for x in map(f, 'abc')]"""
2747
a = """(x for x in map(f, 'abc'))"""
2750
def test_future_builtins(self):
2751
a = "from future_builtins import spam, map, eggs; map(f, 'ham')"
2754
b = """from future_builtins import spam, eggs; x = map(f, 'abc')"""
2755
a = """from future_builtins import spam, eggs; x = list(map(f, 'abc'))"""
2758
a = "from future_builtins import *; map(f, 'ham')"
2761
class Test_zip(FixerTestCase):
2764
def check(self, b, a):
2765
self.unchanged("from future_builtins import zip; " + b, a)
2766
FixerTestCase.check(self, b, a)
2768
def test_zip_basic(self):
2769
b = """x = zip(a, b, c)"""
2770
a = """x = list(zip(a, b, c))"""
2773
b = """x = len(zip(a, b))"""
2774
a = """x = len(list(zip(a, b)))"""
2777
def test_zip_nochange(self):
2778
a = """b.join(zip(a, b))"""
2780
a = """(a + foo(5)).join(zip(a, b))"""
2782
a = """iter(zip(a, b))"""
2784
a = """list(zip(a, b))"""
2786
a = """list(zip(a, b))[0]"""
2788
a = """set(zip(a, b))"""
2790
a = """set(zip(a, b)).pop()"""
2792
a = """tuple(zip(a, b))"""
2794
a = """any(zip(a, b))"""
2796
a = """all(zip(a, b))"""
2798
a = """sum(zip(a, b))"""
2800
a = """sorted(zip(a, b))"""
2802
a = """sorted(zip(a, b), key=blah)"""
2804
a = """sorted(zip(a, b), key=blah)[0]"""
2806
a = """for i in zip(a, b): pass"""
2808
a = """[x for x in zip(a, b)]"""
2810
a = """(x for x in zip(a, b))"""
2813
def test_future_builtins(self):
2814
a = "from future_builtins import spam, zip, eggs; zip(a, b)"
2817
b = """from future_builtins import spam, eggs; x = zip(a, b)"""
2818
a = """from future_builtins import spam, eggs; x = list(zip(a, b))"""
2821
a = "from future_builtins import *; zip(a, b)"
2824
class Test_standarderror(FixerTestCase):
2825
fixer = "standarderror"
2828
b = """x = StandardError()"""
2829
a = """x = Exception()"""
2832
b = """x = StandardError(a, b, c)"""
2833
a = """x = Exception(a, b, c)"""
2836
b = """f(2 + StandardError(a, b, c))"""
2837
a = """f(2 + Exception(a, b, c))"""
2840
class Test_types(FixerTestCase):
2843
def test_basic_types_convert(self):
2844
b = """types.StringType"""
2848
b = """types.DictType"""
2852
b = """types . IntType"""
2856
b = """types.ListType"""
2860
b = """types.LongType"""
2864
b = """types.NoneType"""
2865
a = """type(None)"""
2868
class Test_idioms(FixerTestCase):
2871
def test_while(self):
2872
b = """while 1: foo()"""
2873
a = """while True: foo()"""
2876
b = """while 1: foo()"""
2877
a = """while True: foo()"""
2890
def test_while_unchanged(self):
2891
s = """while 11: foo()"""
2894
s = """while 0: foo()"""
2897
s = """while foo(): foo()"""
2900
s = """while []: foo()"""
2903
def test_eq_simple(self):
2904
b = """type(x) == T"""
2905
a = """isinstance(x, T)"""
2908
b = """if type(x) == T: pass"""
2909
a = """if isinstance(x, T): pass"""
2912
def test_eq_reverse(self):
2913
b = """T == type(x)"""
2914
a = """isinstance(x, T)"""
2917
b = """if T == type(x): pass"""
2918
a = """if isinstance(x, T): pass"""
2921
def test_eq_expression(self):
2922
b = """type(x+y) == d.get('T')"""
2923
a = """isinstance(x+y, d.get('T'))"""
2926
b = """type( x + y) == d.get('T')"""
2927
a = """isinstance(x + y, d.get('T'))"""
2930
def test_is_simple(self):
2931
b = """type(x) is T"""
2932
a = """isinstance(x, T)"""
2935
b = """if type(x) is T: pass"""
2936
a = """if isinstance(x, T): pass"""
2939
def test_is_reverse(self):
2940
b = """T is type(x)"""
2941
a = """isinstance(x, T)"""
2944
b = """if T is type(x): pass"""
2945
a = """if isinstance(x, T): pass"""
2948
def test_is_expression(self):
2949
b = """type(x+y) is d.get('T')"""
2950
a = """isinstance(x+y, d.get('T'))"""
2953
b = """type( x + y) is d.get('T')"""
2954
a = """isinstance(x + y, d.get('T'))"""
2957
def test_is_not_simple(self):
2958
b = """type(x) is not T"""
2959
a = """not isinstance(x, T)"""
2962
b = """if type(x) is not T: pass"""
2963
a = """if not isinstance(x, T): pass"""
2966
def test_is_not_reverse(self):
2967
b = """T is not type(x)"""
2968
a = """not isinstance(x, T)"""
2971
b = """if T is not type(x): pass"""
2972
a = """if not isinstance(x, T): pass"""
2975
def test_is_not_expression(self):
2976
b = """type(x+y) is not d.get('T')"""
2977
a = """not isinstance(x+y, d.get('T'))"""
2980
b = """type( x + y) is not d.get('T')"""
2981
a = """not isinstance(x + y, d.get('T'))"""
2984
def test_ne_simple(self):
2985
b = """type(x) != T"""
2986
a = """not isinstance(x, T)"""
2989
b = """if type(x) != T: pass"""
2990
a = """if not isinstance(x, T): pass"""
2993
def test_ne_reverse(self):
2994
b = """T != type(x)"""
2995
a = """not isinstance(x, T)"""
2998
b = """if T != type(x): pass"""
2999
a = """if not isinstance(x, T): pass"""
3002
def test_ne_expression(self):
3003
b = """type(x+y) != d.get('T')"""
3004
a = """not isinstance(x+y, d.get('T'))"""
3007
b = """type( x + y) != d.get('T')"""
3008
a = """not isinstance(x + y, d.get('T'))"""
3011
def test_type_unchanged(self):
3012
a = """type(x).__name__"""
3015
def test_sort_list_call(self):
3028
v = list(foo(b) + d)
3033
v = sorted(foo(b) + d)
3075
def test_sort_simple_expr(self):
3104
v = sorted(b.keys())
3115
v = sorted(foo(b) + d)
3157
def test_sort_unchanged(self):
3172
class Test_basestring(FixerTestCase):
3173
fixer = "basestring"
3175
def test_basestring(self):
3176
b = """isinstance(x, basestring)"""
3177
a = """isinstance(x, str)"""
3180
class Test_buffer(FixerTestCase):
3183
def test_buffer(self):
3184
b = """x = buffer(y)"""
3185
a = """x = memoryview(y)"""
3188
class Test_future(FixerTestCase):
3191
def test_future(self):
3192
b = """from __future__ import braces"""
3196
b = """# comment\nfrom __future__ import braces"""
3197
a = """# comment\n"""
3200
b = """from __future__ import braces\n# comment"""
3201
a = """\n# comment"""
3204
def test_run_order(self):
3205
self.assert_runs_after('print')
3207
class Test_itertools(FixerTestCase):
3210
def checkall(self, before, after):
3211
# Because we need to check with and without the itertools prefix
3212
# and on each of the three functions, these loops make it all
3214
for i in ('itertools.', ''):
3215
for f in ('map', 'filter', 'zip'):
3216
b = before %(i+'i'+f)
3221
# A simple example -- test_1 covers exactly the same thing,
3222
# but it's not quite as clear.
3223
b = "itertools.izip(a, b)"
3233
b = """itertools.ifilterfalse(a, b)"""
3234
a = """itertools.filterfalse(a, b)"""
3238
b = """ifilterfalse(a, b)"""
3239
a = """filterfalse(a, b)"""
3242
def test_space_1(self):
3247
def test_space_2(self):
3248
b = """ itertools.ifilterfalse(a, b)"""
3249
a = """ itertools.filterfalse(a, b)"""
3252
def test_run_order(self):
3253
self.assert_runs_after('map', 'zip', 'filter')
3255
class Test_itertools_imports(FixerTestCase):
3256
fixer = 'itertools_imports'
3258
def test_reduced(self):
3259
b = "from itertools import imap, izip, foo"
3260
a = "from itertools import foo"
3263
b = "from itertools import bar, imap, izip, foo"
3264
a = "from itertools import bar, foo"
3267
def test_comments(self):
3268
b = "#foo\nfrom itertools import imap, izip"
3272
def test_none(self):
3273
b = "from itertools import imap, izip"
3277
b = "from itertools import izip"
3281
def test_import_as(self):
3282
b = "from itertools import izip, bar as bang, imap"
3283
a = "from itertools import bar as bang"
3286
s = "from itertools import bar as bang"
3289
def test_ifilter(self):
3290
b = "from itertools import ifilterfalse"
3291
a = "from itertools import filterfalse"
3294
b = "from itertools import imap, ifilterfalse, foo"
3295
a = "from itertools import filterfalse, foo"
3298
b = "from itertools import bar, ifilterfalse, foo"
3299
a = "from itertools import bar, filterfalse, foo"
3303
def test_unchanged(self):
3304
s = "from itertools import foo"
3307
class Test_import(FixerTestCase):
3311
FixerTestCase.setUp(self)
3312
# Need to replace fix_import's exists method
3313
# so we can check that it's doing the right thing
3314
self.files_checked = []
3315
self.present_files = set()
3316
self.always_exists = True
3317
def fake_exists(name):
3318
self.files_checked.append(name)
3319
return self.always_exists or (name in self.present_files)
3321
from ..fixes import fix_import
3322
fix_import.exists = fake_exists
3325
from lib2to3.fixes import fix_import
3326
fix_import.exists = os.path.exists
3328
def check_both(self, b, a):
3329
self.always_exists = True
3330
FixerTestCase.check(self, b, a)
3331
self.always_exists = False
3332
FixerTestCase.unchanged(self, b)
3334
def test_files_checked(self):
3336
# Takes a unix path and returns a path with correct separators
3337
return os.path.pathsep.join(path.split("/"))
3339
self.always_exists = False
3340
self.present_files = set(['__init__.py'])
3341
expected_extensions = ('.py', os.path.pathsep, '.pyc', '.so',
3343
names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))
3345
for name in names_to_test:
3346
self.files_checked = []
3347
self.filename = name
3348
self.unchanged("import jam")
3350
if os.path.dirname(name):
3351
name = os.path.dirname(name) + '/jam'
3354
expected_checks = set(name + ext for ext in expected_extensions)
3355
expected_checks.add("__init__.py")
3357
self.assertEqual(set(self.files_checked), expected_checks)
3359
def test_not_in_package(self):
3361
self.always_exists = False
3362
self.present_files = set(["bar.py"])
3365
def test_in_package(self):
3367
a = "from . import bar"
3368
self.always_exists = False
3369
self.present_files = set(["__init__.py", "bar.py"])
3372
def test_comments_and_indent(self):
3373
b = "import bar # Foo"
3374
a = "from . import bar # Foo"
3377
def test_from(self):
3378
b = "from foo import bar, baz"
3379
a = "from .foo import bar, baz"
3380
self.check_both(b, a)
3382
b = "from foo import bar"
3383
a = "from .foo import bar"
3384
self.check_both(b, a)
3386
b = "from foo import (bar, baz)"
3387
a = "from .foo import (bar, baz)"
3388
self.check_both(b, a)
3390
def test_dotted_from(self):
3391
b = "from green.eggs import ham"
3392
a = "from .green.eggs import ham"
3393
self.check_both(b, a)
3395
def test_from_as(self):
3396
b = "from green.eggs import ham as spam"
3397
a = "from .green.eggs import ham as spam"
3398
self.check_both(b, a)
3400
def test_import(self):
3402
a = "from . import foo"
3403
self.check_both(b, a)
3405
b = "import foo, bar"
3406
a = "from . import foo, bar"
3407
self.check_both(b, a)
3409
def test_dotted_import(self):
3410
b = "import foo.bar"
3411
a = "from . import foo.bar"
3412
self.check_both(b, a)
3414
def test_dotted_import_as(self):
3415
b = "import foo.bar as bang"
3416
a = "from . import foo.bar as bang"
3417
self.check_both(b, a)
3419
def test_prefix(self):
3426
from . import foo.bar
3428
self.check_both(b, a)
3431
class Test_set_literal(FixerTestCase):
3433
fixer = "set_literal"
3435
def test_basic(self):
3436
b = """set([1, 2, 3])"""
3440
b = """set((1, 2, 3))"""
3451
b = """set((a, b))"""
3455
b = """set([a, b])"""
3458
b = """set((a*234, f(args=23)))"""
3459
a = """{a*234, f(args=23)}"""
3462
b = """set([a*23, f(23)])"""
3463
a = """{a*23, f(23)}"""
3466
b = """set([a-234**23])"""
3467
a = """{a-234**23}"""
3470
def test_listcomps(self):
3471
b = """set([x for x in y])"""
3472
a = """{x for x in y}"""
3475
b = """set([x for x in y if x == m])"""
3476
a = """{x for x in y if x == m}"""
3479
b = """set([x for x in y for a in b])"""
3480
a = """{x for x in y for a in b}"""
3483
b = """set([f(x) - 23 for x in y])"""
3484
a = """{f(x) - 23 for x in y}"""
3487
def test_whitespace(self):
3488
b = """set( [1, 2])"""
3492
b = """set([1 , 2])"""
3496
b = """set([ 1 ])"""
3500
b = """set( [1] )"""
3504
b = """set([ 1, 2 ])"""
3508
b = """set([x for x in y ])"""
3509
a = """{x for x in y }"""
3519
def test_comments(self):
3520
b = """set((1, 2)) # Hi"""
3521
a = """{1, 2} # Hi"""
3524
# This isn't optimal behavior, but the fixer is optional.
3537
def test_unchanged(self):
3544
s = """set(a, b, c)"""
3547
# Don't transform generators because they might have to be lazy.
3548
s = """set(x for x in y)"""
3551
s = """set(x for x in y if z)"""
3554
s = """set(a*823-23**2 + f(23))"""
3558
class Test_sys_exc(FixerTestCase):
3563
a = "sys.exc_info()[0]"
3568
a = "sys.exc_info()[1]"
3572
b = "sys.exc_traceback"
3573
a = "sys.exc_info()[2]"
3577
b = "sys.exc_type # Foo"
3578
a = "sys.exc_info()[0] # Foo"
3583
a = "sys. exc_info()[0]"
3588
a = "sys .exc_info()[0]"
3592
class Test_paren(FixerTestCase):
3596
b = """[i for i in 1, 2 ]"""
3597
a = """[i for i in (1, 2) ]"""
3601
b = """[i for i in 1, 2, ]"""
3602
a = """[i for i in (1, 2,) ]"""
3606
b = """[i for i in 1, 2 ]"""
3607
a = """[i for i in (1, 2) ]"""
3611
b = """[i for i in 1, 2 if i]"""
3612
a = """[i for i in (1, 2) if i]"""
3616
b = """[i for i in 1, 2 ]"""
3617
a = """[i for i in (1, 2) ]"""
3621
b = """(i for i in 1, 2)"""
3622
a = """(i for i in (1, 2))"""
3626
b = """(i for i in 1 ,2 if i)"""
3627
a = """(i for i in (1 ,2) if i)"""
3630
def test_unchanged_0(self):
3631
s = """[i for i in (1, 2)]"""
3634
def test_unchanged_1(self):
3635
s = """[i for i in foo()]"""
3638
def test_unchanged_2(self):
3639
s = """[i for i in (1, 2) if nothing]"""
3642
def test_unchanged_3(self):
3643
s = """(i for i in (1, 2))"""
3646
def test_unchanged_4(self):
3647
s = """[i for i in m]"""
3650
class Test_metaclass(FixerTestCase):
3654
def test_unchanged(self):
3655
self.unchanged("class X(): pass")
3656
self.unchanged("class X(object): pass")
3657
self.unchanged("class X(object1, object2): pass")
3658
self.unchanged("class X(object1, object2, object3): pass")
3659
self.unchanged("class X(metaclass=Meta): pass")
3660
self.unchanged("class X(b, arg=23, metclass=Meta): pass")
3661
self.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass")
3665
def __metaclass__(self): pass
3675
def test_comments(self):
3679
__metaclass__ = AppleMeta
3682
class X(metaclass=AppleMeta):
3690
__metaclass__ = Meta
3694
class X(metaclass=Meta):
3700
def test_meta(self):
3701
# no-parent class, odd body
3708
class X(metaclass=Q):
3713
# one parent class, no body
3714
b = """class X(object): __metaclass__ = Q"""
3715
a = """class X(object, metaclass=Q): pass"""
3719
# one parent, simple body
3722
__metaclass__ = Meta
3726
class X(object, metaclass=Meta):
3733
__metaclass__ = Meta; x = 4; g = 23
3736
class X(metaclass=Meta):
3741
# one parent, simple body, __metaclass__ last
3745
__metaclass__ = Meta
3748
class X(object, metaclass=Meta):
3753
# redefining __metaclass__
3761
class X(metaclass=B):
3766
# multiple inheritance, simple body
3768
class X(clsA, clsB):
3769
__metaclass__ = Meta
3773
class X(clsA, clsB, metaclass=Meta):
3778
# keywords in the class statement
3779
b = """class m(a, arg=23): __metaclass__ = Meta"""
3780
a = """class m(a, arg=23, metaclass=Meta): pass"""
3784
class X(expression(2 + 4)):
3785
__metaclass__ = Meta
3788
class X(expression(2 + 4), metaclass=Meta):
3794
class X(expression(2 + 4), x**4):
3795
__metaclass__ = Meta
3798
class X(expression(2 + 4), x**4, metaclass=Meta):
3804
class Test_getcwdu(FixerTestCase):
3808
def test_basic(self):
3809
b = """os.getcwdu"""
3813
b = """os.getcwdu()"""
3814
a = """os.getcwd()"""
3817
b = """meth = os.getcwdu"""
3818
a = """meth = os.getcwd"""
3821
b = """os.getcwdu(args)"""
3822
a = """os.getcwd(args)"""
3825
def test_comment(self):
3826
b = """os.getcwdu() # Foo"""
3827
a = """os.getcwd() # Foo"""
3830
def test_unchanged(self):
3831
s = """os.getcwd()"""
3837
s = """os.getcwdb()"""
3840
def test_indentation(self):
3851
def test_multilation(self):
3852
b = """os .getcwdu()"""
3853
a = """os .getcwd()"""
3856
b = """os. getcwdu"""
3857
a = """os. getcwd"""
3860
b = """os.getcwdu ( )"""
3861
a = """os.getcwd ( )"""
3865
if __name__ == "__main__":
3867
support.run_all_tests(__main__)