blob: d7659fa2672d04c60e19b32861d7f434c0415176 [file] [log] [blame]
Martin v. Löwisef04c442008-03-19 05:04:44 +00001""" Test suite for the fixer modules """
Martin v. Löwisef04c442008-03-19 05:04:44 +00002
3# Python imports
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00004import os
Martin v. Löwisef04c442008-03-19 05:04:44 +00005import unittest
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +00006from itertools import chain
Benjamin Petersond613bb42008-07-16 18:44:47 +00007from operator import itemgetter
Martin v. Löwisef04c442008-03-19 05:04:44 +00008
9# Local imports
Benjamin Peterson5cff9312008-11-28 23:01:28 +000010from lib2to3 import pygram, pytree, refactor, fixer_util
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +000011from lib2to3.tests import support
Martin v. Löwis3de92bf2008-04-10 02:50:50 +000012
Martin v. Löwisef04c442008-03-19 05:04:44 +000013
Martin v. Löwisef04c442008-03-19 05:04:44 +000014class FixerTestCase(support.TestCase):
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +000015
16 # Other test cases can subclass this class and replace "fixer_pkg" with
17 # their own.
18 def setUp(self, fix_list=None, fixer_pkg="lib2to3", options=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +000019 if fix_list is None:
Benjamin Petersond613bb42008-07-16 18:44:47 +000020 fix_list = [self.fixer]
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +000021 self.refactor = support.get_refactorer(fixer_pkg, fix_list, options)
Martin v. Löwisef04c442008-03-19 05:04:44 +000022 self.fixer_log = []
Martin v. Löwis3faa84f2008-03-22 00:07:09 +000023 self.filename = "<string>"
Martin v. Löwisef04c442008-03-19 05:04:44 +000024
Benjamin Peterson5cff9312008-11-28 23:01:28 +000025 for fixer in chain(self.refactor.pre_order,
26 self.refactor.post_order):
27 fixer.log = self.fixer_log
Martin v. Löwisef04c442008-03-19 05:04:44 +000028
29 def _check(self, before, after):
30 before = support.reformat(before)
31 after = support.reformat(after)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +000032 tree = self.refactor.refactor_string(before, self.filename)
Benjamin Peterson73137122009-07-01 01:15:26 +000033 self.assertEqual(after, str(tree))
Martin v. Löwisef04c442008-03-19 05:04:44 +000034 return tree
35
36 def check(self, before, after, ignore_warnings=False):
37 tree = self._check(before, after)
Benjamin Peterson73137122009-07-01 01:15:26 +000038 self.assertTrue(tree.was_changed)
Martin v. Löwisef04c442008-03-19 05:04:44 +000039 if not ignore_warnings:
Benjamin Peterson73137122009-07-01 01:15:26 +000040 self.assertEqual(self.fixer_log, [])
Martin v. Löwisef04c442008-03-19 05:04:44 +000041
42 def warns(self, before, after, message, unchanged=False):
43 tree = self._check(before, after)
Benjamin Peterson73137122009-07-01 01:15:26 +000044 self.assertTrue(message in "".join(self.fixer_log))
Martin v. Löwisef04c442008-03-19 05:04:44 +000045 if not unchanged:
Benjamin Peterson73137122009-07-01 01:15:26 +000046 self.assertTrue(tree.was_changed)
Martin v. Löwisef04c442008-03-19 05:04:44 +000047
48 def warns_unchanged(self, before, message):
49 self.warns(before, before, message, unchanged=True)
50
51 def unchanged(self, before, ignore_warnings=False):
52 self._check(before, before)
53 if not ignore_warnings:
Benjamin Peterson73137122009-07-01 01:15:26 +000054 self.assertEqual(self.fixer_log, [])
Martin v. Löwisef04c442008-03-19 05:04:44 +000055
Martin v. Löwis3faa84f2008-03-22 00:07:09 +000056 def assert_runs_after(self, *names):
Benjamin Peterson8951b612008-09-03 02:27:16 +000057 fixes = [self.fixer]
58 fixes.extend(names)
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +000059 r = support.get_refactorer("lib2to3", fixes)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +000060 (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
64 return
65 if pre and pre[-1].__class__.__module__.endswith(n) and not post:
66 # We're the last in pre and post is empty
67 return
68 self.fail("Fixer run order (%s) is incorrect; %s should be last."\
69 %(", ".join([x.__class__.__module__ for x in (pre+post)]), n))
Martin v. Löwisef04c442008-03-19 05:04:44 +000070
71class Test_ne(FixerTestCase):
72 fixer = "ne"
73
74 def test_basic(self):
75 b = """if x <> y:
76 pass"""
77
78 a = """if x != y:
79 pass"""
80 self.check(b, a)
81
82 def test_no_spaces(self):
83 b = """if x<>y:
84 pass"""
85
86 a = """if x!=y:
87 pass"""
88 self.check(b, a)
89
90 def test_chained(self):
91 b = """if x<>y<>z:
92 pass"""
93
94 a = """if x!=y!=z:
95 pass"""
96 self.check(b, a)
97
98class Test_has_key(FixerTestCase):
99 fixer = "has_key"
100
101 def test_1(self):
102 b = """x = d.has_key("x") or d.has_key("y")"""
103 a = """x = "x" in d or "y" in d"""
104 self.check(b, a)
105
106 def test_2(self):
107 b = """x = a.b.c.d.has_key("x") ** 3"""
108 a = """x = ("x" in a.b.c.d) ** 3"""
109 self.check(b, a)
110
111 def test_3(self):
112 b = """x = a.b.has_key(1 + 2).__repr__()"""
113 a = """x = (1 + 2 in a.b).__repr__()"""
114 self.check(b, a)
115
116 def test_4(self):
117 b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4"""
118 a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4"""
119 self.check(b, a)
120
121 def test_5(self):
122 b = """x = a.has_key(f or g)"""
123 a = """x = (f or g) in a"""
124 self.check(b, a)
125
126 def test_6(self):
127 b = """x = a + b.has_key(c)"""
128 a = """x = a + (c in b)"""
129 self.check(b, a)
130
131 def test_7(self):
132 b = """x = a.has_key(lambda: 12)"""
133 a = """x = (lambda: 12) in a"""
134 self.check(b, a)
135
136 def test_8(self):
137 b = """x = a.has_key(a for a in b)"""
138 a = """x = (a for a in b) in a"""
139 self.check(b, a)
140
141 def test_9(self):
142 b = """if not a.has_key(b): pass"""
143 a = """if b not in a: pass"""
144 self.check(b, a)
145
146 def test_10(self):
147 b = """if not a.has_key(b).__repr__(): pass"""
148 a = """if not (b in a).__repr__(): pass"""
149 self.check(b, a)
150
151 def test_11(self):
152 b = """if not a.has_key(b) ** 2: pass"""
153 a = """if not (b in a) ** 2: pass"""
154 self.check(b, a)
155
156class Test_apply(FixerTestCase):
157 fixer = "apply"
158
159 def test_1(self):
160 b = """x = apply(f, g + h)"""
161 a = """x = f(*g + h)"""
162 self.check(b, a)
163
164 def test_2(self):
165 b = """y = apply(f, g, h)"""
166 a = """y = f(*g, **h)"""
167 self.check(b, a)
168
169 def test_3(self):
170 b = """z = apply(fs[0], g or h, h or g)"""
171 a = """z = fs[0](*g or h, **h or g)"""
172 self.check(b, a)
173
174 def test_4(self):
175 b = """apply(f, (x, y) + t)"""
176 a = """f(*(x, y) + t)"""
177 self.check(b, a)
178
179 def test_5(self):
180 b = """apply(f, args,)"""
181 a = """f(*args)"""
182 self.check(b, a)
183
184 def test_6(self):
185 b = """apply(f, args, kwds,)"""
186 a = """f(*args, **kwds)"""
187 self.check(b, a)
188
189 # Test that complex functions are parenthesized
190
191 def test_complex_1(self):
192 b = """x = apply(f+g, args)"""
193 a = """x = (f+g)(*args)"""
194 self.check(b, a)
195
196 def test_complex_2(self):
197 b = """x = apply(f*g, args)"""
198 a = """x = (f*g)(*args)"""
199 self.check(b, a)
200
201 def test_complex_3(self):
202 b = """x = apply(f**g, args)"""
203 a = """x = (f**g)(*args)"""
204 self.check(b, a)
205
206 # But dotted names etc. not
207
208 def test_dotted_name(self):
209 b = """x = apply(f.g, args)"""
210 a = """x = f.g(*args)"""
211 self.check(b, a)
212
213 def test_subscript(self):
214 b = """x = apply(f[x], args)"""
215 a = """x = f[x](*args)"""
216 self.check(b, a)
217
218 def test_call(self):
219 b = """x = apply(f(), args)"""
220 a = """x = f()(*args)"""
221 self.check(b, a)
222
223 # Extreme case
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)"""
227 self.check(b, a)
228
229 # XXX Comments in weird places still get lost
230 def test_weird_comments(self):
231 b = """apply( # foo
232 f, # bar
233 args)"""
234 a = """f(*args)"""
235 self.check(b, a)
236
237 # These should *not* be touched
238
239 def test_unchanged_1(self):
240 s = """apply()"""
241 self.unchanged(s)
242
243 def test_unchanged_2(self):
244 s = """apply(f)"""
245 self.unchanged(s)
246
247 def test_unchanged_3(self):
248 s = """apply(f,)"""
249 self.unchanged(s)
250
251 def test_unchanged_4(self):
252 s = """apply(f, args, kwds, extras)"""
253 self.unchanged(s)
254
255 def test_unchanged_5(self):
256 s = """apply(f, *args, **kwds)"""
257 self.unchanged(s)
258
259 def test_unchanged_6(self):
260 s = """apply(f, *args)"""
261 self.unchanged(s)
262
263 def test_unchanged_7(self):
264 s = """apply(func=f, args=args, kwds=kwds)"""
265 self.unchanged(s)
266
267 def test_unchanged_8(self):
268 s = """apply(f, args=args, kwds=kwds)"""
269 self.unchanged(s)
270
271 def test_unchanged_9(self):
272 s = """apply(f, args, kwds=kwds)"""
273 self.unchanged(s)
274
275 def test_space_1(self):
276 a = """apply( f, args, kwds)"""
277 b = """f(*args, **kwds)"""
278 self.check(a, b)
279
280 def test_space_2(self):
281 a = """apply( f ,args,kwds )"""
282 b = """f(*args, **kwds)"""
283 self.check(a, b)
284
Benjamin Peterson448e81b2012-12-07 22:44:10 -0500285class Test_reload(FixerTestCase):
286 fixer = "reload"
287
288 def test(self):
289 b = """reload(a)"""
290 a = """import imp\nimp.reload(a)"""
291 self.check(b, a)
292
293 def test_comment(self):
294 b = """reload( a ) # comment"""
295 a = """import imp\nimp.reload( a ) # comment"""
296 self.check(b, a)
297
298 # PEP 8 comments
299 b = """reload( a ) # comment"""
300 a = """import imp\nimp.reload( a ) # comment"""
301 self.check(b, a)
302
303 def test_space(self):
304 b = """reload( a )"""
305 a = """import imp\nimp.reload( a )"""
306 self.check(b, a)
307
308 b = """reload( a)"""
309 a = """import imp\nimp.reload( a)"""
310 self.check(b, a)
311
312 b = """reload(a )"""
313 a = """import imp\nimp.reload(a )"""
314 self.check(b, a)
315
316 def test_unchanged(self):
317 s = """reload(a=1)"""
318 self.unchanged(s)
319
320 s = """reload(f, g)"""
321 self.unchanged(s)
322
323 s = """reload(f, *h)"""
324 self.unchanged(s)
325
326 s = """reload(f, *h, **i)"""
327 self.unchanged(s)
328
329 s = """reload(f, **i)"""
330 self.unchanged(s)
331
332 s = """reload(*h, **i)"""
333 self.unchanged(s)
334
335 s = """reload(*h)"""
336 self.unchanged(s)
337
338 s = """reload(**i)"""
339 self.unchanged(s)
340
341 s = """reload()"""
342 self.unchanged(s)
343
Martin v. Löwisef04c442008-03-19 05:04:44 +0000344class Test_intern(FixerTestCase):
345 fixer = "intern"
346
347 def test_prefix_preservation(self):
348 b = """x = intern( a )"""
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000349 a = """import sys\nx = sys.intern( a )"""
Martin v. Löwisef04c442008-03-19 05:04:44 +0000350 self.check(b, a)
351
352 b = """y = intern("b" # test
353 )"""
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000354 a = """import sys\ny = sys.intern("b" # test
Martin v. Löwisef04c442008-03-19 05:04:44 +0000355 )"""
356 self.check(b, a)
357
358 b = """z = intern(a+b+c.d, )"""
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000359 a = """import sys\nz = sys.intern(a+b+c.d, )"""
Martin v. Löwisef04c442008-03-19 05:04:44 +0000360 self.check(b, a)
361
362 def test(self):
363 b = """x = intern(a)"""
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000364 a = """import sys\nx = sys.intern(a)"""
Martin v. Löwisef04c442008-03-19 05:04:44 +0000365 self.check(b, a)
366
367 b = """z = intern(a+b+c.d,)"""
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000368 a = """import sys\nz = sys.intern(a+b+c.d,)"""
Martin v. Löwisef04c442008-03-19 05:04:44 +0000369 self.check(b, a)
370
371 b = """intern("y%s" % 5).replace("y", "")"""
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000372 a = """import sys\nsys.intern("y%s" % 5).replace("y", "")"""
Martin v. Löwisef04c442008-03-19 05:04:44 +0000373 self.check(b, a)
374
375 # These should not be refactored
376
377 def test_unchanged(self):
378 s = """intern(a=1)"""
379 self.unchanged(s)
380
381 s = """intern(f, g)"""
382 self.unchanged(s)
383
384 s = """intern(*h)"""
385 self.unchanged(s)
386
387 s = """intern(**i)"""
388 self.unchanged(s)
389
390 s = """intern()"""
391 self.unchanged(s)
392
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000393class Test_reduce(FixerTestCase):
394 fixer = "reduce"
395
396 def test_simple_call(self):
397 b = "reduce(a, b, c)"
398 a = "from functools import reduce\nreduce(a, b, c)"
399 self.check(b, a)
400
Benjamin Petersone80b51f2009-11-02 18:33:36 +0000401 def test_bug_7253(self):
402 # fix_tuple_params was being bad and orphaning nodes in the tree.
403 b = "def x(arg): reduce(sum, [])"
404 a = "from functools import reduce\ndef x(arg): reduce(sum, [])"
405 self.check(b, a)
406
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000407 def test_call_with_lambda(self):
408 b = "reduce(lambda x, y: x + y, seq)"
409 a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)"
410 self.check(b, a)
411
412 def test_unchanged(self):
413 s = "reduce(a)"
414 self.unchanged(s)
415
416 s = "reduce(a, b=42)"
417 self.unchanged(s)
418
419 s = "reduce(a, b, c, d)"
420 self.unchanged(s)
421
422 s = "reduce(**c)"
423 self.unchanged(s)
424
425 s = "reduce()"
426 self.unchanged(s)
427
Martin v. Löwisef04c442008-03-19 05:04:44 +0000428class Test_print(FixerTestCase):
429 fixer = "print"
430
431 def test_prefix_preservation(self):
432 b = """print 1, 1+1, 1+1+1"""
433 a = """print(1, 1+1, 1+1+1)"""
434 self.check(b, a)
435
436 def test_idempotency(self):
437 s = """print()"""
438 self.unchanged(s)
439
440 s = """print('')"""
441 self.unchanged(s)
442
443 def test_idempotency_print_as_function(self):
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +0000444 self.refactor.driver.grammar = pygram.python_grammar_no_print_statement
445 s = """print(1, 1+1, 1+1+1)"""
446 self.unchanged(s)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000447
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +0000448 s = """print()"""
449 self.unchanged(s)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000450
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +0000451 s = """print('')"""
452 self.unchanged(s)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000453
454 def test_1(self):
455 b = """print 1, 1+1, 1+1+1"""
456 a = """print(1, 1+1, 1+1+1)"""
457 self.check(b, a)
458
459 def test_2(self):
460 b = """print 1, 2"""
461 a = """print(1, 2)"""
462 self.check(b, a)
463
464 def test_3(self):
465 b = """print"""
466 a = """print()"""
467 self.check(b, a)
468
Benjamin Peterson3a2fb142008-09-13 18:37:09 +0000469 def test_4(self):
470 # from bug 3000
471 b = """print whatever; print"""
472 a = """print(whatever); print()"""
473 self.check(b, a)
474
475 def test_5(self):
476 b = """print; print whatever;"""
477 a = """print(); print(whatever);"""
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +0000478 self.check(b, a)
Benjamin Peterson3a2fb142008-09-13 18:37:09 +0000479
Martin v. Löwisef04c442008-03-19 05:04:44 +0000480 def test_tuple(self):
481 b = """print (a, b, c)"""
482 a = """print((a, b, c))"""
483 self.check(b, a)
484
485 # trailing commas
486
487 def test_trailing_comma_1(self):
488 b = """print 1, 2, 3,"""
489 a = """print(1, 2, 3, end=' ')"""
490 self.check(b, a)
491
492 def test_trailing_comma_2(self):
493 b = """print 1, 2,"""
494 a = """print(1, 2, end=' ')"""
495 self.check(b, a)
496
497 def test_trailing_comma_3(self):
498 b = """print 1,"""
499 a = """print(1, end=' ')"""
500 self.check(b, a)
501
502 # >> stuff
503
504 def test_vargs_without_trailing_comma(self):
505 b = """print >>sys.stderr, 1, 2, 3"""
506 a = """print(1, 2, 3, file=sys.stderr)"""
507 self.check(b, a)
508
509 def test_with_trailing_comma(self):
510 b = """print >>sys.stderr, 1, 2,"""
511 a = """print(1, 2, end=' ', file=sys.stderr)"""
512 self.check(b, a)
513
514 def test_no_trailing_comma(self):
515 b = """print >>sys.stderr, 1+1"""
516 a = """print(1+1, file=sys.stderr)"""
517 self.check(b, a)
518
519 def test_spaces_before_file(self):
520 b = """print >> sys.stderr"""
521 a = """print(file=sys.stderr)"""
522 self.check(b, a)
523
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000524 def test_with_future_print_function(self):
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +0000525 s = "from __future__ import print_function\n" \
526 "print('Hai!', end=' ')"
527 self.unchanged(s)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000528
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +0000529 b = "print 'Hello, world!'"
530 a = "print('Hello, world!')"
531 self.check(b, a)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000532
Martin v. Löwisef04c442008-03-19 05:04:44 +0000533
534class Test_exec(FixerTestCase):
535 fixer = "exec"
536
537 def test_prefix_preservation(self):
538 b = """ exec code in ns1, ns2"""
539 a = """ exec(code, ns1, ns2)"""
540 self.check(b, a)
541
542 def test_basic(self):
543 b = """exec code"""
544 a = """exec(code)"""
545 self.check(b, a)
546
547 def test_with_globals(self):
548 b = """exec code in ns"""
549 a = """exec(code, ns)"""
550 self.check(b, a)
551
552 def test_with_globals_locals(self):
553 b = """exec code in ns1, ns2"""
554 a = """exec(code, ns1, ns2)"""
555 self.check(b, a)
556
557 def test_complex_1(self):
558 b = """exec (a.b()) in ns"""
559 a = """exec((a.b()), ns)"""
560 self.check(b, a)
561
562 def test_complex_2(self):
563 b = """exec a.b() + c in ns"""
564 a = """exec(a.b() + c, ns)"""
565 self.check(b, a)
566
567 # These should not be touched
568
569 def test_unchanged_1(self):
570 s = """exec(code)"""
571 self.unchanged(s)
572
573 def test_unchanged_2(self):
574 s = """exec (code)"""
575 self.unchanged(s)
576
577 def test_unchanged_3(self):
578 s = """exec(code, ns)"""
579 self.unchanged(s)
580
581 def test_unchanged_4(self):
582 s = """exec(code, ns1, ns2)"""
583 self.unchanged(s)
584
Martin v. Löwisef04c442008-03-19 05:04:44 +0000585class Test_repr(FixerTestCase):
586 fixer = "repr"
587
588 def test_prefix_preservation(self):
589 b = """x = `1 + 2`"""
590 a = """x = repr(1 + 2)"""
591 self.check(b, a)
592
593 def test_simple_1(self):
594 b = """x = `1 + 2`"""
595 a = """x = repr(1 + 2)"""
596 self.check(b, a)
597
598 def test_simple_2(self):
599 b = """y = `x`"""
600 a = """y = repr(x)"""
601 self.check(b, a)
602
603 def test_complex(self):
604 b = """z = `y`.__repr__()"""
605 a = """z = repr(y).__repr__()"""
606 self.check(b, a)
607
608 def test_tuple(self):
609 b = """x = `1, 2, 3`"""
610 a = """x = repr((1, 2, 3))"""
611 self.check(b, a)
612
613 def test_nested(self):
614 b = """x = `1 + `2``"""
615 a = """x = repr(1 + repr(2))"""
616 self.check(b, a)
617
618 def test_nested_tuples(self):
619 b = """x = `1, 2 + `3, 4``"""
620 a = """x = repr((1, 2 + repr((3, 4))))"""
621 self.check(b, a)
622
623class Test_except(FixerTestCase):
624 fixer = "except"
625
626 def test_prefix_preservation(self):
627 b = """
628 try:
629 pass
630 except (RuntimeError, ImportError), e:
631 pass"""
632 a = """
633 try:
634 pass
635 except (RuntimeError, ImportError) as e:
636 pass"""
637 self.check(b, a)
638
639 def test_simple(self):
640 b = """
641 try:
642 pass
643 except Foo, e:
644 pass"""
645 a = """
646 try:
647 pass
648 except Foo as e:
649 pass"""
650 self.check(b, a)
651
652 def test_simple_no_space_before_target(self):
653 b = """
654 try:
655 pass
656 except Foo,e:
657 pass"""
658 a = """
659 try:
660 pass
661 except Foo as e:
662 pass"""
663 self.check(b, a)
664
665 def test_tuple_unpack(self):
666 b = """
667 def foo():
668 try:
669 pass
670 except Exception, (f, e):
671 pass
672 except ImportError, e:
673 pass"""
674
675 a = """
676 def foo():
677 try:
678 pass
679 except Exception as xxx_todo_changeme:
680 (f, e) = xxx_todo_changeme.args
681 pass
682 except ImportError as e:
683 pass"""
684 self.check(b, a)
685
686 def test_multi_class(self):
687 b = """
688 try:
689 pass
690 except (RuntimeError, ImportError), e:
691 pass"""
692
693 a = """
694 try:
695 pass
696 except (RuntimeError, ImportError) as e:
697 pass"""
698 self.check(b, a)
699
700 def test_list_unpack(self):
701 b = """
702 try:
703 pass
704 except Exception, [a, b]:
705 pass"""
706
707 a = """
708 try:
709 pass
710 except Exception as xxx_todo_changeme:
711 [a, b] = xxx_todo_changeme.args
712 pass"""
713 self.check(b, a)
714
715 def test_weird_target_1(self):
716 b = """
717 try:
718 pass
719 except Exception, d[5]:
720 pass"""
721
722 a = """
723 try:
724 pass
725 except Exception as xxx_todo_changeme:
726 d[5] = xxx_todo_changeme
727 pass"""
728 self.check(b, a)
729
730 def test_weird_target_2(self):
731 b = """
732 try:
733 pass
734 except Exception, a.foo:
735 pass"""
736
737 a = """
738 try:
739 pass
740 except Exception as xxx_todo_changeme:
741 a.foo = xxx_todo_changeme
742 pass"""
743 self.check(b, a)
744
745 def test_weird_target_3(self):
746 b = """
747 try:
748 pass
749 except Exception, a().foo:
750 pass"""
751
752 a = """
753 try:
754 pass
755 except Exception as xxx_todo_changeme:
756 a().foo = xxx_todo_changeme
757 pass"""
758 self.check(b, a)
759
Martin v. Löwis51d18642008-03-28 05:29:57 +0000760 def test_bare_except(self):
761 b = """
762 try:
763 pass
764 except Exception, a:
765 pass
766 except:
767 pass"""
768
769 a = """
770 try:
771 pass
772 except Exception as a:
773 pass
774 except:
775 pass"""
776 self.check(b, a)
777
778 def test_bare_except_and_else_finally(self):
779 b = """
780 try:
781 pass
782 except Exception, a:
783 pass
784 except:
785 pass
786 else:
787 pass
788 finally:
789 pass"""
790
791 a = """
792 try:
793 pass
794 except Exception as a:
795 pass
796 except:
797 pass
798 else:
799 pass
800 finally:
801 pass"""
802 self.check(b, a)
803
804 def test_multi_fixed_excepts_before_bare_except(self):
805 b = """
806 try:
807 pass
808 except TypeError, b:
809 pass
810 except Exception, a:
811 pass
812 except:
813 pass"""
814
815 a = """
816 try:
817 pass
818 except TypeError as b:
819 pass
820 except Exception as a:
821 pass
822 except:
823 pass"""
824 self.check(b, a)
825
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +0000826 def test_one_line_suites(self):
827 b = """
828 try: raise TypeError
829 except TypeError, e:
830 pass
831 """
832 a = """
833 try: raise TypeError
834 except TypeError as e:
835 pass
836 """
837 self.check(b, a)
838 b = """
839 try:
840 raise TypeError
841 except TypeError, e: pass
842 """
843 a = """
844 try:
845 raise TypeError
846 except TypeError as e: pass
847 """
848 self.check(b, a)
849 b = """
850 try: raise TypeError
851 except TypeError, e: pass
852 """
853 a = """
854 try: raise TypeError
855 except TypeError as e: pass
856 """
857 self.check(b, a)
858 b = """
859 try: raise TypeError
860 except TypeError, e: pass
861 else: function()
862 finally: done()
863 """
864 a = """
865 try: raise TypeError
866 except TypeError as e: pass
867 else: function()
868 finally: done()
869 """
870 self.check(b, a)
871
Martin v. Löwisef04c442008-03-19 05:04:44 +0000872 # These should not be touched:
873
874 def test_unchanged_1(self):
875 s = """
876 try:
877 pass
878 except:
879 pass"""
880 self.unchanged(s)
881
882 def test_unchanged_2(self):
883 s = """
884 try:
885 pass
886 except Exception:
887 pass"""
888 self.unchanged(s)
889
890 def test_unchanged_3(self):
891 s = """
892 try:
893 pass
894 except (Exception, SystemExit):
895 pass"""
896 self.unchanged(s)
897
Martin v. Löwisef04c442008-03-19 05:04:44 +0000898class Test_raise(FixerTestCase):
899 fixer = "raise"
900
901 def test_basic(self):
902 b = """raise Exception, 5"""
903 a = """raise Exception(5)"""
904 self.check(b, a)
905
906 def test_prefix_preservation(self):
907 b = """raise Exception,5"""
908 a = """raise Exception(5)"""
909 self.check(b, a)
910
911 b = """raise Exception, 5"""
912 a = """raise Exception(5)"""
913 self.check(b, a)
914
915 def test_with_comments(self):
916 b = """raise Exception, 5 # foo"""
917 a = """raise Exception(5) # foo"""
918 self.check(b, a)
919
920 b = """raise E, (5, 6) % (a, b) # foo"""
921 a = """raise E((5, 6) % (a, b)) # foo"""
922 self.check(b, a)
923
924 b = """def foo():
925 raise Exception, 5, 6 # foo"""
926 a = """def foo():
927 raise Exception(5).with_traceback(6) # foo"""
928 self.check(b, a)
929
Benjamin Petersonb0871ca2010-10-14 23:03:32 +0000930 def test_None_value(self):
931 b = """raise Exception(5), None, tb"""
932 a = """raise Exception(5).with_traceback(tb)"""
933 self.check(b, a)
934
Martin v. Löwisef04c442008-03-19 05:04:44 +0000935 def test_tuple_value(self):
936 b = """raise Exception, (5, 6, 7)"""
937 a = """raise Exception(5, 6, 7)"""
938 self.check(b, a)
939
940 def test_tuple_detection(self):
941 b = """raise E, (5, 6) % (a, b)"""
942 a = """raise E((5, 6) % (a, b))"""
943 self.check(b, a)
944
945 def test_tuple_exc_1(self):
946 b = """raise (((E1, E2), E3), E4), V"""
947 a = """raise E1(V)"""
948 self.check(b, a)
949
950 def test_tuple_exc_2(self):
951 b = """raise (E1, (E2, E3), E4), V"""
952 a = """raise E1(V)"""
953 self.check(b, a)
954
955 # These should produce a warning
956
957 def test_string_exc(self):
958 s = """raise 'foo'"""
959 self.warns_unchanged(s, "Python 3 does not support string exceptions")
960
961 def test_string_exc_val(self):
962 s = """raise "foo", 5"""
963 self.warns_unchanged(s, "Python 3 does not support string exceptions")
964
965 def test_string_exc_val_tb(self):
966 s = """raise "foo", 5, 6"""
967 self.warns_unchanged(s, "Python 3 does not support string exceptions")
968
969 # These should result in traceback-assignment
970
971 def test_tb_1(self):
972 b = """def foo():
973 raise Exception, 5, 6"""
974 a = """def foo():
975 raise Exception(5).with_traceback(6)"""
976 self.check(b, a)
977
978 def test_tb_2(self):
979 b = """def foo():
980 a = 5
981 raise Exception, 5, 6
982 b = 6"""
983 a = """def foo():
984 a = 5
985 raise Exception(5).with_traceback(6)
986 b = 6"""
987 self.check(b, a)
988
989 def test_tb_3(self):
990 b = """def foo():
991 raise Exception,5,6"""
992 a = """def foo():
993 raise Exception(5).with_traceback(6)"""
994 self.check(b, a)
995
996 def test_tb_4(self):
997 b = """def foo():
998 a = 5
999 raise Exception,5,6
1000 b = 6"""
1001 a = """def foo():
1002 a = 5
1003 raise Exception(5).with_traceback(6)
1004 b = 6"""
1005 self.check(b, a)
1006
1007 def test_tb_5(self):
1008 b = """def foo():
1009 raise Exception, (5, 6, 7), 6"""
1010 a = """def foo():
1011 raise Exception(5, 6, 7).with_traceback(6)"""
1012 self.check(b, a)
1013
1014 def test_tb_6(self):
1015 b = """def foo():
1016 a = 5
1017 raise Exception, (5, 6, 7), 6
1018 b = 6"""
1019 a = """def foo():
1020 a = 5
1021 raise Exception(5, 6, 7).with_traceback(6)
1022 b = 6"""
1023 self.check(b, a)
1024
Martin v. Löwisef04c442008-03-19 05:04:44 +00001025class Test_throw(FixerTestCase):
1026 fixer = "throw"
1027
1028 def test_1(self):
1029 b = """g.throw(Exception, 5)"""
1030 a = """g.throw(Exception(5))"""
1031 self.check(b, a)
1032
1033 def test_2(self):
1034 b = """g.throw(Exception,5)"""
1035 a = """g.throw(Exception(5))"""
1036 self.check(b, a)
1037
1038 def test_3(self):
1039 b = """g.throw(Exception, (5, 6, 7))"""
1040 a = """g.throw(Exception(5, 6, 7))"""
1041 self.check(b, a)
1042
1043 def test_4(self):
1044 b = """5 + g.throw(Exception, 5)"""
1045 a = """5 + g.throw(Exception(5))"""
1046 self.check(b, a)
1047
1048 # These should produce warnings
1049
1050 def test_warn_1(self):
1051 s = """g.throw("foo")"""
1052 self.warns_unchanged(s, "Python 3 does not support string exceptions")
1053
1054 def test_warn_2(self):
1055 s = """g.throw("foo", 5)"""
1056 self.warns_unchanged(s, "Python 3 does not support string exceptions")
1057
1058 def test_warn_3(self):
1059 s = """g.throw("foo", 5, 6)"""
1060 self.warns_unchanged(s, "Python 3 does not support string exceptions")
1061
1062 # These should not be touched
1063
1064 def test_untouched_1(self):
1065 s = """g.throw(Exception)"""
1066 self.unchanged(s)
1067
1068 def test_untouched_2(self):
1069 s = """g.throw(Exception(5, 6))"""
1070 self.unchanged(s)
1071
1072 def test_untouched_3(self):
1073 s = """5 + g.throw(Exception(5, 6))"""
1074 self.unchanged(s)
1075
1076 # These should result in traceback-assignment
1077
1078 def test_tb_1(self):
1079 b = """def foo():
1080 g.throw(Exception, 5, 6)"""
1081 a = """def foo():
1082 g.throw(Exception(5).with_traceback(6))"""
1083 self.check(b, a)
1084
1085 def test_tb_2(self):
1086 b = """def foo():
1087 a = 5
1088 g.throw(Exception, 5, 6)
1089 b = 6"""
1090 a = """def foo():
1091 a = 5
1092 g.throw(Exception(5).with_traceback(6))
1093 b = 6"""
1094 self.check(b, a)
1095
1096 def test_tb_3(self):
1097 b = """def foo():
1098 g.throw(Exception,5,6)"""
1099 a = """def foo():
1100 g.throw(Exception(5).with_traceback(6))"""
1101 self.check(b, a)
1102
1103 def test_tb_4(self):
1104 b = """def foo():
1105 a = 5
1106 g.throw(Exception,5,6)
1107 b = 6"""
1108 a = """def foo():
1109 a = 5
1110 g.throw(Exception(5).with_traceback(6))
1111 b = 6"""
1112 self.check(b, a)
1113
1114 def test_tb_5(self):
1115 b = """def foo():
1116 g.throw(Exception, (5, 6, 7), 6)"""
1117 a = """def foo():
1118 g.throw(Exception(5, 6, 7).with_traceback(6))"""
1119 self.check(b, a)
1120
1121 def test_tb_6(self):
1122 b = """def foo():
1123 a = 5
1124 g.throw(Exception, (5, 6, 7), 6)
1125 b = 6"""
1126 a = """def foo():
1127 a = 5
1128 g.throw(Exception(5, 6, 7).with_traceback(6))
1129 b = 6"""
1130 self.check(b, a)
1131
1132 def test_tb_7(self):
1133 b = """def foo():
1134 a + g.throw(Exception, 5, 6)"""
1135 a = """def foo():
1136 a + g.throw(Exception(5).with_traceback(6))"""
1137 self.check(b, a)
1138
1139 def test_tb_8(self):
1140 b = """def foo():
1141 a = 5
1142 a + g.throw(Exception, 5, 6)
1143 b = 6"""
1144 a = """def foo():
1145 a = 5
1146 a + g.throw(Exception(5).with_traceback(6))
1147 b = 6"""
1148 self.check(b, a)
1149
Martin v. Löwisef04c442008-03-19 05:04:44 +00001150class Test_long(FixerTestCase):
1151 fixer = "long"
1152
1153 def test_1(self):
1154 b = """x = long(x)"""
1155 a = """x = int(x)"""
1156 self.check(b, a)
1157
1158 def test_2(self):
1159 b = """y = isinstance(x, long)"""
1160 a = """y = isinstance(x, int)"""
1161 self.check(b, a)
1162
1163 def test_3(self):
1164 b = """z = type(x) in (int, long)"""
1165 a = """z = type(x) in (int, int)"""
1166 self.check(b, a)
1167
Benjamin Peterson8bcddca2009-01-03 16:53:14 +00001168 def test_unchanged(self):
1169 s = """long = True"""
1170 self.unchanged(s)
1171
1172 s = """s.long = True"""
1173 self.unchanged(s)
1174
1175 s = """def long(): pass"""
1176 self.unchanged(s)
1177
1178 s = """class long(): pass"""
1179 self.unchanged(s)
1180
1181 s = """def f(long): pass"""
1182 self.unchanged(s)
1183
1184 s = """def f(g, long): pass"""
1185 self.unchanged(s)
1186
1187 s = """def f(x, long=True): pass"""
1188 self.unchanged(s)
1189
Martin v. Löwisef04c442008-03-19 05:04:44 +00001190 def test_prefix_preservation(self):
1191 b = """x = long( x )"""
1192 a = """x = int( x )"""
1193 self.check(b, a)
1194
Benjamin Peterson8bcddca2009-01-03 16:53:14 +00001195
1196class Test_execfile(FixerTestCase):
1197 fixer = "execfile"
1198
1199 def test_conversion(self):
1200 b = """execfile("fn")"""
1201 a = """exec(compile(open("fn").read(), "fn", 'exec'))"""
1202 self.check(b, a)
1203
1204 b = """execfile("fn", glob)"""
1205 a = """exec(compile(open("fn").read(), "fn", 'exec'), glob)"""
1206 self.check(b, a)
1207
1208 b = """execfile("fn", glob, loc)"""
1209 a = """exec(compile(open("fn").read(), "fn", 'exec'), glob, loc)"""
1210 self.check(b, a)
1211
1212 b = """execfile("fn", globals=glob)"""
1213 a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob)"""
1214 self.check(b, a)
1215
1216 b = """execfile("fn", locals=loc)"""
1217 a = """exec(compile(open("fn").read(), "fn", 'exec'), locals=loc)"""
1218 self.check(b, a)
1219
1220 b = """execfile("fn", globals=glob, locals=loc)"""
1221 a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob, locals=loc)"""
1222 self.check(b, a)
1223
1224 def test_spacing(self):
1225 b = """execfile( "fn" )"""
1226 a = """exec(compile(open( "fn" ).read(), "fn", 'exec'))"""
1227 self.check(b, a)
1228
1229 b = """execfile("fn", globals = glob)"""
1230 a = """exec(compile(open("fn").read(), "fn", 'exec'), globals = glob)"""
1231 self.check(b, a)
1232
1233
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00001234class Test_isinstance(FixerTestCase):
1235 fixer = "isinstance"
1236
1237 def test_remove_multiple_items(self):
1238 b = """isinstance(x, (int, int, int))"""
1239 a = """isinstance(x, int)"""
1240 self.check(b, a)
1241
1242 b = """isinstance(x, (int, float, int, int, float))"""
1243 a = """isinstance(x, (int, float))"""
1244 self.check(b, a)
1245
1246 b = """isinstance(x, (int, float, int, int, float, str))"""
1247 a = """isinstance(x, (int, float, str))"""
1248 self.check(b, a)
1249
1250 b = """isinstance(foo() + bar(), (x(), y(), x(), int, int))"""
1251 a = """isinstance(foo() + bar(), (x(), y(), x(), int))"""
1252 self.check(b, a)
1253
1254 def test_prefix_preservation(self):
1255 b = """if isinstance( foo(), ( bar, bar, baz )) : pass"""
1256 a = """if isinstance( foo(), ( bar, baz )) : pass"""
1257 self.check(b, a)
1258
1259 def test_unchanged(self):
1260 self.unchanged("isinstance(x, (str, int))")
1261
Martin v. Löwisef04c442008-03-19 05:04:44 +00001262class Test_dict(FixerTestCase):
1263 fixer = "dict"
1264
1265 def test_prefix_preservation(self):
1266 b = "if d. keys ( ) : pass"
1267 a = "if list(d. keys ( )) : pass"
1268 self.check(b, a)
1269
1270 b = "if d. items ( ) : pass"
1271 a = "if list(d. items ( )) : pass"
1272 self.check(b, a)
1273
1274 b = "if d. iterkeys ( ) : pass"
1275 a = "if iter(d. keys ( )) : pass"
1276 self.check(b, a)
1277
1278 b = "[i for i in d. iterkeys( ) ]"
1279 a = "[i for i in d. keys( ) ]"
1280 self.check(b, a)
1281
Martin v. Löwis5577eaa2010-01-30 11:22:26 +00001282 b = "if d. viewkeys ( ) : pass"
1283 a = "if d. keys ( ) : pass"
1284 self.check(b, a)
1285
1286 b = "[i for i in d. viewkeys( ) ]"
1287 a = "[i for i in d. keys( ) ]"
1288 self.check(b, a)
1289
Martin v. Löwisef04c442008-03-19 05:04:44 +00001290 def test_trailing_comment(self):
1291 b = "d.keys() # foo"
1292 a = "list(d.keys()) # foo"
1293 self.check(b, a)
1294
1295 b = "d.items() # foo"
1296 a = "list(d.items()) # foo"
1297 self.check(b, a)
1298
1299 b = "d.iterkeys() # foo"
1300 a = "iter(d.keys()) # foo"
1301 self.check(b, a)
1302
1303 b = """[i for i in d.iterkeys() # foo
1304 ]"""
1305 a = """[i for i in d.keys() # foo
1306 ]"""
1307 self.check(b, a)
1308
Martin v. Löwis5577eaa2010-01-30 11:22:26 +00001309 b = """[i for i in d.iterkeys() # foo
1310 ]"""
1311 a = """[i for i in d.keys() # foo
1312 ]"""
1313 self.check(b, a)
1314
1315 b = "d.viewitems() # foo"
1316 a = "d.items() # foo"
1317 self.check(b, a)
1318
Martin v. Löwisef04c442008-03-19 05:04:44 +00001319 def test_unchanged(self):
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +00001320 for wrapper in fixer_util.consuming_calls:
Martin v. Löwisef04c442008-03-19 05:04:44 +00001321 s = "s = %s(d.keys())" % wrapper
1322 self.unchanged(s)
1323
1324 s = "s = %s(d.values())" % wrapper
1325 self.unchanged(s)
1326
1327 s = "s = %s(d.items())" % wrapper
1328 self.unchanged(s)
1329
1330 def test_01(self):
1331 b = "d.keys()"
1332 a = "list(d.keys())"
1333 self.check(b, a)
1334
1335 b = "a[0].foo().keys()"
1336 a = "list(a[0].foo().keys())"
1337 self.check(b, a)
1338
1339 def test_02(self):
1340 b = "d.items()"
1341 a = "list(d.items())"
1342 self.check(b, a)
1343
1344 def test_03(self):
1345 b = "d.values()"
1346 a = "list(d.values())"
1347 self.check(b, a)
1348
1349 def test_04(self):
1350 b = "d.iterkeys()"
1351 a = "iter(d.keys())"
1352 self.check(b, a)
1353
1354 def test_05(self):
1355 b = "d.iteritems()"
1356 a = "iter(d.items())"
1357 self.check(b, a)
1358
1359 def test_06(self):
1360 b = "d.itervalues()"
1361 a = "iter(d.values())"
1362 self.check(b, a)
1363
1364 def test_07(self):
1365 s = "list(d.keys())"
1366 self.unchanged(s)
1367
1368 def test_08(self):
1369 s = "sorted(d.keys())"
1370 self.unchanged(s)
1371
1372 def test_09(self):
1373 b = "iter(d.keys())"
1374 a = "iter(list(d.keys()))"
1375 self.check(b, a)
1376
1377 def test_10(self):
1378 b = "foo(d.keys())"
1379 a = "foo(list(d.keys()))"
1380 self.check(b, a)
1381
1382 def test_11(self):
1383 b = "for i in d.keys(): print i"
1384 a = "for i in list(d.keys()): print i"
1385 self.check(b, a)
1386
1387 def test_12(self):
1388 b = "for i in d.iterkeys(): print i"
1389 a = "for i in d.keys(): print i"
1390 self.check(b, a)
1391
1392 def test_13(self):
1393 b = "[i for i in d.keys()]"
1394 a = "[i for i in list(d.keys())]"
1395 self.check(b, a)
1396
1397 def test_14(self):
1398 b = "[i for i in d.iterkeys()]"
1399 a = "[i for i in d.keys()]"
1400 self.check(b, a)
1401
1402 def test_15(self):
1403 b = "(i for i in d.keys())"
1404 a = "(i for i in list(d.keys()))"
1405 self.check(b, a)
1406
1407 def test_16(self):
1408 b = "(i for i in d.iterkeys())"
1409 a = "(i for i in d.keys())"
1410 self.check(b, a)
1411
1412 def test_17(self):
1413 b = "iter(d.iterkeys())"
1414 a = "iter(d.keys())"
1415 self.check(b, a)
1416
1417 def test_18(self):
1418 b = "list(d.iterkeys())"
1419 a = "list(d.keys())"
1420 self.check(b, a)
1421
1422 def test_19(self):
1423 b = "sorted(d.iterkeys())"
1424 a = "sorted(d.keys())"
1425 self.check(b, a)
1426
1427 def test_20(self):
1428 b = "foo(d.iterkeys())"
1429 a = "foo(iter(d.keys()))"
1430 self.check(b, a)
1431
1432 def test_21(self):
1433 b = "print h.iterkeys().next()"
1434 a = "print iter(h.keys()).next()"
1435 self.check(b, a)
1436
1437 def test_22(self):
1438 b = "print h.keys()[0]"
1439 a = "print list(h.keys())[0]"
1440 self.check(b, a)
1441
1442 def test_23(self):
1443 b = "print list(h.iterkeys().next())"
1444 a = "print list(iter(h.keys()).next())"
1445 self.check(b, a)
1446
1447 def test_24(self):
1448 b = "for x in h.keys()[0]: print x"
1449 a = "for x in list(h.keys())[0]: print x"
1450 self.check(b, a)
1451
Martin v. Löwis5577eaa2010-01-30 11:22:26 +00001452 def test_25(self):
1453 b = "d.viewkeys()"
1454 a = "d.keys()"
1455 self.check(b, a)
1456
1457 def test_26(self):
1458 b = "d.viewitems()"
1459 a = "d.items()"
1460 self.check(b, a)
1461
1462 def test_27(self):
1463 b = "d.viewvalues()"
1464 a = "d.values()"
1465 self.check(b, a)
1466
1467 def test_14(self):
1468 b = "[i for i in d.viewkeys()]"
1469 a = "[i for i in d.keys()]"
1470 self.check(b, a)
1471
1472 def test_15(self):
1473 b = "(i for i in d.viewkeys())"
1474 a = "(i for i in d.keys())"
1475 self.check(b, a)
1476
1477 def test_17(self):
1478 b = "iter(d.viewkeys())"
1479 a = "iter(d.keys())"
1480 self.check(b, a)
1481
1482 def test_18(self):
1483 b = "list(d.viewkeys())"
1484 a = "list(d.keys())"
1485 self.check(b, a)
1486
1487 def test_19(self):
1488 b = "sorted(d.viewkeys())"
1489 a = "sorted(d.keys())"
1490 self.check(b, a)
1491
Martin v. Löwisef04c442008-03-19 05:04:44 +00001492class Test_xrange(FixerTestCase):
1493 fixer = "xrange"
1494
1495 def test_prefix_preservation(self):
1496 b = """x = xrange( 10 )"""
1497 a = """x = range( 10 )"""
1498 self.check(b, a)
1499
1500 b = """x = xrange( 1 , 10 )"""
1501 a = """x = range( 1 , 10 )"""
1502 self.check(b, a)
1503
1504 b = """x = xrange( 0 , 10 , 2 )"""
1505 a = """x = range( 0 , 10 , 2 )"""
1506 self.check(b, a)
1507
Martin v. Löwis3de92bf2008-04-10 02:50:50 +00001508 def test_single_arg(self):
Martin v. Löwisef04c442008-03-19 05:04:44 +00001509 b = """x = xrange(10)"""
1510 a = """x = range(10)"""
1511 self.check(b, a)
1512
Martin v. Löwis3de92bf2008-04-10 02:50:50 +00001513 def test_two_args(self):
Martin v. Löwisef04c442008-03-19 05:04:44 +00001514 b = """x = xrange(1, 10)"""
1515 a = """x = range(1, 10)"""
1516 self.check(b, a)
1517
Martin v. Löwis3de92bf2008-04-10 02:50:50 +00001518 def test_three_args(self):
Martin v. Löwisef04c442008-03-19 05:04:44 +00001519 b = """x = xrange(0, 10, 2)"""
1520 a = """x = range(0, 10, 2)"""
1521 self.check(b, a)
1522
Martin v. Löwis3de92bf2008-04-10 02:50:50 +00001523 def test_wrap_in_list(self):
1524 b = """x = range(10, 3, 9)"""
1525 a = """x = list(range(10, 3, 9))"""
1526 self.check(b, a)
1527
1528 b = """x = foo(range(10, 3, 9))"""
1529 a = """x = foo(list(range(10, 3, 9)))"""
1530 self.check(b, a)
1531
1532 b = """x = range(10, 3, 9) + [4]"""
1533 a = """x = list(range(10, 3, 9)) + [4]"""
1534 self.check(b, a)
1535
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00001536 b = """x = range(10)[::-1]"""
1537 a = """x = list(range(10))[::-1]"""
1538 self.check(b, a)
1539
1540 b = """x = range(10) [3]"""
1541 a = """x = list(range(10)) [3]"""
1542 self.check(b, a)
1543
Martin v. Löwis3de92bf2008-04-10 02:50:50 +00001544 def test_xrange_in_for(self):
Martin v. Löwisef04c442008-03-19 05:04:44 +00001545 b = """for i in xrange(10):\n j=i"""
1546 a = """for i in range(10):\n j=i"""
1547 self.check(b, a)
1548
Martin v. Löwis3de92bf2008-04-10 02:50:50 +00001549 b = """[i for i in xrange(10)]"""
1550 a = """[i for i in range(10)]"""
1551 self.check(b, a)
1552
1553 def test_range_in_for(self):
1554 self.unchanged("for i in range(10): pass")
1555 self.unchanged("[i for i in range(10)]")
1556
1557 def test_in_contains_test(self):
1558 self.unchanged("x in range(10, 3, 9)")
1559
1560 def test_in_consuming_context(self):
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +00001561 for call in fixer_util.consuming_calls:
Martin v. Löwis3de92bf2008-04-10 02:50:50 +00001562 self.unchanged("a = %s(range(10))" % call)
1563
Benjamin Petersonc9e833f2010-05-08 15:46:00 +00001564class Test_xrange_with_reduce(FixerTestCase):
1565
1566 def setUp(self):
1567 super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"])
1568
1569 def test_double_transform(self):
1570 b = """reduce(x, xrange(5))"""
1571 a = """from functools import reduce
1572reduce(x, range(5))"""
1573 self.check(b, a)
1574
Martin v. Löwisef04c442008-03-19 05:04:44 +00001575class Test_raw_input(FixerTestCase):
1576 fixer = "raw_input"
1577
1578 def test_prefix_preservation(self):
1579 b = """x = raw_input( )"""
1580 a = """x = input( )"""
1581 self.check(b, a)
1582
1583 b = """x = raw_input( '' )"""
1584 a = """x = input( '' )"""
1585 self.check(b, a)
1586
1587 def test_1(self):
1588 b = """x = raw_input()"""
1589 a = """x = input()"""
1590 self.check(b, a)
1591
1592 def test_2(self):
1593 b = """x = raw_input('')"""
1594 a = """x = input('')"""
1595 self.check(b, a)
1596
1597 def test_3(self):
1598 b = """x = raw_input('prompt')"""
1599 a = """x = input('prompt')"""
1600 self.check(b, a)
1601
1602 def test_4(self):
1603 b = """x = raw_input(foo(a) + 6)"""
1604 a = """x = input(foo(a) + 6)"""
1605 self.check(b, a)
1606
Benjamin Petersoncf603822008-09-01 19:56:06 +00001607 def test_5(self):
1608 b = """x = raw_input(invite).split()"""
1609 a = """x = input(invite).split()"""
1610 self.check(b, a)
1611
1612 def test_6(self):
1613 b = """x = raw_input(invite) . split ()"""
1614 a = """x = input(invite) . split ()"""
1615 self.check(b, a)
1616
1617 def test_8(self):
1618 b = "x = int(raw_input())"
1619 a = "x = int(input())"
1620 self.check(b, a)
1621
Martin v. Löwisef04c442008-03-19 05:04:44 +00001622class Test_funcattrs(FixerTestCase):
1623 fixer = "funcattrs"
1624
1625 attrs = ["closure", "doc", "name", "defaults", "code", "globals", "dict"]
1626
1627 def test(self):
1628 for attr in self.attrs:
1629 b = "a.func_%s" % attr
1630 a = "a.__%s__" % attr
1631 self.check(b, a)
1632
1633 b = "self.foo.func_%s.foo_bar" % attr
1634 a = "self.foo.__%s__.foo_bar" % attr
1635 self.check(b, a)
1636
1637 def test_unchanged(self):
1638 for attr in self.attrs:
1639 s = "foo(func_%s + 5)" % attr
1640 self.unchanged(s)
1641
1642 s = "f(foo.__%s__)" % attr
1643 self.unchanged(s)
1644
1645 s = "f(foo.__%s__.foo)" % attr
1646 self.unchanged(s)
1647
Martin v. Löwisef04c442008-03-19 05:04:44 +00001648class Test_xreadlines(FixerTestCase):
1649 fixer = "xreadlines"
1650
1651 def test_call(self):
1652 b = "for x in f.xreadlines(): pass"
1653 a = "for x in f: pass"
1654 self.check(b, a)
1655
1656 b = "for x in foo().xreadlines(): pass"
1657 a = "for x in foo(): pass"
1658 self.check(b, a)
1659
1660 b = "for x in (5 + foo()).xreadlines(): pass"
1661 a = "for x in (5 + foo()): pass"
1662 self.check(b, a)
1663
1664 def test_attr_ref(self):
1665 b = "foo(f.xreadlines + 5)"
1666 a = "foo(f.__iter__ + 5)"
1667 self.check(b, a)
1668
1669 b = "foo(f().xreadlines + 5)"
1670 a = "foo(f().__iter__ + 5)"
1671 self.check(b, a)
1672
1673 b = "foo((5 + f()).xreadlines + 5)"
1674 a = "foo((5 + f()).__iter__ + 5)"
1675 self.check(b, a)
1676
1677 def test_unchanged(self):
1678 s = "for x in f.xreadlines(5): pass"
1679 self.unchanged(s)
1680
1681 s = "for x in f.xreadlines(k=5): pass"
1682 self.unchanged(s)
1683
1684 s = "for x in f.xreadlines(*k, **v): pass"
1685 self.unchanged(s)
1686
1687 s = "foo(xreadlines)"
1688 self.unchanged(s)
1689
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00001690
1691class ImportsFixerTests:
Martin v. Löwisef04c442008-03-19 05:04:44 +00001692
1693 def test_import_module(self):
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001694 for old, new in self.modules.items():
Martin v. Löwisef04c442008-03-19 05:04:44 +00001695 b = "import %s" % old
1696 a = "import %s" % new
1697 self.check(b, a)
1698
1699 b = "import foo, %s, bar" % old
1700 a = "import foo, %s, bar" % new
1701 self.check(b, a)
1702
1703 def test_import_from(self):
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001704 for old, new in self.modules.items():
1705 b = "from %s import foo" % old
1706 a = "from %s import foo" % new
Martin v. Löwis2eab97c2008-05-25 15:24:57 +00001707 self.check(b, a)
1708
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001709 b = "from %s import foo, bar" % old
1710 a = "from %s import foo, bar" % new
1711 self.check(b, a)
Martin v. Löwis2eab97c2008-05-25 15:24:57 +00001712
Benjamin Petersonba558182008-11-10 22:21:33 +00001713 b = "from %s import (yes, no)" % old
1714 a = "from %s import (yes, no)" % new
1715 self.check(b, a)
1716
Martin v. Löwisef04c442008-03-19 05:04:44 +00001717 def test_import_module_as(self):
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001718 for old, new in self.modules.items():
Martin v. Löwisef04c442008-03-19 05:04:44 +00001719 b = "import %s as foo_bar" % old
1720 a = "import %s as foo_bar" % new
1721 self.check(b, a)
1722
1723 b = "import %s as foo_bar" % old
1724 a = "import %s as foo_bar" % new
1725 self.check(b, a)
1726
1727 def test_import_from_as(self):
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001728 for old, new in self.modules.items():
1729 b = "from %s import foo as bar" % old
1730 a = "from %s import foo as bar" % new
1731 self.check(b, a)
Martin v. Löwisef04c442008-03-19 05:04:44 +00001732
1733 def test_star(self):
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001734 for old, new in self.modules.items():
1735 b = "from %s import *" % old
1736 a = "from %s import *" % new
1737 self.check(b, a)
Martin v. Löwisef04c442008-03-19 05:04:44 +00001738
1739 def test_import_module_usage(self):
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001740 for old, new in self.modules.items():
Martin v. Löwis2eab97c2008-05-25 15:24:57 +00001741 b = """
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001742 import %s
1743 foo(%s.bar)
1744 """ % (old, old)
Martin v. Löwis2eab97c2008-05-25 15:24:57 +00001745 a = """
Benjamin Peterson4cdf5722008-07-17 02:21:56 +00001746 import %s
1747 foo(%s.bar)
1748 """ % (new, new)
Martin v. Löwis2eab97c2008-05-25 15:24:57 +00001749 self.check(b, a)
1750
Benjamin Peterson5cff9312008-11-28 23:01:28 +00001751 b = """
1752 from %s import x
1753 %s = 23
1754 """ % (old, old)
1755 a = """
1756 from %s import x
1757 %s = 23
1758 """ % (new, old)
1759 self.check(b, a)
1760
1761 s = """
1762 def f():
1763 %s.method()
1764 """ % (old,)
1765 self.unchanged(s)
1766
1767 # test nested usage
1768 b = """
1769 import %s
1770 %s.bar(%s.foo)
1771 """ % (old, old, old)
1772 a = """
1773 import %s
1774 %s.bar(%s.foo)
1775 """ % (new, new, new)
1776 self.check(b, a)
1777
1778 b = """
1779 import %s
1780 x.%s
1781 """ % (old, old)
1782 a = """
1783 import %s
1784 x.%s
1785 """ % (new, old)
1786 self.check(b, a)
1787
1788
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00001789class Test_imports(FixerTestCase, ImportsFixerTests):
1790 fixer = "imports"
1791 from ..fixes.fix_imports import MAPPING as modules
Martin v. Löwisef04c442008-03-19 05:04:44 +00001792
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00001793 def test_multiple_imports(self):
1794 b = """import urlparse, cStringIO"""
1795 a = """import urllib.parse, io"""
1796 self.check(b, a)
1797
1798 def test_multiple_imports_as(self):
1799 b = """
1800 import copy_reg as bar, HTMLParser as foo, urlparse
1801 s = urlparse.spam(bar.foo())
1802 """
1803 a = """
1804 import copyreg as bar, html.parser as foo, urllib.parse
1805 s = urllib.parse.spam(bar.foo())
1806 """
1807 self.check(b, a)
1808
1809
1810class Test_imports2(FixerTestCase, ImportsFixerTests):
Benjamin Petersond613bb42008-07-16 18:44:47 +00001811 fixer = "imports2"
1812 from ..fixes.fix_imports2 import MAPPING as modules
1813
1814
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00001815class Test_imports_fixer_order(FixerTestCase, ImportsFixerTests):
Benjamin Petersond613bb42008-07-16 18:44:47 +00001816
1817 def setUp(self):
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00001818 super(Test_imports_fixer_order, self).setUp(['imports', 'imports2'])
Benjamin Petersond613bb42008-07-16 18:44:47 +00001819 from ..fixes.fix_imports2 import MAPPING as mapping2
1820 self.modules = mapping2.copy()
1821 from ..fixes.fix_imports import MAPPING as mapping1
1822 for key in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'):
1823 self.modules[key] = mapping1[key]
1824
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +00001825 def test_after_local_imports_refactoring(self):
1826 for fix in ("imports", "imports2"):
1827 self.fixer = fix
1828 self.assert_runs_after("import")
1829
Benjamin Petersond613bb42008-07-16 18:44:47 +00001830
1831class Test_urllib(FixerTestCase):
1832 fixer = "urllib"
1833 from ..fixes.fix_urllib import MAPPING as modules
1834
1835 def test_import_module(self):
1836 for old, changes in self.modules.items():
1837 b = "import %s" % old
1838 a = "import %s" % ", ".join(map(itemgetter(0), changes))
1839 self.check(b, a)
1840
1841 def test_import_from(self):
1842 for old, changes in self.modules.items():
1843 all_members = []
1844 for new, members in changes:
1845 for member in members:
1846 all_members.append(member)
1847 b = "from %s import %s" % (old, member)
1848 a = "from %s import %s" % (new, member)
1849 self.check(b, a)
1850
1851 s = "from foo import %s" % member
1852 self.unchanged(s)
1853
1854 b = "from %s import %s" % (old, ", ".join(members))
1855 a = "from %s import %s" % (new, ", ".join(members))
1856 self.check(b, a)
1857
1858 s = "from foo import %s" % ", ".join(members)
1859 self.unchanged(s)
1860
1861 # test the breaking of a module into multiple replacements
1862 b = "from %s import %s" % (old, ", ".join(all_members))
1863 a = "\n".join(["from %s import %s" % (new, ", ".join(members))
1864 for (new, members) in changes])
1865 self.check(b, a)
1866
1867 def test_import_module_as(self):
1868 for old in self.modules:
1869 s = "import %s as foo" % old
1870 self.warns_unchanged(s, "This module is now multiple modules")
1871
1872 def test_import_from_as(self):
1873 for old, changes in self.modules.items():
1874 for new, members in changes:
1875 for member in members:
1876 b = "from %s import %s as foo_bar" % (old, member)
1877 a = "from %s import %s as foo_bar" % (new, member)
1878 self.check(b, a)
Benjamin Petersonb0871ca2010-10-14 23:03:32 +00001879 b = "from %s import %s as blah, %s" % (old, member, member)
1880 a = "from %s import %s as blah, %s" % (new, member, member)
1881 self.check(b, a)
Benjamin Petersond613bb42008-07-16 18:44:47 +00001882
1883 def test_star(self):
1884 for old in self.modules:
1885 s = "from %s import *" % old
1886 self.warns_unchanged(s, "Cannot handle star imports")
1887
Benjamin Peterson68c80ed2010-08-08 19:23:25 +00001888 def test_indented(self):
1889 b = """
1890def foo():
1891 from urllib import urlencode, urlopen
1892"""
1893 a = """
1894def foo():
1895 from urllib.parse import urlencode
1896 from urllib.request import urlopen
1897"""
1898 self.check(b, a)
1899
1900 b = """
1901def foo():
1902 other()
1903 from urllib import urlencode, urlopen
1904"""
1905 a = """
1906def foo():
1907 other()
1908 from urllib.parse import urlencode
1909 from urllib.request import urlopen
1910"""
1911 self.check(b, a)
1912
1913
1914
Benjamin Petersond613bb42008-07-16 18:44:47 +00001915 def test_import_module_usage(self):
1916 for old, changes in self.modules.items():
1917 for new, members in changes:
1918 for member in members:
Benjamin Peterson39778f62009-11-25 18:37:12 +00001919 new_import = ", ".join([n for (n, mems)
1920 in self.modules[old]])
Benjamin Petersond613bb42008-07-16 18:44:47 +00001921 b = """
1922 import %s
1923 foo(%s.%s)
1924 """ % (old, old, member)
1925 a = """
1926 import %s
1927 foo(%s.%s)
Benjamin Peterson39778f62009-11-25 18:37:12 +00001928 """ % (new_import, new, member)
1929 self.check(b, a)
1930 b = """
1931 import %s
1932 %s.%s(%s.%s)
1933 """ % (old, old, member, old, member)
1934 a = """
1935 import %s
1936 %s.%s(%s.%s)
1937 """ % (new_import, new, member, new, member)
Benjamin Petersond613bb42008-07-16 18:44:47 +00001938 self.check(b, a)
1939
1940
Martin v. Löwisef04c442008-03-19 05:04:44 +00001941class Test_input(FixerTestCase):
1942 fixer = "input"
1943
1944 def test_prefix_preservation(self):
1945 b = """x = input( )"""
1946 a = """x = eval(input( ))"""
1947 self.check(b, a)
1948
1949 b = """x = input( '' )"""
1950 a = """x = eval(input( '' ))"""
1951 self.check(b, a)
1952
1953 def test_trailing_comment(self):
1954 b = """x = input() # foo"""
1955 a = """x = eval(input()) # foo"""
1956 self.check(b, a)
1957
1958 def test_idempotency(self):
1959 s = """x = eval(input())"""
1960 self.unchanged(s)
1961
1962 s = """x = eval(input(''))"""
1963 self.unchanged(s)
1964
1965 s = """x = eval(input(foo(5) + 9))"""
1966 self.unchanged(s)
1967
1968 def test_1(self):
1969 b = """x = input()"""
1970 a = """x = eval(input())"""
1971 self.check(b, a)
1972
1973 def test_2(self):
1974 b = """x = input('')"""
1975 a = """x = eval(input(''))"""
1976 self.check(b, a)
1977
1978 def test_3(self):
1979 b = """x = input('prompt')"""
1980 a = """x = eval(input('prompt'))"""
1981 self.check(b, a)
1982
1983 def test_4(self):
1984 b = """x = input(foo(5) + 9)"""
1985 a = """x = eval(input(foo(5) + 9))"""
1986 self.check(b, a)
1987
Martin v. Löwisef04c442008-03-19 05:04:44 +00001988class Test_tuple_params(FixerTestCase):
1989 fixer = "tuple_params"
1990
1991 def test_unchanged_1(self):
1992 s = """def foo(): pass"""
1993 self.unchanged(s)
1994
1995 def test_unchanged_2(self):
1996 s = """def foo(a, b, c): pass"""
1997 self.unchanged(s)
1998
1999 def test_unchanged_3(self):
2000 s = """def foo(a=3, b=4, c=5): pass"""
2001 self.unchanged(s)
2002
2003 def test_1(self):
2004 b = """
2005 def foo(((a, b), c)):
2006 x = 5"""
2007
2008 a = """
2009 def foo(xxx_todo_changeme):
2010 ((a, b), c) = xxx_todo_changeme
2011 x = 5"""
2012 self.check(b, a)
2013
2014 def test_2(self):
2015 b = """
2016 def foo(((a, b), c), d):
2017 x = 5"""
2018
2019 a = """
2020 def foo(xxx_todo_changeme, d):
2021 ((a, b), c) = xxx_todo_changeme
2022 x = 5"""
2023 self.check(b, a)
2024
2025 def test_3(self):
2026 b = """
2027 def foo(((a, b), c), d) -> e:
2028 x = 5"""
2029
2030 a = """
2031 def foo(xxx_todo_changeme, d) -> e:
2032 ((a, b), c) = xxx_todo_changeme
2033 x = 5"""
2034 self.check(b, a)
2035
2036 def test_semicolon(self):
2037 b = """
2038 def foo(((a, b), c)): x = 5; y = 7"""
2039
2040 a = """
2041 def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme; x = 5; y = 7"""
2042 self.check(b, a)
2043
2044 def test_keywords(self):
2045 b = """
2046 def foo(((a, b), c), d, e=5) -> z:
2047 x = 5"""
2048
2049 a = """
2050 def foo(xxx_todo_changeme, d, e=5) -> z:
2051 ((a, b), c) = xxx_todo_changeme
2052 x = 5"""
2053 self.check(b, a)
2054
2055 def test_varargs(self):
2056 b = """
2057 def foo(((a, b), c), d, *vargs, **kwargs) -> z:
2058 x = 5"""
2059
2060 a = """
2061 def foo(xxx_todo_changeme, d, *vargs, **kwargs) -> z:
2062 ((a, b), c) = xxx_todo_changeme
2063 x = 5"""
2064 self.check(b, a)
2065
2066 def test_multi_1(self):
2067 b = """
2068 def foo(((a, b), c), (d, e, f)) -> z:
2069 x = 5"""
2070
2071 a = """
2072 def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
2073 ((a, b), c) = xxx_todo_changeme
2074 (d, e, f) = xxx_todo_changeme1
2075 x = 5"""
2076 self.check(b, a)
2077
2078 def test_multi_2(self):
2079 b = """
2080 def foo(x, ((a, b), c), d, (e, f, g), y) -> z:
2081 x = 5"""
2082
2083 a = """
2084 def foo(x, xxx_todo_changeme, d, xxx_todo_changeme1, y) -> z:
2085 ((a, b), c) = xxx_todo_changeme
2086 (e, f, g) = xxx_todo_changeme1
2087 x = 5"""
2088 self.check(b, a)
2089
2090 def test_docstring(self):
2091 b = """
2092 def foo(((a, b), c), (d, e, f)) -> z:
2093 "foo foo foo foo"
2094 x = 5"""
2095
2096 a = """
2097 def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
2098 "foo foo foo foo"
2099 ((a, b), c) = xxx_todo_changeme
2100 (d, e, f) = xxx_todo_changeme1
2101 x = 5"""
2102 self.check(b, a)
2103
2104 def test_lambda_no_change(self):
2105 s = """lambda x: x + 5"""
2106 self.unchanged(s)
2107
2108 def test_lambda_parens_single_arg(self):
2109 b = """lambda (x): x + 5"""
2110 a = """lambda x: x + 5"""
2111 self.check(b, a)
2112
2113 b = """lambda(x): x + 5"""
2114 a = """lambda x: x + 5"""
2115 self.check(b, a)
2116
2117 b = """lambda ((((x)))): x + 5"""
2118 a = """lambda x: x + 5"""
2119 self.check(b, a)
2120
2121 b = """lambda((((x)))): x + 5"""
2122 a = """lambda x: x + 5"""
2123 self.check(b, a)
2124
2125 def test_lambda_simple(self):
2126 b = """lambda (x, y): x + f(y)"""
2127 a = """lambda x_y: x_y[0] + f(x_y[1])"""
2128 self.check(b, a)
2129
2130 b = """lambda(x, y): x + f(y)"""
2131 a = """lambda x_y: x_y[0] + f(x_y[1])"""
2132 self.check(b, a)
2133
2134 b = """lambda (((x, y))): x + f(y)"""
2135 a = """lambda x_y: x_y[0] + f(x_y[1])"""
2136 self.check(b, a)
2137
2138 b = """lambda(((x, y))): x + f(y)"""
2139 a = """lambda x_y: x_y[0] + f(x_y[1])"""
2140 self.check(b, a)
2141
2142 def test_lambda_one_tuple(self):
2143 b = """lambda (x,): x + f(x)"""
2144 a = """lambda x1: x1[0] + f(x1[0])"""
2145 self.check(b, a)
2146
2147 b = """lambda (((x,))): x + f(x)"""
2148 a = """lambda x1: x1[0] + f(x1[0])"""
2149 self.check(b, a)
2150
2151 def test_lambda_simple_multi_use(self):
2152 b = """lambda (x, y): x + x + f(x) + x"""
2153 a = """lambda x_y: x_y[0] + x_y[0] + f(x_y[0]) + x_y[0]"""
2154 self.check(b, a)
2155
2156 def test_lambda_simple_reverse(self):
2157 b = """lambda (x, y): y + x"""
2158 a = """lambda x_y: x_y[1] + x_y[0]"""
2159 self.check(b, a)
2160
2161 def test_lambda_nested(self):
2162 b = """lambda (x, (y, z)): x + y + z"""
2163 a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
2164 self.check(b, a)
2165
2166 b = """lambda (((x, (y, z)))): x + y + z"""
2167 a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
2168 self.check(b, a)
2169
2170 def test_lambda_nested_multi_use(self):
2171 b = """lambda (x, (y, z)): x + y + f(y)"""
2172 a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + f(x_y_z[1][0])"""
2173 self.check(b, a)
2174
2175class Test_methodattrs(FixerTestCase):
2176 fixer = "methodattrs"
2177
2178 attrs = ["func", "self", "class"]
2179
2180 def test(self):
2181 for attr in self.attrs:
2182 b = "a.im_%s" % attr
2183 if attr == "class":
2184 a = "a.__self__.__class__"
2185 else:
2186 a = "a.__%s__" % attr
2187 self.check(b, a)
2188
2189 b = "self.foo.im_%s.foo_bar" % attr
2190 if attr == "class":
2191 a = "self.foo.__self__.__class__.foo_bar"
2192 else:
2193 a = "self.foo.__%s__.foo_bar" % attr
2194 self.check(b, a)
2195
2196 def test_unchanged(self):
2197 for attr in self.attrs:
2198 s = "foo(im_%s + 5)" % attr
2199 self.unchanged(s)
2200
2201 s = "f(foo.__%s__)" % attr
2202 self.unchanged(s)
2203
2204 s = "f(foo.__%s__.foo)" % attr
2205 self.unchanged(s)
2206
Martin v. Löwisef04c442008-03-19 05:04:44 +00002207class Test_next(FixerTestCase):
2208 fixer = "next"
2209
2210 def test_1(self):
2211 b = """it.next()"""
2212 a = """next(it)"""
2213 self.check(b, a)
2214
2215 def test_2(self):
2216 b = """a.b.c.d.next()"""
2217 a = """next(a.b.c.d)"""
2218 self.check(b, a)
2219
2220 def test_3(self):
2221 b = """(a + b).next()"""
2222 a = """next((a + b))"""
2223 self.check(b, a)
2224
2225 def test_4(self):
2226 b = """a().next()"""
2227 a = """next(a())"""
2228 self.check(b, a)
2229
2230 def test_5(self):
2231 b = """a().next() + b"""
2232 a = """next(a()) + b"""
2233 self.check(b, a)
2234
2235 def test_6(self):
2236 b = """c( a().next() + b)"""
2237 a = """c( next(a()) + b)"""
2238 self.check(b, a)
2239
2240 def test_prefix_preservation_1(self):
2241 b = """
2242 for a in b:
2243 foo(a)
2244 a.next()
2245 """
2246 a = """
2247 for a in b:
2248 foo(a)
2249 next(a)
2250 """
2251 self.check(b, a)
2252
2253 def test_prefix_preservation_2(self):
2254 b = """
2255 for a in b:
2256 foo(a) # abc
2257 # def
2258 a.next()
2259 """
2260 a = """
2261 for a in b:
2262 foo(a) # abc
2263 # def
2264 next(a)
2265 """
2266 self.check(b, a)
2267
2268 def test_prefix_preservation_3(self):
2269 b = """
2270 next = 5
2271 for a in b:
2272 foo(a)
2273 a.next()
2274 """
2275 a = """
2276 next = 5
2277 for a in b:
2278 foo(a)
2279 a.__next__()
2280 """
2281 self.check(b, a, ignore_warnings=True)
2282
2283 def test_prefix_preservation_4(self):
2284 b = """
2285 next = 5
2286 for a in b:
2287 foo(a) # abc
2288 # def
2289 a.next()
2290 """
2291 a = """
2292 next = 5
2293 for a in b:
2294 foo(a) # abc
2295 # def
2296 a.__next__()
2297 """
2298 self.check(b, a, ignore_warnings=True)
2299
2300 def test_prefix_preservation_5(self):
2301 b = """
2302 next = 5
2303 for a in b:
2304 foo(foo(a), # abc
2305 a.next())
2306 """
2307 a = """
2308 next = 5
2309 for a in b:
2310 foo(foo(a), # abc
2311 a.__next__())
2312 """
2313 self.check(b, a, ignore_warnings=True)
2314
2315 def test_prefix_preservation_6(self):
2316 b = """
2317 for a in b:
2318 foo(foo(a), # abc
2319 a.next())
2320 """
2321 a = """
2322 for a in b:
2323 foo(foo(a), # abc
2324 next(a))
2325 """
2326 self.check(b, a)
2327
2328 def test_method_1(self):
2329 b = """
2330 class A:
2331 def next(self):
2332 pass
2333 """
2334 a = """
2335 class A:
2336 def __next__(self):
2337 pass
2338 """
2339 self.check(b, a)
2340
2341 def test_method_2(self):
2342 b = """
2343 class A(object):
2344 def next(self):
2345 pass
2346 """
2347 a = """
2348 class A(object):
2349 def __next__(self):
2350 pass
2351 """
2352 self.check(b, a)
2353
2354 def test_method_3(self):
2355 b = """
2356 class A:
2357 def next(x):
2358 pass
2359 """
2360 a = """
2361 class A:
2362 def __next__(x):
2363 pass
2364 """
2365 self.check(b, a)
2366
2367 def test_method_4(self):
2368 b = """
2369 class A:
2370 def __init__(self, foo):
2371 self.foo = foo
2372
2373 def next(self):
2374 pass
2375
2376 def __iter__(self):
2377 return self
2378 """
2379 a = """
2380 class A:
2381 def __init__(self, foo):
2382 self.foo = foo
2383
2384 def __next__(self):
2385 pass
2386
2387 def __iter__(self):
2388 return self
2389 """
2390 self.check(b, a)
2391
2392 def test_method_unchanged(self):
2393 s = """
2394 class A:
2395 def next(self, a, b):
2396 pass
2397 """
2398 self.unchanged(s)
2399
2400 def test_shadowing_assign_simple(self):
2401 s = """
2402 next = foo
2403
2404 class A:
2405 def next(self, a, b):
2406 pass
2407 """
2408 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2409
2410 def test_shadowing_assign_tuple_1(self):
2411 s = """
2412 (next, a) = foo
2413
2414 class A:
2415 def next(self, a, b):
2416 pass
2417 """
2418 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2419
2420 def test_shadowing_assign_tuple_2(self):
2421 s = """
2422 (a, (b, (next, c)), a) = foo
2423
2424 class A:
2425 def next(self, a, b):
2426 pass
2427 """
2428 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2429
2430 def test_shadowing_assign_list_1(self):
2431 s = """
2432 [next, a] = foo
2433
2434 class A:
2435 def next(self, a, b):
2436 pass
2437 """
2438 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2439
2440 def test_shadowing_assign_list_2(self):
2441 s = """
2442 [a, [b, [next, c]], a] = foo
2443
2444 class A:
2445 def next(self, a, b):
2446 pass
2447 """
2448 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2449
2450 def test_builtin_assign(self):
2451 s = """
2452 def foo():
2453 __builtin__.next = foo
2454
2455 class A:
2456 def next(self, a, b):
2457 pass
2458 """
2459 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2460
2461 def test_builtin_assign_in_tuple(self):
2462 s = """
2463 def foo():
2464 (a, __builtin__.next) = foo
2465
2466 class A:
2467 def next(self, a, b):
2468 pass
2469 """
2470 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2471
2472 def test_builtin_assign_in_list(self):
2473 s = """
2474 def foo():
2475 [a, __builtin__.next] = foo
2476
2477 class A:
2478 def next(self, a, b):
2479 pass
2480 """
2481 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2482
2483 def test_assign_to_next(self):
2484 s = """
2485 def foo():
2486 A.next = foo
2487
2488 class A:
2489 def next(self, a, b):
2490 pass
2491 """
2492 self.unchanged(s)
2493
2494 def test_assign_to_next_in_tuple(self):
2495 s = """
2496 def foo():
2497 (a, A.next) = foo
2498
2499 class A:
2500 def next(self, a, b):
2501 pass
2502 """
2503 self.unchanged(s)
2504
2505 def test_assign_to_next_in_list(self):
2506 s = """
2507 def foo():
2508 [a, A.next] = foo
2509
2510 class A:
2511 def next(self, a, b):
2512 pass
2513 """
2514 self.unchanged(s)
2515
2516 def test_shadowing_import_1(self):
2517 s = """
2518 import foo.bar as next
2519
2520 class A:
2521 def next(self, a, b):
2522 pass
2523 """
2524 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2525
2526 def test_shadowing_import_2(self):
2527 s = """
2528 import bar, bar.foo as next
2529
2530 class A:
2531 def next(self, a, b):
2532 pass
2533 """
2534 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2535
2536 def test_shadowing_import_3(self):
2537 s = """
2538 import bar, bar.foo as next, baz
2539
2540 class A:
2541 def next(self, a, b):
2542 pass
2543 """
2544 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2545
2546 def test_shadowing_import_from_1(self):
2547 s = """
2548 from x import next
2549
2550 class A:
2551 def next(self, a, b):
2552 pass
2553 """
2554 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2555
2556 def test_shadowing_import_from_2(self):
2557 s = """
2558 from x.a import next
2559
2560 class A:
2561 def next(self, a, b):
2562 pass
2563 """
2564 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2565
2566 def test_shadowing_import_from_3(self):
2567 s = """
2568 from x import a, next, b
2569
2570 class A:
2571 def next(self, a, b):
2572 pass
2573 """
2574 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2575
2576 def test_shadowing_import_from_4(self):
2577 s = """
2578 from x.a import a, next, b
2579
2580 class A:
2581 def next(self, a, b):
2582 pass
2583 """
2584 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2585
2586 def test_shadowing_funcdef_1(self):
2587 s = """
2588 def next(a):
2589 pass
2590
2591 class A:
2592 def next(self, a, b):
2593 pass
2594 """
2595 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2596
2597 def test_shadowing_funcdef_2(self):
2598 b = """
2599 def next(a):
2600 pass
2601
2602 class A:
2603 def next(self):
2604 pass
2605
2606 it.next()
2607 """
2608 a = """
2609 def next(a):
2610 pass
2611
2612 class A:
2613 def __next__(self):
2614 pass
2615
2616 it.__next__()
2617 """
2618 self.warns(b, a, "Calls to builtin next() possibly shadowed")
2619
2620 def test_shadowing_global_1(self):
2621 s = """
2622 def f():
2623 global next
2624 next = 5
2625 """
2626 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2627
2628 def test_shadowing_global_2(self):
2629 s = """
2630 def f():
2631 global a, next, b
2632 next = 5
2633 """
2634 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2635
2636 def test_shadowing_for_simple(self):
2637 s = """
2638 for next in it():
2639 pass
2640
2641 b = 5
2642 c = 6
2643 """
2644 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2645
2646 def test_shadowing_for_tuple_1(self):
2647 s = """
2648 for next, b in it():
2649 pass
2650
2651 b = 5
2652 c = 6
2653 """
2654 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2655
2656 def test_shadowing_for_tuple_2(self):
2657 s = """
2658 for a, (next, c), b in it():
2659 pass
2660
2661 b = 5
2662 c = 6
2663 """
2664 self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
2665
2666 def test_noncall_access_1(self):
2667 b = """gnext = g.next"""
2668 a = """gnext = g.__next__"""
2669 self.check(b, a)
2670
2671 def test_noncall_access_2(self):
2672 b = """f(g.next + 5)"""
2673 a = """f(g.__next__ + 5)"""
2674 self.check(b, a)
2675
2676 def test_noncall_access_3(self):
2677 b = """f(g().next + 5)"""
2678 a = """f(g().__next__ + 5)"""
2679 self.check(b, a)
2680
2681class Test_nonzero(FixerTestCase):
2682 fixer = "nonzero"
2683
2684 def test_1(self):
2685 b = """
2686 class A:
2687 def __nonzero__(self):
2688 pass
2689 """
2690 a = """
2691 class A:
2692 def __bool__(self):
2693 pass
2694 """
2695 self.check(b, a)
2696
2697 def test_2(self):
2698 b = """
2699 class A(object):
2700 def __nonzero__(self):
2701 pass
2702 """
2703 a = """
2704 class A(object):
2705 def __bool__(self):
2706 pass
2707 """
2708 self.check(b, a)
2709
2710 def test_unchanged_1(self):
2711 s = """
2712 class A(object):
2713 def __bool__(self):
2714 pass
2715 """
2716 self.unchanged(s)
2717
2718 def test_unchanged_2(self):
2719 s = """
2720 class A(object):
2721 def __nonzero__(self, a):
2722 pass
2723 """
2724 self.unchanged(s)
2725
2726 def test_unchanged_func(self):
2727 s = """
2728 def __nonzero__(self):
2729 pass
2730 """
2731 self.unchanged(s)
2732
2733class Test_numliterals(FixerTestCase):
2734 fixer = "numliterals"
2735
2736 def test_octal_1(self):
2737 b = """0755"""
2738 a = """0o755"""
2739 self.check(b, a)
2740
2741 def test_long_int_1(self):
2742 b = """a = 12L"""
2743 a = """a = 12"""
2744 self.check(b, a)
2745
2746 def test_long_int_2(self):
2747 b = """a = 12l"""
2748 a = """a = 12"""
2749 self.check(b, a)
2750
2751 def test_long_hex(self):
2752 b = """b = 0x12l"""
2753 a = """b = 0x12"""
2754 self.check(b, a)
2755
Benjamin Peterson3a2fb142008-09-13 18:37:09 +00002756 def test_comments_and_spacing(self):
2757 b = """b = 0x12L"""
2758 a = """b = 0x12"""
2759 self.check(b, a)
2760
2761 b = """b = 0755 # spam"""
2762 a = """b = 0o755 # spam"""
2763 self.check(b, a)
2764
Martin v. Löwisef04c442008-03-19 05:04:44 +00002765 def test_unchanged_int(self):
2766 s = """5"""
2767 self.unchanged(s)
2768
2769 def test_unchanged_float(self):
2770 s = """5.0"""
2771 self.unchanged(s)
2772
2773 def test_unchanged_octal(self):
2774 s = """0o755"""
2775 self.unchanged(s)
2776
2777 def test_unchanged_hex(self):
2778 s = """0xABC"""
2779 self.unchanged(s)
2780
2781 def test_unchanged_exp(self):
2782 s = """5.0e10"""
2783 self.unchanged(s)
2784
2785 def test_unchanged_complex_int(self):
2786 s = """5 + 4j"""
2787 self.unchanged(s)
2788
2789 def test_unchanged_complex_float(self):
2790 s = """5.4 + 4.9j"""
2791 self.unchanged(s)
2792
2793 def test_unchanged_complex_bare(self):
2794 s = """4j"""
2795 self.unchanged(s)
2796 s = """4.4j"""
2797 self.unchanged(s)
2798
2799class Test_renames(FixerTestCase):
2800 fixer = "renames"
2801
2802 modules = {"sys": ("maxint", "maxsize"),
2803 }
2804
2805 def test_import_from(self):
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +00002806 for mod, (old, new) in list(self.modules.items()):
Martin v. Löwisef04c442008-03-19 05:04:44 +00002807 b = "from %s import %s" % (mod, old)
2808 a = "from %s import %s" % (mod, new)
2809 self.check(b, a)
2810
2811 s = "from foo import %s" % old
2812 self.unchanged(s)
2813
2814 def test_import_from_as(self):
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +00002815 for mod, (old, new) in list(self.modules.items()):
Martin v. Löwisef04c442008-03-19 05:04:44 +00002816 b = "from %s import %s as foo_bar" % (mod, old)
2817 a = "from %s import %s as foo_bar" % (mod, new)
2818 self.check(b, a)
2819
2820 def test_import_module_usage(self):
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +00002821 for mod, (old, new) in list(self.modules.items()):
Martin v. Löwisef04c442008-03-19 05:04:44 +00002822 b = """
2823 import %s
2824 foo(%s, %s.%s)
2825 """ % (mod, mod, mod, old)
2826 a = """
2827 import %s
2828 foo(%s, %s.%s)
2829 """ % (mod, mod, mod, new)
2830 self.check(b, a)
2831
2832 def XXX_test_from_import_usage(self):
2833 # not implemented yet
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +00002834 for mod, (old, new) in list(self.modules.items()):
Martin v. Löwisef04c442008-03-19 05:04:44 +00002835 b = """
2836 from %s import %s
2837 foo(%s, %s)
2838 """ % (mod, old, mod, old)
2839 a = """
2840 from %s import %s
2841 foo(%s, %s)
2842 """ % (mod, new, mod, new)
2843 self.check(b, a)
2844
Martin v. Löwisef04c442008-03-19 05:04:44 +00002845class Test_unicode(FixerTestCase):
2846 fixer = "unicode"
2847
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +00002848 def test_whitespace(self):
2849 b = """unicode( x)"""
2850 a = """str( x)"""
2851 self.check(b, a)
2852
2853 b = """ unicode(x )"""
2854 a = """ str(x )"""
2855 self.check(b, a)
2856
2857 b = """ u'h'"""
2858 a = """ 'h'"""
2859 self.check(b, a)
2860
Martin v. Löwisef04c442008-03-19 05:04:44 +00002861 def test_unicode_call(self):
2862 b = """unicode(x, y, z)"""
2863 a = """str(x, y, z)"""
2864 self.check(b, a)
2865
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +00002866 def test_unichr(self):
2867 b = """unichr(u'h')"""
2868 a = """chr('h')"""
2869 self.check(b, a)
2870
Martin v. Löwisef04c442008-03-19 05:04:44 +00002871 def test_unicode_literal_1(self):
2872 b = '''u"x"'''
2873 a = '''"x"'''
2874 self.check(b, a)
2875
2876 def test_unicode_literal_2(self):
2877 b = """ur'x'"""
2878 a = """r'x'"""
2879 self.check(b, a)
2880
2881 def test_unicode_literal_3(self):
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +00002882 b = """UR'''x''' """
2883 a = """R'''x''' """
Martin v. Löwisef04c442008-03-19 05:04:44 +00002884 self.check(b, a)
2885
2886class Test_callable(FixerTestCase):
2887 fixer = "callable"
2888
2889 def test_prefix_preservation(self):
2890 b = """callable( x)"""
Benjamin Petersond56a5d72009-12-29 00:44:14 +00002891 a = """import collections\nisinstance( x, collections.Callable)"""
Martin v. Löwisef04c442008-03-19 05:04:44 +00002892 self.check(b, a)
2893
2894 b = """if callable(x): pass"""
Benjamin Petersond56a5d72009-12-29 00:44:14 +00002895 a = """import collections
2896if isinstance(x, collections.Callable): pass"""
Martin v. Löwisef04c442008-03-19 05:04:44 +00002897 self.check(b, a)
2898
2899 def test_callable_call(self):
2900 b = """callable(x)"""
Benjamin Petersond56a5d72009-12-29 00:44:14 +00002901 a = """import collections\nisinstance(x, collections.Callable)"""
2902 self.check(b, a)
2903
2904 def test_global_import(self):
2905 b = """
2906def spam(foo):
2907 callable(foo)"""[1:]
2908 a = """
2909import collections
2910def spam(foo):
2911 isinstance(foo, collections.Callable)"""[1:]
2912 self.check(b, a)
2913
2914 b = """
2915import collections
2916def spam(foo):
2917 callable(foo)"""[1:]
2918 # same output if it was already imported
2919 self.check(b, a)
2920
2921 b = """
2922from collections import *
2923def spam(foo):
2924 callable(foo)"""[1:]
2925 a = """
2926from collections import *
2927import collections
2928def spam(foo):
2929 isinstance(foo, collections.Callable)"""[1:]
2930 self.check(b, a)
2931
2932 b = """
2933do_stuff()
2934do_some_other_stuff()
2935assert callable(do_stuff)"""[1:]
2936 a = """
2937import collections
2938do_stuff()
2939do_some_other_stuff()
2940assert isinstance(do_stuff, collections.Callable)"""[1:]
2941 self.check(b, a)
2942
2943 b = """
2944if isinstance(do_stuff, Callable):
2945 assert callable(do_stuff)
2946 do_stuff(do_stuff)
2947 if not callable(do_stuff):
2948 exit(1)
2949 else:
2950 assert callable(do_stuff)
2951else:
2952 assert not callable(do_stuff)"""[1:]
2953 a = """
2954import collections
2955if isinstance(do_stuff, Callable):
2956 assert isinstance(do_stuff, collections.Callable)
2957 do_stuff(do_stuff)
2958 if not isinstance(do_stuff, collections.Callable):
2959 exit(1)
2960 else:
2961 assert isinstance(do_stuff, collections.Callable)
2962else:
2963 assert not isinstance(do_stuff, collections.Callable)"""[1:]
Martin v. Löwisef04c442008-03-19 05:04:44 +00002964 self.check(b, a)
2965
2966 def test_callable_should_not_change(self):
2967 a = """callable(*x)"""
2968 self.unchanged(a)
2969
2970 a = """callable(x, y)"""
2971 self.unchanged(a)
2972
2973 a = """callable(x, kw=y)"""
2974 self.unchanged(a)
2975
2976 a = """callable()"""
2977 self.unchanged(a)
2978
2979class Test_filter(FixerTestCase):
2980 fixer = "filter"
2981
2982 def test_prefix_preservation(self):
2983 b = """x = filter( foo, 'abc' )"""
2984 a = """x = list(filter( foo, 'abc' ))"""
2985 self.check(b, a)
2986
2987 b = """x = filter( None , 'abc' )"""
2988 a = """x = [_f for _f in 'abc' if _f]"""
2989 self.check(b, a)
2990
2991 def test_filter_basic(self):
2992 b = """x = filter(None, 'abc')"""
2993 a = """x = [_f for _f in 'abc' if _f]"""
2994 self.check(b, a)
2995
2996 b = """x = len(filter(f, 'abc'))"""
2997 a = """x = len(list(filter(f, 'abc')))"""
2998 self.check(b, a)
2999
3000 b = """x = filter(lambda x: x%2 == 0, range(10))"""
3001 a = """x = [x for x in range(10) if x%2 == 0]"""
3002 self.check(b, a)
3003
3004 # Note the parens around x
3005 b = """x = filter(lambda (x): x%2 == 0, range(10))"""
3006 a = """x = [x for x in range(10) if x%2 == 0]"""
3007 self.check(b, a)
3008
3009 # XXX This (rare) case is not supported
3010## b = """x = filter(f, 'abc')[0]"""
3011## a = """x = list(filter(f, 'abc'))[0]"""
3012## self.check(b, a)
3013
3014 def test_filter_nochange(self):
3015 a = """b.join(filter(f, 'abc'))"""
3016 self.unchanged(a)
3017 a = """(a + foo(5)).join(filter(f, 'abc'))"""
3018 self.unchanged(a)
3019 a = """iter(filter(f, 'abc'))"""
3020 self.unchanged(a)
3021 a = """list(filter(f, 'abc'))"""
3022 self.unchanged(a)
3023 a = """list(filter(f, 'abc'))[0]"""
3024 self.unchanged(a)
3025 a = """set(filter(f, 'abc'))"""
3026 self.unchanged(a)
3027 a = """set(filter(f, 'abc')).pop()"""
3028 self.unchanged(a)
3029 a = """tuple(filter(f, 'abc'))"""
3030 self.unchanged(a)
3031 a = """any(filter(f, 'abc'))"""
3032 self.unchanged(a)
3033 a = """all(filter(f, 'abc'))"""
3034 self.unchanged(a)
3035 a = """sum(filter(f, 'abc'))"""
3036 self.unchanged(a)
3037 a = """sorted(filter(f, 'abc'))"""
3038 self.unchanged(a)
3039 a = """sorted(filter(f, 'abc'), key=blah)"""
3040 self.unchanged(a)
3041 a = """sorted(filter(f, 'abc'), key=blah)[0]"""
3042 self.unchanged(a)
Benjamin Peterson57af3872012-11-29 10:55:22 -05003043 a = """enumerate(filter(f, 'abc'))"""
3044 self.unchanged(a)
3045 a = """enumerate(filter(f, 'abc'), start=1)"""
3046 self.unchanged(a)
Martin v. Löwisef04c442008-03-19 05:04:44 +00003047 a = """for i in filter(f, 'abc'): pass"""
3048 self.unchanged(a)
3049 a = """[x for x in filter(f, 'abc')]"""
3050 self.unchanged(a)
3051 a = """(x for x in filter(f, 'abc'))"""
3052 self.unchanged(a)
3053
3054 def test_future_builtins(self):
3055 a = "from future_builtins import spam, filter; filter(f, 'ham')"
3056 self.unchanged(a)
3057
3058 b = """from future_builtins import spam; x = filter(f, 'abc')"""
3059 a = """from future_builtins import spam; x = list(filter(f, 'abc'))"""
3060 self.check(b, a)
3061
3062 a = "from future_builtins import *; filter(f, 'ham')"
3063 self.unchanged(a)
3064
3065class Test_map(FixerTestCase):
3066 fixer = "map"
3067
3068 def check(self, b, a):
3069 self.unchanged("from future_builtins import map; " + b, a)
Martin v. Löwis64903f92008-11-25 03:08:21 +00003070 super(Test_map, self).check(b, a)
Martin v. Löwisef04c442008-03-19 05:04:44 +00003071
3072 def test_prefix_preservation(self):
3073 b = """x = map( f, 'abc' )"""
3074 a = """x = list(map( f, 'abc' ))"""
3075 self.check(b, a)
3076
3077 def test_trailing_comment(self):
3078 b = """x = map(f, 'abc') # foo"""
3079 a = """x = list(map(f, 'abc')) # foo"""
3080 self.check(b, a)
3081
Benjamin Petersone80b51f2009-11-02 18:33:36 +00003082 def test_None_with_multiple_arguments(self):
3083 s = """x = map(None, a, b, c)"""
3084 self.warns_unchanged(s, "cannot convert map(None, ...) with "
3085 "multiple arguments")
3086
Martin v. Löwisef04c442008-03-19 05:04:44 +00003087 def test_map_basic(self):
3088 b = """x = map(f, 'abc')"""
3089 a = """x = list(map(f, 'abc'))"""
3090 self.check(b, a)
3091
3092 b = """x = len(map(f, 'abc', 'def'))"""
3093 a = """x = len(list(map(f, 'abc', 'def')))"""
3094 self.check(b, a)
3095
3096 b = """x = map(None, 'abc')"""
3097 a = """x = list('abc')"""
3098 self.check(b, a)
3099
Martin v. Löwisef04c442008-03-19 05:04:44 +00003100 b = """x = map(lambda x: x+1, range(4))"""
3101 a = """x = [x+1 for x in range(4)]"""
3102 self.check(b, a)
3103
3104 # Note the parens around x
3105 b = """x = map(lambda (x): x+1, range(4))"""
3106 a = """x = [x+1 for x in range(4)]"""
3107 self.check(b, a)
3108
3109 b = """
3110 foo()
3111 # foo
3112 map(f, x)
3113 """
3114 a = """
3115 foo()
3116 # foo
3117 list(map(f, x))
3118 """
3119 self.warns(b, a, "You should use a for loop here")
3120
3121 # XXX This (rare) case is not supported
3122## b = """x = map(f, 'abc')[0]"""
3123## a = """x = list(map(f, 'abc'))[0]"""
3124## self.check(b, a)
3125
3126 def test_map_nochange(self):
3127 a = """b.join(map(f, 'abc'))"""
3128 self.unchanged(a)
3129 a = """(a + foo(5)).join(map(f, 'abc'))"""
3130 self.unchanged(a)
3131 a = """iter(map(f, 'abc'))"""
3132 self.unchanged(a)
3133 a = """list(map(f, 'abc'))"""
3134 self.unchanged(a)
3135 a = """list(map(f, 'abc'))[0]"""
3136 self.unchanged(a)
3137 a = """set(map(f, 'abc'))"""
3138 self.unchanged(a)
3139 a = """set(map(f, 'abc')).pop()"""
3140 self.unchanged(a)
3141 a = """tuple(map(f, 'abc'))"""
3142 self.unchanged(a)
3143 a = """any(map(f, 'abc'))"""
3144 self.unchanged(a)
3145 a = """all(map(f, 'abc'))"""
3146 self.unchanged(a)
3147 a = """sum(map(f, 'abc'))"""
3148 self.unchanged(a)
3149 a = """sorted(map(f, 'abc'))"""
3150 self.unchanged(a)
3151 a = """sorted(map(f, 'abc'), key=blah)"""
3152 self.unchanged(a)
3153 a = """sorted(map(f, 'abc'), key=blah)[0]"""
3154 self.unchanged(a)
Benjamin Peterson57af3872012-11-29 10:55:22 -05003155 a = """enumerate(map(f, 'abc'))"""
3156 self.unchanged(a)
3157 a = """enumerate(map(f, 'abc'), start=1)"""
3158 self.unchanged(a)
Martin v. Löwisef04c442008-03-19 05:04:44 +00003159 a = """for i in map(f, 'abc'): pass"""
3160 self.unchanged(a)
3161 a = """[x for x in map(f, 'abc')]"""
3162 self.unchanged(a)
3163 a = """(x for x in map(f, 'abc'))"""
3164 self.unchanged(a)
3165
3166 def test_future_builtins(self):
3167 a = "from future_builtins import spam, map, eggs; map(f, 'ham')"
3168 self.unchanged(a)
3169
3170 b = """from future_builtins import spam, eggs; x = map(f, 'abc')"""
3171 a = """from future_builtins import spam, eggs; x = list(map(f, 'abc'))"""
3172 self.check(b, a)
3173
3174 a = "from future_builtins import *; map(f, 'ham')"
3175 self.unchanged(a)
3176
Martin v. Löwisf733c602008-03-19 05:26:18 +00003177class Test_zip(FixerTestCase):
3178 fixer = "zip"
3179
3180 def check(self, b, a):
3181 self.unchanged("from future_builtins import zip; " + b, a)
Martin v. Löwis64903f92008-11-25 03:08:21 +00003182 super(Test_zip, self).check(b, a)
Martin v. Löwisf733c602008-03-19 05:26:18 +00003183
3184 def test_zip_basic(self):
3185 b = """x = zip(a, b, c)"""
3186 a = """x = list(zip(a, b, c))"""
3187 self.check(b, a)
3188
3189 b = """x = len(zip(a, b))"""
3190 a = """x = len(list(zip(a, b)))"""
3191 self.check(b, a)
3192
3193 def test_zip_nochange(self):
3194 a = """b.join(zip(a, b))"""
3195 self.unchanged(a)
3196 a = """(a + foo(5)).join(zip(a, b))"""
3197 self.unchanged(a)
3198 a = """iter(zip(a, b))"""
3199 self.unchanged(a)
3200 a = """list(zip(a, b))"""
3201 self.unchanged(a)
3202 a = """list(zip(a, b))[0]"""
3203 self.unchanged(a)
3204 a = """set(zip(a, b))"""
3205 self.unchanged(a)
3206 a = """set(zip(a, b)).pop()"""
3207 self.unchanged(a)
3208 a = """tuple(zip(a, b))"""
3209 self.unchanged(a)
3210 a = """any(zip(a, b))"""
3211 self.unchanged(a)
3212 a = """all(zip(a, b))"""
3213 self.unchanged(a)
3214 a = """sum(zip(a, b))"""
3215 self.unchanged(a)
3216 a = """sorted(zip(a, b))"""
3217 self.unchanged(a)
3218 a = """sorted(zip(a, b), key=blah)"""
3219 self.unchanged(a)
3220 a = """sorted(zip(a, b), key=blah)[0]"""
3221 self.unchanged(a)
Benjamin Peterson57af3872012-11-29 10:55:22 -05003222 a = """enumerate(zip(a, b))"""
3223 self.unchanged(a)
3224 a = """enumerate(zip(a, b), start=1)"""
3225 self.unchanged(a)
Martin v. Löwisf733c602008-03-19 05:26:18 +00003226 a = """for i in zip(a, b): pass"""
3227 self.unchanged(a)
3228 a = """[x for x in zip(a, b)]"""
3229 self.unchanged(a)
3230 a = """(x for x in zip(a, b))"""
3231 self.unchanged(a)
3232
3233 def test_future_builtins(self):
3234 a = "from future_builtins import spam, zip, eggs; zip(a, b)"
3235 self.unchanged(a)
3236
3237 b = """from future_builtins import spam, eggs; x = zip(a, b)"""
3238 a = """from future_builtins import spam, eggs; x = list(zip(a, b))"""
3239 self.check(b, a)
3240
3241 a = "from future_builtins import *; zip(a, b)"
3242 self.unchanged(a)
3243
Martin v. Löwisef04c442008-03-19 05:04:44 +00003244class Test_standarderror(FixerTestCase):
3245 fixer = "standarderror"
3246
3247 def test(self):
3248 b = """x = StandardError()"""
3249 a = """x = Exception()"""
3250 self.check(b, a)
3251
3252 b = """x = StandardError(a, b, c)"""
3253 a = """x = Exception(a, b, c)"""
3254 self.check(b, a)
3255
3256 b = """f(2 + StandardError(a, b, c))"""
3257 a = """f(2 + Exception(a, b, c))"""
3258 self.check(b, a)
3259
3260class Test_types(FixerTestCase):
3261 fixer = "types"
3262
3263 def test_basic_types_convert(self):
3264 b = """types.StringType"""
3265 a = """bytes"""
3266 self.check(b, a)
3267
3268 b = """types.DictType"""
3269 a = """dict"""
3270 self.check(b, a)
3271
3272 b = """types . IntType"""
3273 a = """int"""
3274 self.check(b, a)
3275
3276 b = """types.ListType"""
3277 a = """list"""
3278 self.check(b, a)
3279
3280 b = """types.LongType"""
3281 a = """int"""
3282 self.check(b, a)
3283
3284 b = """types.NoneType"""
3285 a = """type(None)"""
3286 self.check(b, a)
3287
3288class Test_idioms(FixerTestCase):
3289 fixer = "idioms"
3290
3291 def test_while(self):
3292 b = """while 1: foo()"""
3293 a = """while True: foo()"""
3294 self.check(b, a)
3295
3296 b = """while 1: foo()"""
3297 a = """while True: foo()"""
3298 self.check(b, a)
3299
3300 b = """
3301 while 1:
3302 foo()
3303 """
3304 a = """
3305 while True:
3306 foo()
3307 """
3308 self.check(b, a)
3309
3310 def test_while_unchanged(self):
3311 s = """while 11: foo()"""
3312 self.unchanged(s)
3313
3314 s = """while 0: foo()"""
3315 self.unchanged(s)
3316
3317 s = """while foo(): foo()"""
3318 self.unchanged(s)
3319
3320 s = """while []: foo()"""
3321 self.unchanged(s)
3322
3323 def test_eq_simple(self):
3324 b = """type(x) == T"""
3325 a = """isinstance(x, T)"""
3326 self.check(b, a)
3327
3328 b = """if type(x) == T: pass"""
3329 a = """if isinstance(x, T): pass"""
3330 self.check(b, a)
3331
3332 def test_eq_reverse(self):
3333 b = """T == type(x)"""
3334 a = """isinstance(x, T)"""
3335 self.check(b, a)
3336
3337 b = """if T == type(x): pass"""
3338 a = """if isinstance(x, T): pass"""
3339 self.check(b, a)
3340
3341 def test_eq_expression(self):
3342 b = """type(x+y) == d.get('T')"""
3343 a = """isinstance(x+y, d.get('T'))"""
3344 self.check(b, a)
3345
3346 b = """type( x + y) == d.get('T')"""
3347 a = """isinstance(x + y, d.get('T'))"""
3348 self.check(b, a)
3349
3350 def test_is_simple(self):
3351 b = """type(x) is T"""
3352 a = """isinstance(x, T)"""
3353 self.check(b, a)
3354
3355 b = """if type(x) is T: pass"""
3356 a = """if isinstance(x, T): pass"""
3357 self.check(b, a)
3358
3359 def test_is_reverse(self):
3360 b = """T is type(x)"""
3361 a = """isinstance(x, T)"""
3362 self.check(b, a)
3363
3364 b = """if T is type(x): pass"""
3365 a = """if isinstance(x, T): pass"""
3366 self.check(b, a)
3367
3368 def test_is_expression(self):
3369 b = """type(x+y) is d.get('T')"""
3370 a = """isinstance(x+y, d.get('T'))"""
3371 self.check(b, a)
3372
3373 b = """type( x + y) is d.get('T')"""
3374 a = """isinstance(x + y, d.get('T'))"""
3375 self.check(b, a)
3376
3377 def test_is_not_simple(self):
3378 b = """type(x) is not T"""
3379 a = """not isinstance(x, T)"""
3380 self.check(b, a)
3381
3382 b = """if type(x) is not T: pass"""
3383 a = """if not isinstance(x, T): pass"""
3384 self.check(b, a)
3385
3386 def test_is_not_reverse(self):
3387 b = """T is not type(x)"""
3388 a = """not isinstance(x, T)"""
3389 self.check(b, a)
3390
3391 b = """if T is not type(x): pass"""
3392 a = """if not isinstance(x, T): pass"""
3393 self.check(b, a)
3394
3395 def test_is_not_expression(self):
3396 b = """type(x+y) is not d.get('T')"""
3397 a = """not isinstance(x+y, d.get('T'))"""
3398 self.check(b, a)
3399
3400 b = """type( x + y) is not d.get('T')"""
3401 a = """not isinstance(x + y, d.get('T'))"""
3402 self.check(b, a)
3403
3404 def test_ne_simple(self):
3405 b = """type(x) != T"""
3406 a = """not isinstance(x, T)"""
3407 self.check(b, a)
3408
3409 b = """if type(x) != T: pass"""
3410 a = """if not isinstance(x, T): pass"""
3411 self.check(b, a)
3412
3413 def test_ne_reverse(self):
3414 b = """T != type(x)"""
3415 a = """not isinstance(x, T)"""
3416 self.check(b, a)
3417
3418 b = """if T != type(x): pass"""
3419 a = """if not isinstance(x, T): pass"""
3420 self.check(b, a)
3421
3422 def test_ne_expression(self):
3423 b = """type(x+y) != d.get('T')"""
3424 a = """not isinstance(x+y, d.get('T'))"""
3425 self.check(b, a)
3426
3427 b = """type( x + y) != d.get('T')"""
3428 a = """not isinstance(x + y, d.get('T'))"""
3429 self.check(b, a)
3430
3431 def test_type_unchanged(self):
3432 a = """type(x).__name__"""
3433 self.unchanged(a)
3434
3435 def test_sort_list_call(self):
3436 b = """
3437 v = list(t)
3438 v.sort()
3439 foo(v)
3440 """
3441 a = """
3442 v = sorted(t)
3443 foo(v)
3444 """
3445 self.check(b, a)
3446
3447 b = """
3448 v = list(foo(b) + d)
3449 v.sort()
3450 foo(v)
3451 """
3452 a = """
3453 v = sorted(foo(b) + d)
3454 foo(v)
3455 """
3456 self.check(b, a)
3457
3458 b = """
3459 while x:
3460 v = list(t)
3461 v.sort()
3462 foo(v)
3463 """
3464 a = """
3465 while x:
3466 v = sorted(t)
3467 foo(v)
3468 """
3469 self.check(b, a)
3470
3471 b = """
3472 v = list(t)
3473 # foo
3474 v.sort()
3475 foo(v)
3476 """
3477 a = """
3478 v = sorted(t)
3479 # foo
3480 foo(v)
3481 """
3482 self.check(b, a)
3483
3484 b = r"""
3485 v = list( t)
3486 v.sort()
3487 foo(v)
3488 """
3489 a = r"""
3490 v = sorted( t)
3491 foo(v)
3492 """
3493 self.check(b, a)
3494
Benjamin Petersone80b51f2009-11-02 18:33:36 +00003495 b = r"""
3496 try:
3497 m = list(s)
3498 m.sort()
3499 except: pass
3500 """
3501
3502 a = r"""
3503 try:
3504 m = sorted(s)
3505 except: pass
3506 """
3507 self.check(b, a)
3508
3509 b = r"""
3510 try:
3511 m = list(s)
3512 # foo
3513 m.sort()
3514 except: pass
3515 """
3516
3517 a = r"""
3518 try:
3519 m = sorted(s)
3520 # foo
3521 except: pass
3522 """
3523 self.check(b, a)
3524
3525 b = r"""
3526 m = list(s)
3527 # more comments
3528 m.sort()"""
3529
3530 a = r"""
3531 m = sorted(s)
3532 # more comments"""
3533 self.check(b, a)
3534
Martin v. Löwisef04c442008-03-19 05:04:44 +00003535 def test_sort_simple_expr(self):
3536 b = """
3537 v = t
3538 v.sort()
3539 foo(v)
3540 """
3541 a = """
3542 v = sorted(t)
3543 foo(v)
3544 """
3545 self.check(b, a)
3546
3547 b = """
3548 v = foo(b)
3549 v.sort()
3550 foo(v)
3551 """
3552 a = """
3553 v = sorted(foo(b))
3554 foo(v)
3555 """
3556 self.check(b, a)
3557
3558 b = """
3559 v = b.keys()
3560 v.sort()
3561 foo(v)
3562 """
3563 a = """
3564 v = sorted(b.keys())
3565 foo(v)
3566 """
3567 self.check(b, a)
3568
3569 b = """
3570 v = foo(b) + d
3571 v.sort()
3572 foo(v)
3573 """
3574 a = """
3575 v = sorted(foo(b) + d)
3576 foo(v)
3577 """
3578 self.check(b, a)
3579
3580 b = """
3581 while x:
3582 v = t
3583 v.sort()
3584 foo(v)
3585 """
3586 a = """
3587 while x:
3588 v = sorted(t)
3589 foo(v)
3590 """
3591 self.check(b, a)
3592
3593 b = """
3594 v = t
3595 # foo
3596 v.sort()
3597 foo(v)
3598 """
3599 a = """
3600 v = sorted(t)
3601 # foo
3602 foo(v)
3603 """
3604 self.check(b, a)
3605
3606 b = r"""
3607 v = t
3608 v.sort()
3609 foo(v)
3610 """
3611 a = r"""
3612 v = sorted(t)
3613 foo(v)
3614 """
3615 self.check(b, a)
3616
3617 def test_sort_unchanged(self):
3618 s = """
3619 v = list(t)
3620 w.sort()
3621 foo(w)
3622 """
3623 self.unchanged(s)
3624
3625 s = """
3626 v = list(t)
3627 v.sort(u)
3628 foo(v)
3629 """
3630 self.unchanged(s)
3631
Martin v. Löwisef04c442008-03-19 05:04:44 +00003632class Test_basestring(FixerTestCase):
3633 fixer = "basestring"
3634
3635 def test_basestring(self):
3636 b = """isinstance(x, basestring)"""
3637 a = """isinstance(x, str)"""
3638 self.check(b, a)
3639
Martin v. Löwisef04c442008-03-19 05:04:44 +00003640class Test_buffer(FixerTestCase):
3641 fixer = "buffer"
3642
3643 def test_buffer(self):
3644 b = """x = buffer(y)"""
3645 a = """x = memoryview(y)"""
3646 self.check(b, a)
3647
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +00003648 def test_slicing(self):
3649 b = """buffer(y)[4:5]"""
3650 a = """memoryview(y)[4:5]"""
3651 self.check(b, a)
3652
Martin v. Löwisef04c442008-03-19 05:04:44 +00003653class Test_future(FixerTestCase):
3654 fixer = "future"
3655
3656 def test_future(self):
3657 b = """from __future__ import braces"""
3658 a = """"""
3659 self.check(b, a)
3660
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003661 b = """# comment\nfrom __future__ import braces"""
3662 a = """# comment\n"""
3663 self.check(b, a)
3664
3665 b = """from __future__ import braces\n# comment"""
3666 a = """\n# comment"""
3667 self.check(b, a)
3668
3669 def test_run_order(self):
3670 self.assert_runs_after('print')
3671
Martin v. Löwisef04c442008-03-19 05:04:44 +00003672class Test_itertools(FixerTestCase):
3673 fixer = "itertools"
3674
3675 def checkall(self, before, after):
3676 # Because we need to check with and without the itertools prefix
3677 # and on each of the three functions, these loops make it all
3678 # much easier
3679 for i in ('itertools.', ''):
3680 for f in ('map', 'filter', 'zip'):
3681 b = before %(i+'i'+f)
3682 a = after %(f)
3683 self.check(b, a)
3684
3685 def test_0(self):
3686 # A simple example -- test_1 covers exactly the same thing,
3687 # but it's not quite as clear.
3688 b = "itertools.izip(a, b)"
3689 a = "zip(a, b)"
3690 self.check(b, a)
3691
3692 def test_1(self):
3693 b = """%s(f, a)"""
3694 a = """%s(f, a)"""
3695 self.checkall(b, a)
3696
Benjamin Peterson49d71492011-03-07 22:50:37 -06003697 def test_qualified(self):
Martin v. Löwisef04c442008-03-19 05:04:44 +00003698 b = """itertools.ifilterfalse(a, b)"""
3699 a = """itertools.filterfalse(a, b)"""
3700 self.check(b, a)
3701
Benjamin Peterson49d71492011-03-07 22:50:37 -06003702 b = """itertools.izip_longest(a, b)"""
3703 a = """itertools.zip_longest(a, b)"""
3704 self.check(b, a)
3705
3706 def test_2(self):
Martin v. Löwisef04c442008-03-19 05:04:44 +00003707 b = """ifilterfalse(a, b)"""
3708 a = """filterfalse(a, b)"""
3709 self.check(b, a)
3710
Benjamin Peterson49d71492011-03-07 22:50:37 -06003711 b = """izip_longest(a, b)"""
3712 a = """zip_longest(a, b)"""
3713 self.check(b, a)
3714
Martin v. Löwisef04c442008-03-19 05:04:44 +00003715 def test_space_1(self):
3716 b = """ %s(f, a)"""
3717 a = """ %s(f, a)"""
3718 self.checkall(b, a)
3719
3720 def test_space_2(self):
3721 b = """ itertools.ifilterfalse(a, b)"""
3722 a = """ itertools.filterfalse(a, b)"""
3723 self.check(b, a)
3724
Benjamin Peterson49d71492011-03-07 22:50:37 -06003725 b = """ itertools.izip_longest(a, b)"""
3726 a = """ itertools.zip_longest(a, b)"""
3727 self.check(b, a)
3728
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003729 def test_run_order(self):
3730 self.assert_runs_after('map', 'zip', 'filter')
3731
Benjamin Peterson49d71492011-03-07 22:50:37 -06003732
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003733class Test_itertools_imports(FixerTestCase):
3734 fixer = 'itertools_imports'
3735
3736 def test_reduced(self):
3737 b = "from itertools import imap, izip, foo"
3738 a = "from itertools import foo"
3739 self.check(b, a)
3740
3741 b = "from itertools import bar, imap, izip, foo"
3742 a = "from itertools import bar, foo"
3743 self.check(b, a)
3744
Benjamin Peterson68c80ed2010-08-08 19:23:25 +00003745 b = "from itertools import chain, imap, izip"
3746 a = "from itertools import chain"
3747 self.check(b, a)
3748
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003749 def test_comments(self):
3750 b = "#foo\nfrom itertools import imap, izip"
3751 a = "#foo\n"
3752 self.check(b, a)
3753
3754 def test_none(self):
3755 b = "from itertools import imap, izip"
3756 a = ""
3757 self.check(b, a)
3758
Martin v. Löwisa675ef12008-03-24 00:50:58 +00003759 b = "from itertools import izip"
3760 a = ""
3761 self.check(b, a)
3762
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003763 def test_import_as(self):
3764 b = "from itertools import izip, bar as bang, imap"
3765 a = "from itertools import bar as bang"
3766 self.check(b, a)
3767
Benjamin Peterson608d8bc2009-05-05 23:23:31 +00003768 b = "from itertools import izip as _zip, imap, bar"
3769 a = "from itertools import bar"
3770 self.check(b, a)
3771
3772 b = "from itertools import imap as _map"
3773 a = ""
3774 self.check(b, a)
3775
3776 b = "from itertools import imap as _map, izip as _zip"
3777 a = ""
3778 self.check(b, a)
3779
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003780 s = "from itertools import bar as bang"
3781 self.unchanged(s)
3782
Benjamin Peterson49d71492011-03-07 22:50:37 -06003783 def test_ifilter_and_zip_longest(self):
3784 for name in "filterfalse", "zip_longest":
3785 b = "from itertools import i%s" % (name,)
3786 a = "from itertools import %s" % (name,)
3787 self.check(b, a)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003788
Benjamin Peterson49d71492011-03-07 22:50:37 -06003789 b = "from itertools import imap, i%s, foo" % (name,)
3790 a = "from itertools import %s, foo" % (name,)
3791 self.check(b, a)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003792
Benjamin Peterson49d71492011-03-07 22:50:37 -06003793 b = "from itertools import bar, i%s, foo" % (name,)
3794 a = "from itertools import bar, %s, foo" % (name,)
3795 self.check(b, a)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003796
Benjamin Peterson1b84b5f2010-07-04 16:49:46 +00003797 def test_import_star(self):
3798 s = "from itertools import *"
3799 self.unchanged(s)
3800
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003801
3802 def test_unchanged(self):
3803 s = "from itertools import foo"
3804 self.unchanged(s)
3805
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +00003806
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003807class Test_import(FixerTestCase):
3808 fixer = "import"
3809
3810 def setUp(self):
Martin v. Löwis64903f92008-11-25 03:08:21 +00003811 super(Test_import, self).setUp()
Martin v. Löwise1e9f232008-04-01 06:17:46 +00003812 # Need to replace fix_import's exists method
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003813 # so we can check that it's doing the right thing
3814 self.files_checked = []
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003815 self.present_files = set()
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003816 self.always_exists = True
3817 def fake_exists(name):
3818 self.files_checked.append(name)
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003819 return self.always_exists or (name in self.present_files)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003820
Benjamin Petersonc9e833f2010-05-08 15:46:00 +00003821 from lib2to3.fixes import fix_import
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003822 fix_import.exists = fake_exists
3823
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003824 def tearDown(self):
3825 from lib2to3.fixes import fix_import
3826 fix_import.exists = os.path.exists
3827
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003828 def check_both(self, b, a):
3829 self.always_exists = True
Martin v. Löwis64903f92008-11-25 03:08:21 +00003830 super(Test_import, self).check(b, a)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003831 self.always_exists = False
Martin v. Löwis64903f92008-11-25 03:08:21 +00003832 super(Test_import, self).unchanged(b)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003833
3834 def test_files_checked(self):
3835 def p(path):
3836 # Takes a unix path and returns a path with correct separators
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003837 return os.path.pathsep.join(path.split("/"))
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003838
3839 self.always_exists = False
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003840 self.present_files = set(['__init__.py'])
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +00003841 expected_extensions = ('.py', os.path.sep, '.pyc', '.so', '.sl', '.pyd')
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003842 names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))
3843
3844 for name in names_to_test:
3845 self.files_checked = []
3846 self.filename = name
3847 self.unchanged("import jam")
3848
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003849 if os.path.dirname(name):
3850 name = os.path.dirname(name) + '/jam'
3851 else:
3852 name = 'jam'
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003853 expected_checks = set(name + ext for ext in expected_extensions)
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003854 expected_checks.add("__init__.py")
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003855
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003856 self.assertEqual(set(self.files_checked), expected_checks)
3857
3858 def test_not_in_package(self):
3859 s = "import bar"
3860 self.always_exists = False
3861 self.present_files = set(["bar.py"])
3862 self.unchanged(s)
3863
Benjamin Petersonc9e833f2010-05-08 15:46:00 +00003864 def test_with_absolute_import_enabled(self):
3865 s = "from __future__ import absolute_import\nimport bar"
3866 self.always_exists = False
3867 self.present_files = set(["__init__.py", "bar.py"])
3868 self.unchanged(s)
3869
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003870 def test_in_package(self):
3871 b = "import bar"
3872 a = "from . import bar"
3873 self.always_exists = False
3874 self.present_files = set(["__init__.py", "bar.py"])
3875 self.check(b, a)
3876
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +00003877 def test_import_from_package(self):
3878 b = "import bar"
3879 a = "from . import bar"
3880 self.always_exists = False
Benjamin Peterson784935f2009-07-21 13:13:16 +00003881 self.present_files = set(["__init__.py", "bar" + os.path.sep])
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +00003882 self.check(b, a)
3883
Benjamin Petersonc9e833f2010-05-08 15:46:00 +00003884 def test_already_relative_import(self):
3885 s = "from . import bar"
3886 self.unchanged(s)
3887
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00003888 def test_comments_and_indent(self):
3889 b = "import bar # Foo"
3890 a = "from . import bar # Foo"
3891 self.check(b, a)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003892
3893 def test_from(self):
Martin v. Löwisa675ef12008-03-24 00:50:58 +00003894 b = "from foo import bar, baz"
3895 a = "from .foo import bar, baz"
3896 self.check_both(b, a)
3897
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003898 b = "from foo import bar"
3899 a = "from .foo import bar"
3900 self.check_both(b, a)
3901
Benjamin Petersonba558182008-11-10 22:21:33 +00003902 b = "from foo import (bar, baz)"
3903 a = "from .foo import (bar, baz)"
3904 self.check_both(b, a)
3905
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003906 def test_dotted_from(self):
3907 b = "from green.eggs import ham"
3908 a = "from .green.eggs import ham"
3909 self.check_both(b, a)
3910
3911 def test_from_as(self):
3912 b = "from green.eggs import ham as spam"
3913 a = "from .green.eggs import ham as spam"
3914 self.check_both(b, a)
3915
3916 def test_import(self):
3917 b = "import foo"
Martin v. Löwisa675ef12008-03-24 00:50:58 +00003918 a = "from . import foo"
3919 self.check_both(b, a)
3920
3921 b = "import foo, bar"
3922 a = "from . import foo, bar"
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003923 self.check_both(b, a)
3924
Benjamin Peterson8bcddca2009-01-03 16:53:14 +00003925 b = "import foo, bar, x"
3926 a = "from . import foo, bar, x"
3927 self.check_both(b, a)
3928
3929 b = "import x, y, z"
3930 a = "from . import x, y, z"
3931 self.check_both(b, a)
3932
Martin v. Löwis64903f92008-11-25 03:08:21 +00003933 def test_import_as(self):
3934 b = "import foo as x"
3935 a = "from . import foo as x"
3936 self.check_both(b, a)
3937
Benjamin Peterson8bcddca2009-01-03 16:53:14 +00003938 b = "import a as b, b as c, c as d"
3939 a = "from . import a as b, b as c, c as d"
3940 self.check_both(b, a)
3941
3942 def test_local_and_absolute(self):
3943 self.always_exists = False
3944 self.present_files = set(["foo.py", "__init__.py"])
3945
3946 s = "import foo, bar"
3947 self.warns_unchanged(s, "absolute and local imports together")
3948
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003949 def test_dotted_import(self):
3950 b = "import foo.bar"
Martin v. Löwisa675ef12008-03-24 00:50:58 +00003951 a = "from . import foo.bar"
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003952 self.check_both(b, a)
3953
3954 def test_dotted_import_as(self):
3955 b = "import foo.bar as bang"
Martin v. Löwisa675ef12008-03-24 00:50:58 +00003956 a = "from . import foo.bar as bang"
Martin v. Löwis3faa84f2008-03-22 00:07:09 +00003957 self.check_both(b, a)
3958
Benjamin Peterson0f6de932008-07-19 14:19:28 +00003959 def test_prefix(self):
3960 b = """
3961 # prefix
3962 import foo.bar
3963 """
3964 a = """
3965 # prefix
3966 from . import foo.bar
3967 """
3968 self.check_both(b, a)
3969
Benjamin Peterson206e3072008-10-19 14:07:49 +00003970
3971class Test_set_literal(FixerTestCase):
3972
3973 fixer = "set_literal"
3974
3975 def test_basic(self):
3976 b = """set([1, 2, 3])"""
3977 a = """{1, 2, 3}"""
3978 self.check(b, a)
3979
3980 b = """set((1, 2, 3))"""
3981 a = """{1, 2, 3}"""
3982 self.check(b, a)
3983
3984 b = """set((1,))"""
3985 a = """{1}"""
3986 self.check(b, a)
3987
3988 b = """set([1])"""
3989 self.check(b, a)
3990
3991 b = """set((a, b))"""
3992 a = """{a, b}"""
3993 self.check(b, a)
3994
3995 b = """set([a, b])"""
3996 self.check(b, a)
3997
3998 b = """set((a*234, f(args=23)))"""
3999 a = """{a*234, f(args=23)}"""
4000 self.check(b, a)
4001
4002 b = """set([a*23, f(23)])"""
4003 a = """{a*23, f(23)}"""
4004 self.check(b, a)
4005
4006 b = """set([a-234**23])"""
4007 a = """{a-234**23}"""
4008 self.check(b, a)
4009
4010 def test_listcomps(self):
4011 b = """set([x for x in y])"""
4012 a = """{x for x in y}"""
4013 self.check(b, a)
4014
4015 b = """set([x for x in y if x == m])"""
4016 a = """{x for x in y if x == m}"""
4017 self.check(b, a)
4018
4019 b = """set([x for x in y for a in b])"""
4020 a = """{x for x in y for a in b}"""
4021 self.check(b, a)
4022
4023 b = """set([f(x) - 23 for x in y])"""
4024 a = """{f(x) - 23 for x in y}"""
4025 self.check(b, a)
4026
4027 def test_whitespace(self):
4028 b = """set( [1, 2])"""
4029 a = """{1, 2}"""
4030 self.check(b, a)
4031
4032 b = """set([1 , 2])"""
4033 a = """{1 , 2}"""
4034 self.check(b, a)
4035
4036 b = """set([ 1 ])"""
4037 a = """{ 1 }"""
4038 self.check(b, a)
4039
4040 b = """set( [1] )"""
4041 a = """{1}"""
4042 self.check(b, a)
4043
4044 b = """set([ 1, 2 ])"""
4045 a = """{ 1, 2 }"""
4046 self.check(b, a)
4047
4048 b = """set([x for x in y ])"""
4049 a = """{x for x in y }"""
4050 self.check(b, a)
4051
4052 b = """set(
4053 [1, 2]
4054 )
4055 """
4056 a = """{1, 2}\n"""
4057 self.check(b, a)
4058
4059 def test_comments(self):
4060 b = """set((1, 2)) # Hi"""
4061 a = """{1, 2} # Hi"""
4062 self.check(b, a)
4063
4064 # This isn't optimal behavior, but the fixer is optional.
4065 b = """
4066 # Foo
4067 set( # Bar
4068 (1, 2)
4069 )
4070 """
4071 a = """
4072 # Foo
4073 {1, 2}
4074 """
4075 self.check(b, a)
4076
4077 def test_unchanged(self):
4078 s = """set()"""
4079 self.unchanged(s)
4080
4081 s = """set(a)"""
4082 self.unchanged(s)
4083
4084 s = """set(a, b, c)"""
4085 self.unchanged(s)
4086
4087 # Don't transform generators because they might have to be lazy.
4088 s = """set(x for x in y)"""
4089 self.unchanged(s)
4090
4091 s = """set(x for x in y if z)"""
4092 self.unchanged(s)
4093
4094 s = """set(a*823-23**2 + f(23))"""
4095 self.unchanged(s)
4096
4097
Benjamin Petersoncf603822008-09-01 19:56:06 +00004098class Test_sys_exc(FixerTestCase):
4099 fixer = "sys_exc"
4100
4101 def test_0(self):
4102 b = "sys.exc_type"
4103 a = "sys.exc_info()[0]"
4104 self.check(b, a)
4105
4106 def test_1(self):
4107 b = "sys.exc_value"
4108 a = "sys.exc_info()[1]"
4109 self.check(b, a)
4110
4111 def test_2(self):
4112 b = "sys.exc_traceback"
4113 a = "sys.exc_info()[2]"
4114 self.check(b, a)
4115
4116 def test_3(self):
4117 b = "sys.exc_type # Foo"
4118 a = "sys.exc_info()[0] # Foo"
4119 self.check(b, a)
4120
4121 def test_4(self):
4122 b = "sys. exc_type"
4123 a = "sys. exc_info()[0]"
4124 self.check(b, a)
4125
4126 def test_5(self):
4127 b = "sys .exc_type"
4128 a = "sys .exc_info()[0]"
4129 self.check(b, a)
4130
4131
4132class Test_paren(FixerTestCase):
4133 fixer = "paren"
4134
4135 def test_0(self):
4136 b = """[i for i in 1, 2 ]"""
4137 a = """[i for i in (1, 2) ]"""
4138 self.check(b, a)
4139
4140 def test_1(self):
4141 b = """[i for i in 1, 2, ]"""
4142 a = """[i for i in (1, 2,) ]"""
4143 self.check(b, a)
4144
4145 def test_2(self):
4146 b = """[i for i in 1, 2 ]"""
4147 a = """[i for i in (1, 2) ]"""
4148 self.check(b, a)
4149
4150 def test_3(self):
4151 b = """[i for i in 1, 2 if i]"""
4152 a = """[i for i in (1, 2) if i]"""
4153 self.check(b, a)
4154
4155 def test_4(self):
4156 b = """[i for i in 1, 2 ]"""
4157 a = """[i for i in (1, 2) ]"""
4158 self.check(b, a)
4159
4160 def test_5(self):
4161 b = """(i for i in 1, 2)"""
4162 a = """(i for i in (1, 2))"""
4163 self.check(b, a)
4164
4165 def test_6(self):
4166 b = """(i for i in 1 ,2 if i)"""
4167 a = """(i for i in (1 ,2) if i)"""
4168 self.check(b, a)
4169
4170 def test_unchanged_0(self):
4171 s = """[i for i in (1, 2)]"""
4172 self.unchanged(s)
4173
4174 def test_unchanged_1(self):
4175 s = """[i for i in foo()]"""
4176 self.unchanged(s)
4177
4178 def test_unchanged_2(self):
4179 s = """[i for i in (1, 2) if nothing]"""
4180 self.unchanged(s)
4181
4182 def test_unchanged_3(self):
4183 s = """(i for i in (1, 2))"""
4184 self.unchanged(s)
4185
4186 def test_unchanged_4(self):
4187 s = """[i for i in m]"""
4188 self.unchanged(s)
4189
Benjamin Peterson3a2fb142008-09-13 18:37:09 +00004190class Test_metaclass(FixerTestCase):
4191
4192 fixer = 'metaclass'
4193
4194 def test_unchanged(self):
4195 self.unchanged("class X(): pass")
4196 self.unchanged("class X(object): pass")
4197 self.unchanged("class X(object1, object2): pass")
4198 self.unchanged("class X(object1, object2, object3): pass")
4199 self.unchanged("class X(metaclass=Meta): pass")
4200 self.unchanged("class X(b, arg=23, metclass=Meta): pass")
4201 self.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass")
4202
4203 s = """
4204 class X:
4205 def __metaclass__(self): pass
4206 """
4207 self.unchanged(s)
4208
Benjamin Petersonba558182008-11-10 22:21:33 +00004209 s = """
4210 class X:
4211 a[23] = 74
4212 """
4213 self.unchanged(s)
4214
Benjamin Peterson3a2fb142008-09-13 18:37:09 +00004215 def test_comments(self):
4216 b = """
4217 class X:
4218 # hi
4219 __metaclass__ = AppleMeta
4220 """
4221 a = """
4222 class X(metaclass=AppleMeta):
4223 # hi
4224 pass
4225 """
4226 self.check(b, a)
4227
4228 b = """
4229 class X:
4230 __metaclass__ = Meta
4231 # Bedtime!
4232 """
4233 a = """
4234 class X(metaclass=Meta):
4235 pass
4236 # Bedtime!
4237 """
4238 self.check(b, a)
4239
4240 def test_meta(self):
4241 # no-parent class, odd body
4242 b = """
4243 class X():
4244 __metaclass__ = Q
4245 pass
4246 """
4247 a = """
4248 class X(metaclass=Q):
4249 pass
4250 """
4251 self.check(b, a)
4252
4253 # one parent class, no body
4254 b = """class X(object): __metaclass__ = Q"""
4255 a = """class X(object, metaclass=Q): pass"""
4256 self.check(b, a)
4257
4258
4259 # one parent, simple body
4260 b = """
4261 class X(object):
4262 __metaclass__ = Meta
4263 bar = 7
4264 """
4265 a = """
4266 class X(object, metaclass=Meta):
4267 bar = 7
4268 """
4269 self.check(b, a)
4270
4271 b = """
4272 class X:
4273 __metaclass__ = Meta; x = 4; g = 23
4274 """
4275 a = """
4276 class X(metaclass=Meta):
4277 x = 4; g = 23
4278 """
4279 self.check(b, a)
4280
4281 # one parent, simple body, __metaclass__ last
4282 b = """
4283 class X(object):
4284 bar = 7
4285 __metaclass__ = Meta
4286 """
4287 a = """
4288 class X(object, metaclass=Meta):
4289 bar = 7
4290 """
4291 self.check(b, a)
4292
4293 # redefining __metaclass__
4294 b = """
4295 class X():
4296 __metaclass__ = A
4297 __metaclass__ = B
4298 bar = 7
4299 """
4300 a = """
4301 class X(metaclass=B):
4302 bar = 7
4303 """
4304 self.check(b, a)
4305
4306 # multiple inheritance, simple body
4307 b = """
4308 class X(clsA, clsB):
4309 __metaclass__ = Meta
4310 bar = 7
4311 """
4312 a = """
4313 class X(clsA, clsB, metaclass=Meta):
4314 bar = 7
4315 """
4316 self.check(b, a)
4317
4318 # keywords in the class statement
4319 b = """class m(a, arg=23): __metaclass__ = Meta"""
4320 a = """class m(a, arg=23, metaclass=Meta): pass"""
4321 self.check(b, a)
4322
Benjamin Petersonba558182008-11-10 22:21:33 +00004323 b = """
4324 class X(expression(2 + 4)):
4325 __metaclass__ = Meta
4326 """
4327 a = """
4328 class X(expression(2 + 4), metaclass=Meta):
4329 pass
4330 """
4331 self.check(b, a)
4332
4333 b = """
4334 class X(expression(2 + 4), x**4):
4335 __metaclass__ = Meta
4336 """
4337 a = """
4338 class X(expression(2 + 4), x**4, metaclass=Meta):
4339 pass
4340 """
4341 self.check(b, a)
4342
Martin v. Löwis64903f92008-11-25 03:08:21 +00004343 b = """
4344 class X:
4345 __metaclass__ = Meta
4346 save.py = 23
4347 """
4348 a = """
4349 class X(metaclass=Meta):
4350 save.py = 23
4351 """
4352 self.check(b, a)
4353
Martin v. Löwisef04c442008-03-19 05:04:44 +00004354
Benjamin Peterson7d8d9a52008-10-04 21:04:36 +00004355class Test_getcwdu(FixerTestCase):
4356
4357 fixer = 'getcwdu'
4358
4359 def test_basic(self):
4360 b = """os.getcwdu"""
4361 a = """os.getcwd"""
4362 self.check(b, a)
4363
4364 b = """os.getcwdu()"""
4365 a = """os.getcwd()"""
4366 self.check(b, a)
4367
4368 b = """meth = os.getcwdu"""
4369 a = """meth = os.getcwd"""
4370 self.check(b, a)
4371
4372 b = """os.getcwdu(args)"""
4373 a = """os.getcwd(args)"""
4374 self.check(b, a)
4375
4376 def test_comment(self):
4377 b = """os.getcwdu() # Foo"""
4378 a = """os.getcwd() # Foo"""
4379 self.check(b, a)
4380
4381 def test_unchanged(self):
4382 s = """os.getcwd()"""
4383 self.unchanged(s)
4384
4385 s = """getcwdu()"""
4386 self.unchanged(s)
4387
4388 s = """os.getcwdb()"""
4389 self.unchanged(s)
4390
4391 def test_indentation(self):
4392 b = """
4393 if 1:
4394 os.getcwdu()
4395 """
4396 a = """
4397 if 1:
4398 os.getcwd()
4399 """
4400 self.check(b, a)
4401
4402 def test_multilation(self):
4403 b = """os .getcwdu()"""
4404 a = """os .getcwd()"""
4405 self.check(b, a)
4406
4407 b = """os. getcwdu"""
4408 a = """os. getcwd"""
4409 self.check(b, a)
4410
4411 b = """os.getcwdu ( )"""
4412 a = """os.getcwd ( )"""
4413 self.check(b, a)
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +00004414
4415
4416class Test_operator(FixerTestCase):
4417
4418 fixer = "operator"
4419
4420 def test_operator_isCallable(self):
4421 b = "operator.isCallable(x)"
4422 a = "hasattr(x, '__call__')"
4423 self.check(b, a)
4424
4425 def test_operator_sequenceIncludes(self):
4426 b = "operator.sequenceIncludes(x, y)"
4427 a = "operator.contains(x, y)"
4428 self.check(b, a)
4429
Benjamin Peterson68c80ed2010-08-08 19:23:25 +00004430 b = "operator .sequenceIncludes(x, y)"
4431 a = "operator .contains(x, y)"
4432 self.check(b, a)
4433
4434 b = "operator. sequenceIncludes(x, y)"
4435 a = "operator. contains(x, y)"
4436 self.check(b, a)
4437
4438 def test_operator_isSequenceType(self):
4439 b = "operator.isSequenceType(x)"
4440 a = "import collections\nisinstance(x, collections.Sequence)"
4441 self.check(b, a)
4442
4443 def test_operator_isMappingType(self):
4444 b = "operator.isMappingType(x)"
4445 a = "import collections\nisinstance(x, collections.Mapping)"
4446 self.check(b, a)
4447
4448 def test_operator_isNumberType(self):
4449 b = "operator.isNumberType(x)"
4450 a = "import numbers\nisinstance(x, numbers.Number)"
4451 self.check(b, a)
4452
4453 def test_operator_repeat(self):
4454 b = "operator.repeat(x, n)"
4455 a = "operator.mul(x, n)"
4456 self.check(b, a)
4457
4458 b = "operator .repeat(x, n)"
4459 a = "operator .mul(x, n)"
4460 self.check(b, a)
4461
4462 b = "operator. repeat(x, n)"
4463 a = "operator. mul(x, n)"
4464 self.check(b, a)
4465
4466 def test_operator_irepeat(self):
4467 b = "operator.irepeat(x, n)"
4468 a = "operator.imul(x, n)"
4469 self.check(b, a)
4470
4471 b = "operator .irepeat(x, n)"
4472 a = "operator .imul(x, n)"
4473 self.check(b, a)
4474
4475 b = "operator. irepeat(x, n)"
4476 a = "operator. imul(x, n)"
4477 self.check(b, a)
4478
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +00004479 def test_bare_isCallable(self):
4480 s = "isCallable(x)"
Benjamin Peterson68c80ed2010-08-08 19:23:25 +00004481 t = "You should use 'hasattr(x, '__call__')' here."
4482 self.warns_unchanged(s, t)
Benjamin Petersondd6a4ed2009-07-21 12:55:57 +00004483
4484 def test_bare_sequenceIncludes(self):
4485 s = "sequenceIncludes(x, y)"
Benjamin Peterson68c80ed2010-08-08 19:23:25 +00004486 t = "You should use 'operator.contains(x, y)' here."
4487 self.warns_unchanged(s, t)
4488
4489 def test_bare_operator_isSequenceType(self):
4490 s = "isSequenceType(z)"
4491 t = "You should use 'isinstance(z, collections.Sequence)' here."
4492 self.warns_unchanged(s, t)
4493
4494 def test_bare_operator_isMappingType(self):
4495 s = "isMappingType(x)"
4496 t = "You should use 'isinstance(x, collections.Mapping)' here."
4497 self.warns_unchanged(s, t)
4498
4499 def test_bare_operator_isNumberType(self):
4500 s = "isNumberType(y)"
4501 t = "You should use 'isinstance(y, numbers.Number)' here."
4502 self.warns_unchanged(s, t)
4503
4504 def test_bare_operator_repeat(self):
4505 s = "repeat(x, n)"
4506 t = "You should use 'operator.mul(x, n)' here."
4507 self.warns_unchanged(s, t)
4508
4509 def test_bare_operator_irepeat(self):
4510 s = "irepeat(y, 187)"
4511 t = "You should use 'operator.imul(y, 187)' here."
4512 self.warns_unchanged(s, t)
Benjamin Peterson5fbccff2010-03-23 03:29:23 +00004513
4514
4515class Test_exitfunc(FixerTestCase):
4516
4517 fixer = "exitfunc"
4518
4519 def test_simple(self):
4520 b = """
4521 import sys
4522 sys.exitfunc = my_atexit
4523 """
4524 a = """
4525 import sys
4526 import atexit
4527 atexit.register(my_atexit)
4528 """
4529 self.check(b, a)
4530
4531 def test_names_import(self):
4532 b = """
4533 import sys, crumbs
4534 sys.exitfunc = my_func
4535 """
4536 a = """
4537 import sys, crumbs, atexit
4538 atexit.register(my_func)
4539 """
4540 self.check(b, a)
4541
4542 def test_complex_expression(self):
4543 b = """
4544 import sys
4545 sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
4546 """
4547 a = """
4548 import sys
4549 import atexit
4550 atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
4551 """
4552 self.check(b, a)
4553
4554 def test_comments(self):
4555 b = """
4556 import sys # Foo
4557 sys.exitfunc = f # Blah
4558 """
4559 a = """
4560 import sys
4561 import atexit # Foo
4562 atexit.register(f) # Blah
4563 """
4564 self.check(b, a)
4565
4566 b = """
4567 import apples, sys, crumbs, larry # Pleasant comments
4568 sys.exitfunc = func
4569 """
4570 a = """
4571 import apples, sys, crumbs, larry, atexit # Pleasant comments
4572 atexit.register(func)
4573 """
4574 self.check(b, a)
4575
4576 def test_in_a_function(self):
4577 b = """
4578 import sys
4579 def f():
4580 sys.exitfunc = func
4581 """
4582 a = """
4583 import sys
4584 import atexit
4585 def f():
4586 atexit.register(func)
4587 """
4588 self.check(b, a)
4589
4590 def test_no_sys_import(self):
4591 b = """sys.exitfunc = f"""
4592 a = """atexit.register(f)"""
4593 msg = ("Can't find sys import; Please add an atexit import at the "
4594 "top of your file.")
4595 self.warns(b, a, msg)
4596
4597
4598 def test_unchanged(self):
4599 s = """f(sys.exitfunc)"""
4600 self.unchanged(s)