PageRenderTime 63ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

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

http://github.com/IronLanguages/main
Python | 4529 lines | 4452 code | 72 blank | 5 comment | 11 complexity | 10926e53ce2f87d4767fc70ff8b03837 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.assertTrue(message in "".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_14(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_15(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_17(self):
  1143. b = "iter(d.viewkeys())"
  1144. a = "iter(d.keys())"
  1145. self.check(b, a)
  1146. def test_18(self):
  1147. b = "list(d.viewkeys())"
  1148. a = "list(d.keys())"
  1149. self.check(b, a)
  1150. def test_19(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. class Test_callable(FixerTestCase):
  2289. fixer = "callable"
  2290. def test_prefix_preservation(self):
  2291. b = """callable( x)"""
  2292. a = """import collections\nisinstance( x, collections.Callable)"""
  2293. self.check(b, a)
  2294. b = """if callable(x): pass"""
  2295. a = """import collections
  2296. if isinstance(x, collections.Callable): pass"""
  2297. self.check(b, a)
  2298. def test_callable_call(self):
  2299. b = """callable(x)"""
  2300. a = """import collections\nisinstance(x, collections.Callable)"""
  2301. self.check(b, a)
  2302. def test_global_import(self):
  2303. b = """
  2304. def spam(foo):
  2305. callable(foo)"""[1:]
  2306. a = """
  2307. import collections
  2308. def spam(foo):
  2309. isinstance(foo, collections.Callable)"""[1:]
  2310. self.check(b, a)
  2311. b = """
  2312. import collections
  2313. def spam(foo):
  2314. callable(foo)"""[1:]
  2315. # same output if it was already imported
  2316. self.check(b, a)
  2317. b = """
  2318. from collections import *
  2319. def spam(foo):
  2320. callable(foo)"""[1:]
  2321. a = """
  2322. from collections import *
  2323. import collections
  2324. def spam(foo):
  2325. isinstance(foo, collections.Callable)"""[1:]
  2326. self.check(b, a)
  2327. b = """
  2328. do_stuff()
  2329. do_some_other_stuff()
  2330. assert callable(do_stuff)"""[1:]
  2331. a = """
  2332. import collections
  2333. do_stuff()
  2334. do_some_other_stuff()
  2335. assert isinstance(do_stuff, collections.Callable)"""[1:]
  2336. self.check(b, a)
  2337. b = """
  2338. if isinstance(do_stuff, Callable):
  2339. assert callable(do_stuff)
  2340. do_stuff(do_stuff)
  2341. if not callable(do_stuff):
  2342. exit(1)
  2343. else:
  2344. assert callable(do_stuff)
  2345. else:
  2346. assert not callable(do_stuff)"""[1:]
  2347. a = """
  2348. import collections
  2349. if isinstance(do_stuff, Callable):
  2350. assert isinstance(do_stuff, collections.Callable)
  2351. do_stuff(do_stuff)
  2352. if not isinstance(do_stuff, collections.Callable):
  2353. exit(1)
  2354. else:
  2355. assert isinstance(do_stuff, collections.Callable)
  2356. else:
  2357. assert not isinstance(do_stuff, collections.Callable)"""[1:]
  2358. self.check(b, a)
  2359. def test_callable_should_not_change(self):
  2360. a = """callable(*x)"""
  2361. self.unchanged(a)
  2362. a = """callable(x, y)"""
  2363. self.unchanged(a)
  2364. a = """callable(x, kw=y)"""
  2365. self.unchanged(a)
  2366. a = """callable()"""
  2367. self.unchanged(a)
  2368. class Test_filter(FixerTestCase):
  2369. fixer = "filter"
  2370. def test_prefix_preservation(self):
  2371. b = """x = filter( foo, 'abc' )"""
  2372. a = """x = list(filter( foo, 'abc' ))"""
  2373. self.check(b, a)
  2374. b = """x = filter( None , 'abc' )"""
  2375. a = """x = [_f for _f in 'abc' if _f]"""
  2376. self.check(b, a)
  2377. def test_filter_basic(self):
  2378. b = """x = filter(None, 'abc')"""
  2379. a = """x = [_f for _f in 'abc' if _f]"""
  2380. self.check(b, a)
  2381. b = """x = len(filter(f, 'abc'))"""
  2382. a = """x = len(list(filter(f, 'abc')))"""
  2383. self.check(b, a)
  2384. b = """x = filter(lambda x: x%2 == 0, range(10))"""
  2385. a = """x = [x for x in range(10) if x%2 == 0]"""
  2386. self.check(b, a)
  2387. # Note the parens around x
  2388. b = """x = filter(lambda (x): x%2 == 0, range(10))"""
  2389. a = """x = [x for x in range(10) if x%2 == 0]"""
  2390. self.check(b, a)
  2391. # XXX This (rare) case is not supported
  2392. ## b = """x = filter(f, 'abc')[0]"""
  2393. ## a = """x = list(filter(f, 'abc'))[0]"""
  2394. ## self.check(b, a)
  2395. def test_filter_nochange(self):
  2396. a = """b.join(filter(f, 'abc'))"""
  2397. self.unchanged(a)
  2398. a = """(a + foo(5)).join(filter(f, 'abc'))"""
  2399. self.unchanged(a)
  2400. a = """iter(filter(f, 'abc'))"""
  2401. self.unchanged(a)
  2402. a = """list(filter(f, 'abc'))"""
  2403. self.unchanged(a)
  2404. a = """list(filter(f, 'abc'))[0]"""
  2405. self.unchanged(a)
  2406. a = """set(filter(f, 'abc'))"""
  2407. self.unchanged(a)
  2408. a = """set(filter(f, 'abc')).pop()"""
  2409. self.unchanged(a)
  2410. a = """tuple(filter(f, 'abc'))"""
  2411. self.unchanged(a)
  2412. a = """any(filter(f, 'abc'))"""
  2413. self.unchanged(a)
  2414. a = """all(filter(f, 'abc'))"""
  2415. self.unchanged(a)
  2416. a = """sum(filter(f, 'abc'))"""
  2417. self.unchanged(a)
  2418. a = """sorted(filter(f, 'abc'))"""
  2419. self.unchanged(a)
  2420. a = """sorted(filter(f, 'abc'), key=blah)"""
  2421. self.unchanged(a)
  2422. a = """sorted(filter(f, 'abc'), key=blah)[0]"""
  2423. self.unchanged(a)
  2424. a = """for i in filter(f, 'abc'): pass"""
  2425. self.unchanged(a)
  2426. a = """[x for x in filter(f, 'abc')]"""
  2427. self.unchanged(a)
  2428. a = """(x for x in filter(f, 'abc'))"""
  2429. self.unchanged(a)
  2430. def test_future_builtins(self):
  2431. a = "from future_builtins import spam, filter; filter(f, 'ham')"
  2432. self.unchanged(a)
  2433. b = """from future_builtins import spam; x = filter(f, 'abc')"""
  2434. a = """from future_builtins import spam; x = list(filter(f, 'abc'))"""
  2435. self.check(b, a)
  2436. a = "from future_builtins import *; filter(f, 'ham')"
  2437. self.unchanged(a)
  2438. class Test_map(FixerTestCase):
  2439. fixer = "map"
  2440. def check(self, b, a):
  2441. self.unchanged("from future_builtins import map; " + b, a)
  2442. super(Test_map, self).check(b, a)
  2443. def test_prefix_preservation(self):
  2444. b = """x = map( f, 'abc' )"""
  2445. a = """x = list(map( f, 'abc' ))"""
  2446. self.check(b, a)
  2447. def test_trailing_comment(self):
  2448. b = """x = map(f, 'abc') # foo"""
  2449. a = """x = list(map(f, 'abc')) # foo"""
  2450. self.check(b, a)
  2451. def test_None_with_multiple_arguments(self):
  2452. s = """x = map(None, a, b, c)"""
  2453. self.warns_unchanged(s, "cannot convert map(None, ...) with "
  2454. "multiple arguments")
  2455. def test_map_basic(self):
  2456. b = """x = map(f, 'abc')"""
  2457. a = """x = list(map(f, 'abc'))"""
  2458. self.check(b, a)
  2459. b = """x = len(map(f, 'abc', 'def'))"""
  2460. a = """x = len(list(map(f, 'abc', 'def')))"""
  2461. self.check(b, a)
  2462. b = """x = map(None, 'abc')"""
  2463. a = """x = list('abc')"""
  2464. self.check(b, a)
  2465. b = """x = map(lambda x: x+1, range(4))"""
  2466. a = """x = [x+1 for x in range(4)]"""
  2467. self.check(b, a)
  2468. # Note the parens around x
  2469. b = """x = map(lambda (x): x+1, range(4))"""
  2470. a = """x = [x+1 for x in range(4)]"""
  2471. self.check(b, a)
  2472. b = """
  2473. foo()
  2474. # foo
  2475. map(f, x)
  2476. """
  2477. a = """
  2478. foo()
  2479. # foo
  2480. list(map(f, x))
  2481. """
  2482. self.warns(b, a, "You should use a for loop here")
  2483. # XXX This (rare) case is not supported
  2484. ## b = """x = map(f, 'abc')[0]"""
  2485. ## a = """x = list(map(f, 'abc'))[0]"""
  2486. ## self.check(b, a)
  2487. def test_map_nochange(self):
  2488. a = """b.join(map(f, 'abc'))"""
  2489. self.unchanged(a)
  2490. a = """(a + foo(5)).join(map(f, 'abc'))"""
  2491. self.unchanged(a)
  2492. a = """iter(map(f, 'abc'))"""
  2493. self.unchanged(a)
  2494. a = """list(map(f, 'abc'))"""
  2495. self.unchanged(a)
  2496. a = """list(map(f, 'abc'))[0]"""
  2497. self.unchanged(a)
  2498. a = """set(map(f, 'abc'))"""
  2499. self.unchanged(a)
  2500. a = """set(map(f, 'abc')).pop()"""
  2501. self.unchanged(a)
  2502. a = """tuple(map(f, 'abc'))"""
  2503. self.unchanged(a)
  2504. a = """any(map(f, 'abc'))"""
  2505. self.unchanged(a)
  2506. a = """all(map(f, 'abc'))"""
  2507. self.unchanged(a)
  2508. a = """sum(map(f, 'abc'))"""
  2509. self.unchanged(a)
  2510. a = """sorted(map(f, 'abc'))"""
  2511. self.unchanged(a)
  2512. a = """sorted(map(f, 'abc'), key=blah)"""
  2513. self.unchanged(a)
  2514. a = """sorted(map(f, 'abc'), key=blah)[0]"""
  2515. self.unchanged(a)
  2516. a = """for i in map(f, 'abc'): pass"""
  2517. self.unchanged(a)
  2518. a = """[x for x in map(f, 'abc')]"""
  2519. self.unchanged(a)
  2520. a = """(x for x in map(f, 'abc'))"""
  2521. self.unchanged(a)
  2522. def test_future_builtins(self):
  2523. a = "from future_builtins import spam, map, eggs; map(f, 'ham')"
  2524. self.unchanged(a)
  2525. b = """from future_builtins import spam, eggs; x = map(f, 'abc')"""
  2526. a = """from future_builtins import spam, eggs; x = list(map(f, 'abc'))"""
  2527. self.check(b, a)
  2528. a = "from future_builtins import *; map(f, 'ham')"
  2529. self.unchanged(a)
  2530. class Test_zip(FixerTestCase):
  2531. fixer = "zip"
  2532. def check(self, b, a):
  2533. self.unchanged("from future_builtins import zip; " + b, a)
  2534. super(Test_zip, self).check(b, a)
  2535. def test_zip_basic(self):
  2536. b = """x = zip(a, b, c)"""
  2537. a = """x = list(zip(a, b, c))"""
  2538. self.check(b, a)
  2539. b = """x = len(zip(a, b))"""
  2540. a = """x = len(list(zip(a, b)))"""
  2541. self.check(b, a)
  2542. def test_zip_nochange(self):
  2543. a = """b.join(zip(a, b))"""
  2544. self.unchanged(a)
  2545. a = """(a + foo(5)).join(zip(a, b))"""
  2546. self.unchanged(a)
  2547. a = """iter(zip(a, b))"""
  2548. self.unchanged(a)
  2549. a = """list(zip(a, b))"""
  2550. self.unchanged(a)
  2551. a = """list(zip(a, b))[0]"""
  2552. self.unchanged(a)
  2553. a = """set(zip(a, b))"""
  2554. self.unchanged(a)
  2555. a = """set(zip(a, b)).pop()"""
  2556. self.unchanged(a)
  2557. a = """tuple(zip(a, b))"""
  2558. self.unchanged(a)
  2559. a = """any(zip(a, b))"""
  2560. self.unchanged(a)
  2561. a = """all(zip(a, b))"""
  2562. self.unchanged(a)
  2563. a = """sum(zip(a, b))"""
  2564. self.unchanged(a)
  2565. a = """sorted(zip(a, b))"""
  2566. self.unchanged(a)
  2567. a = """sorted(zip(a, b), key=blah)"""
  2568. self.unchanged(a)
  2569. a = """sorted(zip(a, b), key=blah)[0]"""
  2570. self.unchanged(a)
  2571. a = """for i in zip(a, b): pass"""
  2572. self.unchanged(a)
  2573. a = """[x for x in zip(a, b)]"""
  2574. self.unchanged(a)
  2575. a = """(x for x in zip(a, b))"""
  2576. self.unchanged(a)
  2577. def test_future_builtins(self):
  2578. a = "from future_builtins import spam, zip, eggs; zip(a, b)"
  2579. self.unchanged(a)
  2580. b = """from future_builtins import spam, eggs; x = zip(a, b)"""
  2581. a = """from future_builtins import spam, eggs; x = list(zip(a, b))"""
  2582. self.check(b, a)
  2583. a = "from future_builtins import *; zip(a, b)"
  2584. self.unchanged(a)
  2585. class Test_standarderror(FixerTestCase):
  2586. fixer = "standarderror"
  2587. def test(self):
  2588. b = """x = StandardError()"""
  2589. a = """x = Exception()"""
  2590. self.check(b, a)
  2591. b = """x = StandardError(a, b, c)"""
  2592. a = """x = Exception(a, b, c)"""
  2593. self.check(b, a)
  2594. b = """f(2 + StandardError(a, b, c))"""
  2595. a = """f(2 + Exception(a, b, c))"""
  2596. self.check(b, a)
  2597. class Test_types(FixerTestCase):
  2598. fixer = "types"
  2599. def test_basic_types_convert(self):
  2600. b = """types.StringType"""
  2601. a = """bytes"""
  2602. self.check(b, a)
  2603. b = """types.DictType"""
  2604. a = """dict"""
  2605. self.check(b, a)
  2606. b = """types . IntType"""
  2607. a = """int"""
  2608. self.check(b, a)
  2609. b = """types.ListType"""
  2610. a = """list"""
  2611. self.check(b, a)
  2612. b = """types.LongType"""
  2613. a = """int"""
  2614. self.check(b, a)
  2615. b = """types.NoneType"""
  2616. a = """type(None)"""
  2617. self.check(b, a)
  2618. class Test_idioms(FixerTestCase):
  2619. fixer = "idioms"
  2620. def test_while(self):
  2621. b = """while 1: foo()"""
  2622. a = """while True: foo()"""
  2623. self.check(b, a)
  2624. b = """while 1: foo()"""
  2625. a = """while True: foo()"""
  2626. self.check(b, a)
  2627. b = """
  2628. while 1:
  2629. foo()
  2630. """
  2631. a = """
  2632. while True:
  2633. foo()
  2634. """
  2635. self.check(b, a)
  2636. def test_while_unchanged(self):
  2637. s = """while 11: foo()"""
  2638. self.unchanged(s)
  2639. s = """while 0: foo()"""
  2640. self.unchanged(s)
  2641. s = """while foo(): foo()"""
  2642. self.unchanged(s)
  2643. s = """while []: foo()"""
  2644. self.unchanged(s)
  2645. def test_eq_simple(self):
  2646. b = """type(x) == T"""
  2647. a = """isinstance(x, T)"""
  2648. self.check(b, a)
  2649. b = """if type(x) == T: pass"""
  2650. a = """if isinstance(x, T): pass"""
  2651. self.check(b, a)
  2652. def test_eq_reverse(self):
  2653. b = """T == type(x)"""
  2654. a = """isinstance(x, T)"""
  2655. self.check(b, a)
  2656. b = """if T == type(x): pass"""
  2657. a = """if isinstance(x, T): pass"""
  2658. self.check(b, a)
  2659. def test_eq_expression(self):
  2660. b = """type(x+y) == d.get('T')"""
  2661. a = """isinstance(x+y, d.get('T'))"""
  2662. self.check(b, a)
  2663. b = """type( x + y) == d.get('T')"""
  2664. a = """isinstance(x + y, d.get('T'))"""
  2665. self.check(b, a)
  2666. def test_is_simple(self):
  2667. b = """type(x) is T"""
  2668. a = """isinstance(x, T)"""
  2669. self.check(b, a)
  2670. b = """if type(x) is T: pass"""
  2671. a = """if isinstance(x, T): pass"""
  2672. self.check(b, a)
  2673. def test_is_reverse(self):
  2674. b = """T is type(x)"""
  2675. a = """isinstance(x, T)"""
  2676. self.check(b, a)
  2677. b = """if T is type(x): pass"""
  2678. a = """if isinstance(x, T): pass"""
  2679. self.check(b, a)
  2680. def test_is_expression(self):
  2681. b = """type(x+y) is d.get('T')"""
  2682. a = """isinstance(x+y, d.get('T'))"""
  2683. self.check(b, a)
  2684. b = """type( x + y) is d.get('T')"""
  2685. a = """isinstance(x + y, d.get('T'))"""
  2686. self.check(b, a)
  2687. def test_is_not_simple(self):
  2688. b = """type(x) is not T"""
  2689. a = """not isinstance(x, T)"""
  2690. self.check(b, a)
  2691. b = """if type(x) is not T: pass"""
  2692. a = """if not isinstance(x, T): pass"""
  2693. self.check(b, a)
  2694. def test_is_not_reverse(self):
  2695. b = """T is not type(x)"""
  2696. a = """not isinstance(x, T)"""
  2697. self.check(b, a)
  2698. b = """if T is not type(x): pass"""
  2699. a = """if not isinstance(x, T): pass"""
  2700. self.check(b, a)
  2701. def test_is_not_expression(self):
  2702. b = """type(x+y) is not d.get('T')"""
  2703. a = """not isinstance(x+y, d.get('T'))"""
  2704. self.check(b, a)
  2705. b = """type( x + y) is not d.get('T')"""
  2706. a = """not isinstance(x + y, d.get('T'))"""
  2707. self.check(b, a)
  2708. def test_ne_simple(self):
  2709. b = """type(x) != T"""
  2710. a = """not isinstance(x, T)"""
  2711. self.check(b, a)
  2712. b = """if type(x) != T: pass"""
  2713. a = """if not isinstance(x, T): pass"""
  2714. self.check(b, a)
  2715. def test_ne_reverse(self):
  2716. b = """T != type(x)"""
  2717. a = """not isinstance(x, T)"""
  2718. self.check(b, a)
  2719. b = """if T != type(x): pass"""
  2720. a = """if not isinstance(x, T): pass"""
  2721. self.check(b, a)
  2722. def test_ne_expression(self):
  2723. b = """type(x+y) != d.get('T')"""
  2724. a = """not isinstance(x+y, d.get('T'))"""
  2725. self.check(b, a)
  2726. b = """type( x + y) != d.get('T')"""
  2727. a = """not isinstance(x + y, d.get('T'))"""
  2728. self.check(b, a)
  2729. def test_type_unchanged(self):
  2730. a = """type(x).__name__"""
  2731. self.unchanged(a)
  2732. def test_sort_list_call(self):
  2733. b = """
  2734. v = list(t)
  2735. v.sort()
  2736. foo(v)
  2737. """
  2738. a = """
  2739. v = sorted(t)
  2740. foo(v)
  2741. """
  2742. self.check(b, a)
  2743. b = """
  2744. v = list(foo(b) + d)
  2745. v.sort()
  2746. foo(v)
  2747. """
  2748. a = """
  2749. v = sorted(foo(b) + d)
  2750. foo(v)
  2751. """
  2752. self.check(b, a)
  2753. b = """
  2754. while x:
  2755. v = list(t)
  2756. v.sort()
  2757. foo(v)
  2758. """
  2759. a = """
  2760. while x:
  2761. v = sorted(t)
  2762. foo(v)
  2763. """
  2764. self.check(b, a)
  2765. b = """
  2766. v = list(t)
  2767. # foo
  2768. v.sort()
  2769. foo(v)
  2770. """
  2771. a = """
  2772. v = sorted(t)
  2773. # foo
  2774. foo(v)
  2775. """
  2776. self.check(b, a)
  2777. b = r"""
  2778. v = list( t)
  2779. v.sort()
  2780. foo(v)
  2781. """
  2782. a = r"""
  2783. v = sorted( t)
  2784. foo(v)
  2785. """
  2786. self.check(b, a)
  2787. b = r"""
  2788. try:
  2789. m = list(s)
  2790. m.sort()
  2791. except: pass
  2792. """
  2793. a = r"""
  2794. try:
  2795. m = sorted(s)
  2796. except: pass
  2797. """
  2798. self.check(b, a)
  2799. b = r"""
  2800. try:
  2801. m = list(s)
  2802. # foo
  2803. m.sort()
  2804. except: pass
  2805. """
  2806. a = r"""
  2807. try:
  2808. m = sorted(s)
  2809. # foo
  2810. except: pass
  2811. """
  2812. self.check(b, a)
  2813. b = r"""
  2814. m = list(s)
  2815. # more comments
  2816. m.sort()"""
  2817. a = r"""
  2818. m = sorted(s)
  2819. # more comments"""
  2820. self.check(b, a)
  2821. def test_sort_simple_expr(self):
  2822. b = """
  2823. v = t
  2824. v.sort()
  2825. foo(v)
  2826. """
  2827. a = """
  2828. v = sorted(t)
  2829. foo(v)
  2830. """
  2831. self.check(b, a)
  2832. b = """
  2833. v = foo(b)
  2834. v.sort()
  2835. foo(v)
  2836. """
  2837. a = """
  2838. v = sorted(foo(b))
  2839. foo(v)
  2840. """
  2841. self.check(b, a)
  2842. b = """
  2843. v = b.keys()
  2844. v.sort()
  2845. foo(v)
  2846. """
  2847. a = """
  2848. v = sorted(b.keys())
  2849. foo(v)
  2850. """
  2851. self.check(b, a)
  2852. b = """
  2853. v = foo(b) + d
  2854. v.sort()
  2855. foo(v)
  2856. """
  2857. a = """
  2858. v = sorted(foo(b) + d)
  2859. foo(v)
  2860. """
  2861. self.check(b, a)
  2862. b = """
  2863. while x:
  2864. v = t
  2865. v.sort()
  2866. foo(v)
  2867. """
  2868. a = """
  2869. while x:
  2870. v = sorted(t)
  2871. foo(v)
  2872. """
  2873. self.check(b, a)
  2874. b = """
  2875. v = t
  2876. # foo
  2877. v.sort()
  2878. foo(v)
  2879. """
  2880. a = """
  2881. v = sorted(t)
  2882. # foo
  2883. foo(v)
  2884. """
  2885. self.check(b, a)
  2886. b = r"""
  2887. v = t
  2888. v.sort()
  2889. foo(v)
  2890. """
  2891. a = r"""
  2892. v = sorted(t)
  2893. foo(v)
  2894. """
  2895. self.check(b, a)
  2896. def test_sort_unchanged(self):
  2897. s = """
  2898. v = list(t)
  2899. w.sort()
  2900. foo(w)
  2901. """
  2902. self.unchanged(s)
  2903. s = """
  2904. v = list(t)
  2905. v.sort(u)
  2906. foo(v)
  2907. """
  2908. self.unchanged(s)
  2909. class Test_basestring(FixerTestCase):
  2910. fixer = "basestring"
  2911. def test_basestring(self):
  2912. b = """isinstance(x, basestring)"""
  2913. a = """isinstance(x, str)"""
  2914. self.check(b, a)
  2915. class Test_buffer(FixerTestCase):
  2916. fixer = "buffer"
  2917. def test_buffer(self):
  2918. b = """x = buffer(y)"""
  2919. a = """x = memoryview(y)"""
  2920. self.check(b, a)
  2921. def test_slicing(self):
  2922. b = """buffer(y)[4:5]"""
  2923. a = """memoryview(y)[4:5]"""
  2924. self.check(b, a)
  2925. class Test_future(FixerTestCase):
  2926. fixer = "future"
  2927. def test_future(self):
  2928. b = """from __future__ import braces"""
  2929. a = """"""
  2930. self.check(b, a)
  2931. b = """# comment\nfrom __future__ import braces"""
  2932. a = """# comment\n"""
  2933. self.check(b, a)
  2934. b = """from __future__ import braces\n# comment"""
  2935. a = """\n# comment"""
  2936. self.check(b, a)
  2937. def test_run_order(self):
  2938. self.assert_runs_after('print')
  2939. class Test_itertools(FixerTestCase):
  2940. fixer = "itertools"
  2941. def checkall(self, before, after):
  2942. # Because we need to check with and without the itertools prefix
  2943. # and on each of the three functions, these loops make it all
  2944. # much easier
  2945. for i in ('itertools.', ''):
  2946. for f in ('map', 'filter', 'zip'):
  2947. b = before %(i+'i'+f)
  2948. a = after %(f)
  2949. self.check(b, a)
  2950. def test_0(self):
  2951. # A simple example -- test_1 covers exactly the same thing,
  2952. # but it's not quite as clear.
  2953. b = "itertools.izip(a, b)"
  2954. a = "zip(a, b)"
  2955. self.check(b, a)
  2956. def test_1(self):
  2957. b = """%s(f, a)"""
  2958. a = """%s(f, a)"""
  2959. self.checkall(b, a)
  2960. def test_qualified(self):
  2961. b = """itertools.ifilterfalse(a, b)"""
  2962. a = """itertools.filterfalse(a, b)"""
  2963. self.check(b, a)
  2964. b = """itertools.izip_longest(a, b)"""
  2965. a = """itertools.zip_longest(a, b)"""
  2966. self.check(b, a)
  2967. def test_2(self):
  2968. b = """ifilterfalse(a, b)"""
  2969. a = """filterfalse(a, b)"""
  2970. self.check(b, a)
  2971. b = """izip_longest(a, b)"""
  2972. a = """zip_longest(a, b)"""
  2973. self.check(b, a)
  2974. def test_space_1(self):
  2975. b = """ %s(f, a)"""
  2976. a = """ %s(f, a)"""
  2977. self.checkall(b, a)
  2978. def test_space_2(self):
  2979. b = """ itertools.ifilterfalse(a, b)"""
  2980. a = """ itertools.filterfalse(a, b)"""
  2981. self.check(b, a)
  2982. b = """ itertools.izip_longest(a, b)"""
  2983. a = """ itertools.zip_longest(a, b)"""
  2984. self.check(b, a)
  2985. def test_run_order(self):
  2986. self.assert_runs_after('map', 'zip', 'filter')
  2987. class Test_itertools_imports(FixerTestCase):
  2988. fixer = 'itertools_imports'
  2989. def test_reduced(self):
  2990. b = "from itertools import imap, izip, foo"
  2991. a = "from itertools import foo"
  2992. self.check(b, a)
  2993. b = "from itertools import bar, imap, izip, foo"
  2994. a = "from itertools import bar, foo"
  2995. self.check(b, a)
  2996. b = "from itertools import chain, imap, izip"
  2997. a = "from itertools import chain"
  2998. self.check(b, a)
  2999. def test_comments(self):
  3000. b = "#foo\nfrom itertools import imap, izip"
  3001. a = "#foo\n"
  3002. self.check(b, a)
  3003. def test_none(self):
  3004. b = "from itertools import imap, izip"
  3005. a = ""
  3006. self.check(b, a)
  3007. b = "from itertools import izip"
  3008. a = ""
  3009. self.check(b, a)
  3010. def test_import_as(self):
  3011. b = "from itertools import izip, bar as bang, imap"
  3012. a = "from itertools import bar as bang"
  3013. self.check(b, a)
  3014. b = "from itertools import izip as _zip, imap, bar"
  3015. a = "from itertools import bar"
  3016. self.check(b, a)
  3017. b = "from itertools import imap as _map"
  3018. a = ""
  3019. self.check(b, a)
  3020. b = "from itertools import imap as _map, izip as _zip"
  3021. a = ""
  3022. self.check(b, a)
  3023. s = "from itertools import bar as bang"
  3024. self.unchanged(s)
  3025. def test_ifilter_and_zip_longest(self):
  3026. for name in "filterfalse", "zip_longest":
  3027. b = "from itertools import i%s" % (name,)
  3028. a = "from itertools import %s" % (name,)
  3029. self.check(b, a)
  3030. b = "from itertools import imap, i%s, foo" % (name,)
  3031. a = "from itertools import %s, foo" % (name,)
  3032. self.check(b, a)
  3033. b = "from itertools import bar, i%s, foo" % (name,)
  3034. a = "from itertools import bar, %s, foo" % (name,)
  3035. self.check(b, a)
  3036. def test_import_star(self):
  3037. s = "from itertools import *"
  3038. self.unchanged(s)
  3039. def test_unchanged(self):
  3040. s = "from itertools import foo"
  3041. self.unchanged(s)
  3042. class Test_import(FixerTestCase):
  3043. fixer = "import"
  3044. def setUp(self):
  3045. super(Test_import, self).setUp()
  3046. # Need to replace fix_import's exists method
  3047. # so we can check that it's doing the right thing
  3048. self.files_checked = []
  3049. self.present_files = set()
  3050. self.always_exists = True
  3051. def fake_exists(name):
  3052. self.files_checked.append(name)
  3053. return self.always_exists or (name in self.present_files)
  3054. from lib2to3.fixes import fix_import
  3055. fix_import.exists = fake_exists
  3056. def tearDown(self):
  3057. from lib2to3.fixes import fix_import
  3058. fix_import.exists = os.path.exists
  3059. def check_both(self, b, a):
  3060. self.always_exists = True
  3061. super(Test_import, self).check(b, a)
  3062. self.always_exists = False
  3063. super(Test_import, self).unchanged(b)
  3064. def test_files_checked(self):
  3065. def p(path):
  3066. # Takes a unix path and returns a path with correct separators
  3067. return os.path.pathsep.join(path.split("/"))
  3068. self.always_exists = False
  3069. self.present_files = set(['__init__.py'])
  3070. expected_extensions = ('.py', os.path.sep, '.pyc', '.so', '.sl', '.pyd')
  3071. names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))
  3072. for name in names_to_test:
  3073. self.files_checked = []
  3074. self.filename = name
  3075. self.unchanged("import jam")
  3076. if os.path.dirname(name):
  3077. name = os.path.dirname(name) + '/jam'
  3078. else:
  3079. name = 'jam'
  3080. expected_checks = set(name + ext for ext in expected_extensions)
  3081. expected_checks.add("__init__.py")
  3082. self.assertEqual(set(self.files_checked), expected_checks)
  3083. def test_not_in_package(self):
  3084. s = "import bar"
  3085. self.always_exists = False
  3086. self.present_files = set(["bar.py"])
  3087. self.unchanged(s)
  3088. def test_with_absolute_import_enabled(self):
  3089. s = "from __future__ import absolute_import\nimport bar"
  3090. self.always_exists = False
  3091. self.present_files = set(["__init__.py", "bar.py"])
  3092. self.unchanged(s)
  3093. def test_in_package(self):
  3094. b = "import bar"
  3095. a = "from . import bar"
  3096. self.always_exists = False
  3097. self.present_files = set(["__init__.py", "bar.py"])
  3098. self.check(b, a)
  3099. def test_import_from_package(self):
  3100. b = "import bar"
  3101. a = "from . import bar"
  3102. self.always_exists = False
  3103. self.present_files = set(["__init__.py", "bar" + os.path.sep])
  3104. self.check(b, a)
  3105. def test_already_relative_import(self):
  3106. s = "from . import bar"
  3107. self.unchanged(s)
  3108. def test_comments_and_indent(self):
  3109. b = "import bar # Foo"
  3110. a = "from . import bar # Foo"
  3111. self.check(b, a)
  3112. def test_from(self):
  3113. b = "from foo import bar, baz"
  3114. a = "from .foo import bar, baz"
  3115. self.check_both(b, a)
  3116. b = "from foo import bar"
  3117. a = "from .foo import bar"
  3118. self.check_both(b, a)
  3119. b = "from foo import (bar, baz)"
  3120. a = "from .foo import (bar, baz)"
  3121. self.check_both(b, a)
  3122. def test_dotted_from(self):
  3123. b = "from green.eggs import ham"
  3124. a = "from .green.eggs import ham"
  3125. self.check_both(b, a)
  3126. def test_from_as(self):
  3127. b = "from green.eggs import ham as spam"
  3128. a = "from .green.eggs import ham as spam"
  3129. self.check_both(b, a)
  3130. def test_import(self):
  3131. b = "import foo"
  3132. a = "from . import foo"
  3133. self.check_both(b, a)
  3134. b = "import foo, bar"
  3135. a = "from . import foo, bar"
  3136. self.check_both(b, a)
  3137. b = "import foo, bar, x"
  3138. a = "from . import foo, bar, x"
  3139. self.check_both(b, a)
  3140. b = "import x, y, z"
  3141. a = "from . import x, y, z"
  3142. self.check_both(b, a)
  3143. def test_import_as(self):
  3144. b = "import foo as x"
  3145. a = "from . import foo as x"
  3146. self.check_both(b, a)
  3147. b = "import a as b, b as c, c as d"
  3148. a = "from . import a as b, b as c, c as d"
  3149. self.check_both(b, a)
  3150. def test_local_and_absolute(self):
  3151. self.always_exists = False
  3152. self.present_files = set(["foo.py", "__init__.py"])
  3153. s = "import foo, bar"
  3154. self.warns_unchanged(s, "absolute and local imports together")
  3155. def test_dotted_import(self):
  3156. b = "import foo.bar"
  3157. a = "from . import foo.bar"
  3158. self.check_both(b, a)
  3159. def test_dotted_import_as(self):
  3160. b = "import foo.bar as bang"
  3161. a = "from . import foo.bar as bang"
  3162. self.check_both(b, a)
  3163. def test_prefix(self):
  3164. b = """
  3165. # prefix
  3166. import foo.bar
  3167. """
  3168. a = """
  3169. # prefix
  3170. from . import foo.bar
  3171. """
  3172. self.check_both(b, a)
  3173. class Test_set_literal(FixerTestCase):
  3174. fixer = "set_literal"
  3175. def test_basic(self):
  3176. b = """set([1, 2, 3])"""
  3177. a = """{1, 2, 3}"""
  3178. self.check(b, a)
  3179. b = """set((1, 2, 3))"""
  3180. a = """{1, 2, 3}"""
  3181. self.check(b, a)
  3182. b = """set((1,))"""
  3183. a = """{1}"""
  3184. self.check(b, a)
  3185. b = """set([1])"""
  3186. self.check(b, a)
  3187. b = """set((a, b))"""
  3188. a = """{a, b}"""
  3189. self.check(b, a)
  3190. b = """set([a, b])"""
  3191. self.check(b, a)
  3192. b = """set((a*234, f(args=23)))"""
  3193. a = """{a*234, f(args=23)}"""
  3194. self.check(b, a)
  3195. b = """set([a*23, f(23)])"""
  3196. a = """{a*23, f(23)}"""
  3197. self.check(b, a)
  3198. b = """set([a-234**23])"""
  3199. a = """{a-234**23}"""
  3200. self.check(b, a)
  3201. def test_listcomps(self):
  3202. b = """set([x for x in y])"""
  3203. a = """{x for x in y}"""
  3204. self.check(b, a)
  3205. b = """set([x for x in y if x == m])"""
  3206. a = """{x for x in y if x == m}"""
  3207. self.check(b, a)
  3208. b = """set([x for x in y for a in b])"""
  3209. a = """{x for x in y for a in b}"""
  3210. self.check(b, a)
  3211. b = """set([f(x) - 23 for x in y])"""
  3212. a = """{f(x) - 23 for x in y}"""
  3213. self.check(b, a)
  3214. def test_whitespace(self):
  3215. b = """set( [1, 2])"""
  3216. a = """{1, 2}"""
  3217. self.check(b, a)
  3218. b = """set([1 , 2])"""
  3219. a = """{1 , 2}"""
  3220. self.check(b, a)
  3221. b = """set([ 1 ])"""
  3222. a = """{ 1 }"""
  3223. self.check(b, a)
  3224. b = """set( [1] )"""
  3225. a = """{1}"""
  3226. self.check(b, a)
  3227. b = """set([ 1, 2 ])"""
  3228. a = """{ 1, 2 }"""
  3229. self.check(b, a)
  3230. b = """set([x for x in y ])"""
  3231. a = """{x for x in y }"""
  3232. self.check(b, a)
  3233. b = """set(
  3234. [1, 2]
  3235. )
  3236. """
  3237. a = """{1, 2}\n"""
  3238. self.check(b, a)
  3239. def test_comments(self):
  3240. b = """set((1, 2)) # Hi"""
  3241. a = """{1, 2} # Hi"""
  3242. self.check(b, a)
  3243. # This isn't optimal behavior, but the fixer is optional.
  3244. b = """
  3245. # Foo
  3246. set( # Bar
  3247. (1, 2)
  3248. )
  3249. """
  3250. a = """
  3251. # Foo
  3252. {1, 2}
  3253. """
  3254. self.check(b, a)
  3255. def test_unchanged(self):
  3256. s = """set()"""
  3257. self.unchanged(s)
  3258. s = """set(a)"""
  3259. self.unchanged(s)
  3260. s = """set(a, b, c)"""
  3261. self.unchanged(s)
  3262. # Don't transform generators because they might have to be lazy.
  3263. s = """set(x for x in y)"""
  3264. self.unchanged(s)
  3265. s = """set(x for x in y if z)"""
  3266. self.unchanged(s)
  3267. s = """set(a*823-23**2 + f(23))"""
  3268. self.unchanged(s)
  3269. class Test_sys_exc(FixerTestCase):
  3270. fixer = "sys_exc"
  3271. def test_0(self):
  3272. b = "sys.exc_type"
  3273. a = "sys.exc_info()[0]"
  3274. self.check(b, a)
  3275. def test_1(self):
  3276. b = "sys.exc_value"
  3277. a = "sys.exc_info()[1]"
  3278. self.check(b, a)
  3279. def test_2(self):
  3280. b = "sys.exc_traceback"
  3281. a = "sys.exc_info()[2]"
  3282. self.check(b, a)
  3283. def test_3(self):
  3284. b = "sys.exc_type # Foo"
  3285. a = "sys.exc_info()[0] # Foo"
  3286. self.check(b, a)
  3287. def test_4(self):
  3288. b = "sys. exc_type"
  3289. a = "sys. exc_info()[0]"
  3290. self.check(b, a)
  3291. def test_5(self):
  3292. b = "sys .exc_type"
  3293. a = "sys .exc_info()[0]"
  3294. self.check(b, a)
  3295. class Test_paren(FixerTestCase):
  3296. fixer = "paren"
  3297. def test_0(self):
  3298. b = """[i for i in 1, 2 ]"""
  3299. a = """[i for i in (1, 2) ]"""
  3300. self.check(b, a)
  3301. def test_1(self):
  3302. b = """[i for i in 1, 2, ]"""
  3303. a = """[i for i in (1, 2,) ]"""
  3304. self.check(b, a)
  3305. def test_2(self):
  3306. b = """[i for i in 1, 2 ]"""
  3307. a = """[i for i in (1, 2) ]"""
  3308. self.check(b, a)
  3309. def test_3(self):
  3310. b = """[i for i in 1, 2 if i]"""
  3311. a = """[i for i in (1, 2) if i]"""
  3312. self.check(b, a)
  3313. def test_4(self):
  3314. b = """[i for i in 1, 2 ]"""
  3315. a = """[i for i in (1, 2) ]"""
  3316. self.check(b, a)
  3317. def test_5(self):
  3318. b = """(i for i in 1, 2)"""
  3319. a = """(i for i in (1, 2))"""
  3320. self.check(b, a)
  3321. def test_6(self):
  3322. b = """(i for i in 1 ,2 if i)"""
  3323. a = """(i for i in (1 ,2) if i)"""
  3324. self.check(b, a)
  3325. def test_unchanged_0(self):
  3326. s = """[i for i in (1, 2)]"""
  3327. self.unchanged(s)
  3328. def test_unchanged_1(self):
  3329. s = """[i for i in foo()]"""
  3330. self.unchanged(s)
  3331. def test_unchanged_2(self):
  3332. s = """[i for i in (1, 2) if nothing]"""
  3333. self.unchanged(s)
  3334. def test_unchanged_3(self):
  3335. s = """(i for i in (1, 2))"""
  3336. self.unchanged(s)
  3337. def test_unchanged_4(self):
  3338. s = """[i for i in m]"""
  3339. self.unchanged(s)
  3340. class Test_metaclass(FixerTestCase):
  3341. fixer = 'metaclass'
  3342. def test_unchanged(self):
  3343. self.unchanged("class X(): pass")
  3344. self.unchanged("class X(object): pass")
  3345. self.unchanged("class X(object1, object2): pass")
  3346. self.unchanged("class X(object1, object2, object3): pass")
  3347. self.unchanged("class X(metaclass=Meta): pass")
  3348. self.unchanged("class X(b, arg=23, metclass=Meta): pass")
  3349. self.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass")
  3350. s = """
  3351. class X:
  3352. def __metaclass__(self): pass
  3353. """
  3354. self.unchanged(s)
  3355. s = """
  3356. class X:
  3357. a[23] = 74
  3358. """
  3359. self.unchanged(s)
  3360. def test_comments(self):
  3361. b = """
  3362. class X:
  3363. # hi
  3364. __metaclass__ = AppleMeta
  3365. """
  3366. a = """
  3367. class X(metaclass=AppleMeta):
  3368. # hi
  3369. pass
  3370. """
  3371. self.check(b, a)
  3372. b = """
  3373. class X:
  3374. __metaclass__ = Meta
  3375. # Bedtime!
  3376. """
  3377. a = """
  3378. class X(metaclass=Meta):
  3379. pass
  3380. # Bedtime!
  3381. """
  3382. self.check(b, a)
  3383. def test_meta(self):
  3384. # no-parent class, odd body
  3385. b = """
  3386. class X():
  3387. __metaclass__ = Q
  3388. pass
  3389. """
  3390. a = """
  3391. class X(metaclass=Q):
  3392. pass
  3393. """
  3394. self.check(b, a)
  3395. # one parent class, no body
  3396. b = """class X(object): __metaclass__ = Q"""
  3397. a = """class X(object, metaclass=Q): pass"""
  3398. self.check(b, a)
  3399. # one parent, simple body
  3400. b = """
  3401. class X(object):
  3402. __metaclass__ = Meta
  3403. bar = 7
  3404. """
  3405. a = """
  3406. class X(object, metaclass=Meta):
  3407. bar = 7
  3408. """
  3409. self.check(b, a)
  3410. b = """
  3411. class X:
  3412. __metaclass__ = Meta; x = 4; g = 23
  3413. """
  3414. a = """
  3415. class X(metaclass=Meta):
  3416. x = 4; g = 23
  3417. """
  3418. self.check(b, a)
  3419. # one parent, simple body, __metaclass__ last
  3420. b = """
  3421. class X(object):
  3422. bar = 7
  3423. __metaclass__ = Meta
  3424. """
  3425. a = """
  3426. class X(object, metaclass=Meta):
  3427. bar = 7
  3428. """
  3429. self.check(b, a)
  3430. # redefining __metaclass__
  3431. b = """
  3432. class X():
  3433. __metaclass__ = A
  3434. __metaclass__ = B
  3435. bar = 7
  3436. """
  3437. a = """
  3438. class X(metaclass=B):
  3439. bar = 7
  3440. """
  3441. self.check(b, a)
  3442. # multiple inheritance, simple body
  3443. b = """
  3444. class X(clsA, clsB):
  3445. __metaclass__ = Meta
  3446. bar = 7
  3447. """
  3448. a = """
  3449. class X(clsA, clsB, metaclass=Meta):
  3450. bar = 7
  3451. """
  3452. self.check(b, a)
  3453. # keywords in the class statement
  3454. b = """class m(a, arg=23): __metaclass__ = Meta"""
  3455. a = """class m(a, arg=23, metaclass=Meta): pass"""
  3456. self.check(b, a)
  3457. b = """
  3458. class X(expression(2 + 4)):
  3459. __metaclass__ = Meta
  3460. """
  3461. a = """
  3462. class X(expression(2 + 4), metaclass=Meta):
  3463. pass
  3464. """
  3465. self.check(b, a)
  3466. b = """
  3467. class X(expression(2 + 4), x**4):
  3468. __metaclass__ = Meta
  3469. """
  3470. a = """
  3471. class X(expression(2 + 4), x**4, metaclass=Meta):
  3472. pass
  3473. """
  3474. self.check(b, a)
  3475. b = """
  3476. class X:
  3477. __metaclass__ = Meta
  3478. save.py = 23
  3479. """
  3480. a = """
  3481. class X(metaclass=Meta):
  3482. save.py = 23
  3483. """
  3484. self.check(b, a)
  3485. class Test_getcwdu(FixerTestCase):
  3486. fixer = 'getcwdu'
  3487. def test_basic(self):
  3488. b = """os.getcwdu"""
  3489. a = """os.getcwd"""
  3490. self.check(b, a)
  3491. b = """os.getcwdu()"""
  3492. a = """os.getcwd()"""
  3493. self.check(b, a)
  3494. b = """meth = os.getcwdu"""
  3495. a = """meth = os.getcwd"""
  3496. self.check(b, a)
  3497. b = """os.getcwdu(args)"""
  3498. a = """os.getcwd(args)"""
  3499. self.check(b, a)
  3500. def test_comment(self):
  3501. b = """os.getcwdu() # Foo"""
  3502. a = """os.getcwd() # Foo"""
  3503. self.check(b, a)
  3504. def test_unchanged(self):
  3505. s = """os.getcwd()"""
  3506. self.unchanged(s)
  3507. s = """getcwdu()"""
  3508. self.unchanged(s)
  3509. s = """os.getcwdb()"""
  3510. self.unchanged(s)
  3511. def test_indentation(self):
  3512. b = """
  3513. if 1:
  3514. os.getcwdu()
  3515. """
  3516. a = """
  3517. if 1:
  3518. os.getcwd()
  3519. """
  3520. self.check(b, a)
  3521. def test_multilation(self):
  3522. b = """os .getcwdu()"""
  3523. a = """os .getcwd()"""
  3524. self.check(b, a)
  3525. b = """os. getcwdu"""
  3526. a = """os. getcwd"""
  3527. self.check(b, a)
  3528. b = """os.getcwdu ( )"""
  3529. a = """os.getcwd ( )"""
  3530. self.check(b, a)
  3531. class Test_operator(FixerTestCase):
  3532. fixer = "operator"
  3533. def test_operator_isCallable(self):
  3534. b = "operator.isCallable(x)"
  3535. a = "hasattr(x, '__call__')"
  3536. self.check(b, a)
  3537. def test_operator_sequenceIncludes(self):
  3538. b = "operator.sequenceIncludes(x, y)"
  3539. a = "operator.contains(x, y)"
  3540. self.check(b, a)
  3541. b = "operator .sequenceIncludes(x, y)"
  3542. a = "operator .contains(x, y)"
  3543. self.check(b, a)
  3544. b = "operator. sequenceIncludes(x, y)"
  3545. a = "operator. contains(x, y)"
  3546. self.check(b, a)
  3547. def test_operator_isSequenceType(self):
  3548. b = "operator.isSequenceType(x)"
  3549. a = "import collections\nisinstance(x, collections.Sequence)"
  3550. self.check(b, a)
  3551. def test_operator_isMappingType(self):
  3552. b = "operator.isMappingType(x)"
  3553. a = "import collections\nisinstance(x, collections.Mapping)"
  3554. self.check(b, a)
  3555. def test_operator_isNumberType(self):
  3556. b = "operator.isNumberType(x)"
  3557. a = "import numbers\nisinstance(x, numbers.Number)"
  3558. self.check(b, a)
  3559. def test_operator_repeat(self):
  3560. b = "operator.repeat(x, n)"
  3561. a = "operator.mul(x, n)"
  3562. self.check(b, a)
  3563. b = "operator .repeat(x, n)"
  3564. a = "operator .mul(x, n)"
  3565. self.check(b, a)
  3566. b = "operator. repeat(x, n)"
  3567. a = "operator. mul(x, n)"
  3568. self.check(b, a)
  3569. def test_operator_irepeat(self):
  3570. b = "operator.irepeat(x, n)"
  3571. a = "operator.imul(x, n)"
  3572. self.check(b, a)
  3573. b = "operator .irepeat(x, n)"
  3574. a = "operator .imul(x, n)"
  3575. self.check(b, a)
  3576. b = "operator. irepeat(x, n)"
  3577. a = "operator. imul(x, n)"
  3578. self.check(b, a)
  3579. def test_bare_isCallable(self):
  3580. s = "isCallable(x)"
  3581. t = "You should use 'hasattr(x, '__call__')' here."
  3582. self.warns_unchanged(s, t)
  3583. def test_bare_sequenceIncludes(self):
  3584. s = "sequenceIncludes(x, y)"
  3585. t = "You should use 'operator.contains(x, y)' here."
  3586. self.warns_unchanged(s, t)
  3587. def test_bare_operator_isSequenceType(self):
  3588. s = "isSequenceType(z)"
  3589. t = "You should use 'isinstance(z, collections.Sequence)' here."
  3590. self.warns_unchanged(s, t)
  3591. def test_bare_operator_isMappingType(self):
  3592. s = "isMappingType(x)"
  3593. t = "You should use 'isinstance(x, collections.Mapping)' here."
  3594. self.warns_unchanged(s, t)
  3595. def test_bare_operator_isNumberType(self):
  3596. s = "isNumberType(y)"
  3597. t = "You should use 'isinstance(y, numbers.Number)' here."
  3598. self.warns_unchanged(s, t)
  3599. def test_bare_operator_repeat(self):
  3600. s = "repeat(x, n)"
  3601. t = "You should use 'operator.mul(x, n)' here."
  3602. self.warns_unchanged(s, t)
  3603. def test_bare_operator_irepeat(self):
  3604. s = "irepeat(y, 187)"
  3605. t = "You should use 'operator.imul(y, 187)' here."
  3606. self.warns_unchanged(s, t)
  3607. class Test_exitfunc(FixerTestCase):
  3608. fixer = "exitfunc"
  3609. def test_simple(self):
  3610. b = """
  3611. import sys
  3612. sys.exitfunc = my_atexit
  3613. """
  3614. a = """
  3615. import sys
  3616. import atexit
  3617. atexit.register(my_atexit)
  3618. """
  3619. self.check(b, a)
  3620. def test_names_import(self):
  3621. b = """
  3622. import sys, crumbs
  3623. sys.exitfunc = my_func
  3624. """
  3625. a = """
  3626. import sys, crumbs, atexit
  3627. atexit.register(my_func)
  3628. """
  3629. self.check(b, a)
  3630. def test_complex_expression(self):
  3631. b = """
  3632. import sys
  3633. sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
  3634. """
  3635. a = """
  3636. import sys
  3637. import atexit
  3638. atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
  3639. """
  3640. self.check(b, a)
  3641. def test_comments(self):
  3642. b = """
  3643. import sys # Foo
  3644. sys.exitfunc = f # Blah
  3645. """
  3646. a = """
  3647. import sys
  3648. import atexit # Foo
  3649. atexit.register(f) # Blah
  3650. """
  3651. self.check(b, a)
  3652. b = """
  3653. import apples, sys, crumbs, larry # Pleasant comments
  3654. sys.exitfunc = func
  3655. """
  3656. a = """
  3657. import apples, sys, crumbs, larry, atexit # Pleasant comments
  3658. atexit.register(func)
  3659. """
  3660. self.check(b, a)
  3661. def test_in_a_function(self):
  3662. b = """
  3663. import sys
  3664. def f():
  3665. sys.exitfunc = func
  3666. """
  3667. a = """
  3668. import sys
  3669. import atexit
  3670. def f():
  3671. atexit.register(func)
  3672. """
  3673. self.check(b, a)
  3674. def test_no_sys_import(self):
  3675. b = """sys.exitfunc = f"""
  3676. a = """atexit.register(f)"""
  3677. msg = ("Can't find sys import; Please add an atexit import at the "
  3678. "top of your file.")
  3679. self.warns(b, a, msg)
  3680. def test_unchanged(self):
  3681. s = """f(sys.exitfunc)"""
  3682. self.unchanged(s)