PageRenderTime 69ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/lib2to3/tests/test_fixers.py

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