PageRenderTime 58ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

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

http://github.com/IronLanguages/main
Python | 4632 lines | 4554 code | 73 blank | 5 comment | 11 complexity | 4b3a84ec97cda92606886a9328dbf380 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. """ Test suite for the fixer modules """
  2. # Python imports
  3. import os
  4. import unittest
  5. from itertools import chain
  6. from operator import itemgetter
  7. # Local imports
  8. from lib2to3 import pygram, pytree, refactor, fixer_util
  9. from lib2to3.tests import support
  10. class FixerTestCase(support.TestCase):
  11. # Other test cases can subclass this class and replace "fixer_pkg" with
  12. # their own.
  13. def setUp(self, fix_list=None, fixer_pkg="lib2to3", options=None):
  14. if fix_list is None:
  15. fix_list = [self.fixer]
  16. self.refactor = support.get_refactorer(fixer_pkg, fix_list, options)
  17. self.fixer_log = []
  18. self.filename = u"<string>"
  19. for fixer in chain(self.refactor.pre_order,
  20. self.refactor.post_order):
  21. fixer.log = self.fixer_log
  22. def _check(self, before, after):
  23. before = support.reformat(before)
  24. after = support.reformat(after)
  25. tree = self.refactor.refactor_string(before, self.filename)
  26. self.assertEqual(after, unicode(tree))
  27. return tree
  28. def check(self, before, after, ignore_warnings=False):
  29. tree = self._check(before, after)
  30. self.assertTrue(tree.was_changed)
  31. if not ignore_warnings:
  32. self.assertEqual(self.fixer_log, [])
  33. def warns(self, before, after, message, unchanged=False):
  34. tree = self._check(before, after)
  35. self.assertIn(message, "".join(self.fixer_log))
  36. if not unchanged:
  37. self.assertTrue(tree.was_changed)
  38. def warns_unchanged(self, before, message):
  39. self.warns(before, before, message, unchanged=True)
  40. def unchanged(self, before, ignore_warnings=False):
  41. self._check(before, before)
  42. if not ignore_warnings:
  43. self.assertEqual(self.fixer_log, [])
  44. def assert_runs_after(self, *names):
  45. fixes = [self.fixer]
  46. fixes.extend(names)
  47. r = support.get_refactorer("lib2to3", fixes)
  48. (pre, post) = r.get_fixers()
  49. n = "fix_" + self.fixer
  50. if post and post[-1].__class__.__module__.endswith(n):
  51. # We're the last fixer to run
  52. return
  53. if pre and pre[-1].__class__.__module__.endswith(n) and not post:
  54. # We're the last in pre and post is empty
  55. return
  56. self.fail("Fixer run order (%s) is incorrect; %s should be last."\
  57. %(", ".join([x.__class__.__module__ for x in (pre+post)]), n))
  58. class Test_ne(FixerTestCase):
  59. fixer = "ne"
  60. def test_basic(self):
  61. b = """if x <> y:
  62. pass"""
  63. a = """if x != y:
  64. pass"""
  65. self.check(b, a)
  66. def test_no_spaces(self):
  67. b = """if x<>y:
  68. pass"""
  69. a = """if x!=y:
  70. pass"""
  71. self.check(b, a)
  72. def test_chained(self):
  73. b = """if x<>y<>z:
  74. pass"""
  75. a = """if x!=y!=z:
  76. pass"""
  77. self.check(b, a)
  78. class Test_has_key(FixerTestCase):
  79. fixer = "has_key"
  80. def test_1(self):
  81. b = """x = d.has_key("x") or d.has_key("y")"""
  82. a = """x = "x" in d or "y" in d"""
  83. self.check(b, a)
  84. def test_2(self):
  85. b = """x = a.b.c.d.has_key("x") ** 3"""
  86. a = """x = ("x" in a.b.c.d) ** 3"""
  87. self.check(b, a)
  88. def test_3(self):
  89. b = """x = a.b.has_key(1 + 2).__repr__()"""
  90. a = """x = (1 + 2 in a.b).__repr__()"""
  91. self.check(b, a)
  92. def test_4(self):
  93. b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4"""
  94. a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4"""
  95. self.check(b, a)
  96. def test_5(self):
  97. b = """x = a.has_key(f or g)"""
  98. a = """x = (f or g) in a"""
  99. self.check(b, a)
  100. def test_6(self):
  101. b = """x = a + b.has_key(c)"""
  102. a = """x = a + (c in b)"""
  103. self.check(b, a)
  104. def test_7(self):
  105. b = """x = a.has_key(lambda: 12)"""
  106. a = """x = (lambda: 12) in a"""
  107. self.check(b, a)
  108. def test_8(self):
  109. b = """x = a.has_key(a for a in b)"""
  110. a = """x = (a for a in b) in a"""
  111. self.check(b, a)
  112. def test_9(self):
  113. b = """if not a.has_key(b): pass"""
  114. a = """if b not in a: pass"""
  115. self.check(b, a)
  116. def test_10(self):
  117. b = """if not a.has_key(b).__repr__(): pass"""
  118. a = """if not (b in a).__repr__(): pass"""
  119. self.check(b, a)
  120. def test_11(self):
  121. b = """if not a.has_key(b) ** 2: pass"""
  122. a = """if not (b in a) ** 2: pass"""
  123. self.check(b, a)
  124. class Test_apply(FixerTestCase):
  125. fixer = "apply"
  126. def test_1(self):
  127. b = """x = apply(f, g + h)"""
  128. a = """x = f(*g + h)"""
  129. self.check(b, a)
  130. def test_2(self):
  131. b = """y = apply(f, g, h)"""
  132. a = """y = f(*g, **h)"""
  133. self.check(b, a)
  134. def test_3(self):
  135. b = """z = apply(fs[0], g or h, h or g)"""
  136. a = """z = fs[0](*g or h, **h or g)"""
  137. self.check(b, a)
  138. def test_4(self):
  139. b = """apply(f, (x, y) + t)"""
  140. a = """f(*(x, y) + t)"""
  141. self.check(b, a)
  142. def test_5(self):
  143. b = """apply(f, args,)"""
  144. a = """f(*args)"""
  145. self.check(b, a)
  146. def test_6(self):
  147. b = """apply(f, args, kwds,)"""
  148. a = """f(*args, **kwds)"""
  149. self.check(b, a)
  150. # Test that complex functions are parenthesized
  151. def test_complex_1(self):
  152. b = """x = apply(f+g, args)"""
  153. a = """x = (f+g)(*args)"""
  154. self.check(b, a)
  155. def test_complex_2(self):
  156. b = """x = apply(f*g, args)"""
  157. a = """x = (f*g)(*args)"""
  158. self.check(b, a)
  159. def test_complex_3(self):
  160. b = """x = apply(f**g, args)"""
  161. a = """x = (f**g)(*args)"""
  162. self.check(b, a)
  163. # But dotted names etc. not
  164. def test_dotted_name(self):
  165. b = """x = apply(f.g, args)"""
  166. a = """x = f.g(*args)"""
  167. self.check(b, a)
  168. def test_subscript(self):
  169. b = """x = apply(f[x], args)"""
  170. a = """x = f[x](*args)"""
  171. self.check(b, a)
  172. def test_call(self):
  173. b = """x = apply(f(), args)"""
  174. a = """x = f()(*args)"""
  175. self.check(b, a)
  176. # Extreme case
  177. def test_extreme(self):
  178. b = """x = apply(a.b.c.d.e.f, args, kwds)"""
  179. a = """x = a.b.c.d.e.f(*args, **kwds)"""
  180. self.check(b, a)
  181. # XXX Comments in weird places still get lost
  182. def test_weird_comments(self):
  183. b = """apply( # foo
  184. f, # bar
  185. args)"""
  186. a = """f(*args)"""
  187. self.check(b, a)
  188. # These should *not* be touched
  189. def test_unchanged_1(self):
  190. s = """apply()"""
  191. self.unchanged(s)
  192. def test_unchanged_2(self):
  193. s = """apply(f)"""
  194. self.unchanged(s)
  195. def test_unchanged_3(self):
  196. s = """apply(f,)"""
  197. self.unchanged(s)
  198. def test_unchanged_4(self):
  199. s = """apply(f, args, kwds, extras)"""
  200. self.unchanged(s)
  201. def test_unchanged_5(self):
  202. s = """apply(f, *args, **kwds)"""
  203. self.unchanged(s)
  204. def test_unchanged_6(self):
  205. s = """apply(f, *args)"""
  206. self.unchanged(s)
  207. def test_unchanged_7(self):
  208. s = """apply(func=f, args=args, kwds=kwds)"""
  209. self.unchanged(s)
  210. def test_unchanged_8(self):
  211. s = """apply(f, args=args, kwds=kwds)"""
  212. self.unchanged(s)
  213. def test_unchanged_9(self):
  214. s = """apply(f, args, kwds=kwds)"""
  215. self.unchanged(s)
  216. def test_space_1(self):
  217. a = """apply( f, args, kwds)"""
  218. b = """f(*args, **kwds)"""
  219. self.check(a, b)
  220. def test_space_2(self):
  221. a = """apply( f ,args,kwds )"""
  222. b = """f(*args, **kwds)"""
  223. self.check(a, b)
  224. class Test_intern(FixerTestCase):
  225. fixer = "intern"
  226. def test_prefix_preservation(self):
  227. b = """x = intern( a )"""
  228. a = """import sys\nx = sys.intern( a )"""
  229. self.check(b, a)
  230. b = """y = intern("b" # test
  231. )"""
  232. a = """import sys\ny = sys.intern("b" # test
  233. )"""
  234. self.check(b, a)
  235. b = """z = intern(a+b+c.d, )"""
  236. a = """import sys\nz = sys.intern(a+b+c.d, )"""
  237. self.check(b, a)
  238. def test(self):
  239. b = """x = intern(a)"""
  240. a = """import sys\nx = sys.intern(a)"""
  241. self.check(b, a)
  242. b = """z = intern(a+b+c.d,)"""
  243. a = """import sys\nz = sys.intern(a+b+c.d,)"""
  244. self.check(b, a)
  245. b = """intern("y%s" % 5).replace("y", "")"""
  246. a = """import sys\nsys.intern("y%s" % 5).replace("y", "")"""
  247. self.check(b, a)
  248. # These should not be refactored
  249. def test_unchanged(self):
  250. s = """intern(a=1)"""
  251. self.unchanged(s)
  252. s = """intern(f, g)"""
  253. self.unchanged(s)
  254. s = """intern(*h)"""
  255. self.unchanged(s)
  256. s = """intern(**i)"""
  257. self.unchanged(s)
  258. s = """intern()"""
  259. self.unchanged(s)
  260. class Test_reduce(FixerTestCase):
  261. fixer = "reduce"
  262. def test_simple_call(self):
  263. b = "reduce(a, b, c)"
  264. a = "from functools import reduce\nreduce(a, b, c)"
  265. self.check(b, a)
  266. def test_bug_7253(self):
  267. # fix_tuple_params was being bad and orphaning nodes in the tree.
  268. b = "def x(arg): reduce(sum, [])"
  269. a = "from functools import reduce\ndef x(arg): reduce(sum, [])"
  270. self.check(b, a)
  271. def test_call_with_lambda(self):
  272. b = "reduce(lambda x, y: x + y, seq)"
  273. a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)"
  274. self.check(b, a)
  275. def test_unchanged(self):
  276. s = "reduce(a)"
  277. self.unchanged(s)
  278. s = "reduce(a, b=42)"
  279. self.unchanged(s)
  280. s = "reduce(a, b, c, d)"
  281. self.unchanged(s)
  282. s = "reduce(**c)"
  283. self.unchanged(s)
  284. s = "reduce()"
  285. self.unchanged(s)
  286. class Test_print(FixerTestCase):
  287. fixer = "print"
  288. def test_prefix_preservation(self):
  289. b = """print 1, 1+1, 1+1+1"""
  290. a = """print(1, 1+1, 1+1+1)"""
  291. self.check(b, a)
  292. def test_idempotency(self):
  293. s = """print()"""
  294. self.unchanged(s)
  295. s = """print('')"""
  296. self.unchanged(s)
  297. def test_idempotency_print_as_function(self):
  298. self.refactor.driver.grammar = pygram.python_grammar_no_print_statement
  299. s = """print(1, 1+1, 1+1+1)"""
  300. self.unchanged(s)
  301. s = """print()"""
  302. self.unchanged(s)
  303. s = """print('')"""
  304. self.unchanged(s)
  305. def test_1(self):
  306. b = """print 1, 1+1, 1+1+1"""
  307. a = """print(1, 1+1, 1+1+1)"""
  308. self.check(b, a)
  309. def test_2(self):
  310. b = """print 1, 2"""
  311. a = """print(1, 2)"""
  312. self.check(b, a)
  313. def test_3(self):
  314. b = """print"""
  315. a = """print()"""
  316. self.check(b, a)
  317. def test_4(self):
  318. # from bug 3000
  319. b = """print whatever; print"""
  320. a = """print(whatever); print()"""
  321. self.check(b, a)
  322. def test_5(self):
  323. b = """print; print whatever;"""
  324. a = """print(); print(whatever);"""
  325. self.check(b, a)
  326. def test_tuple(self):
  327. b = """print (a, b, c)"""
  328. a = """print((a, b, c))"""
  329. self.check(b, a)
  330. # trailing commas
  331. def test_trailing_comma_1(self):
  332. b = """print 1, 2, 3,"""
  333. a = """print(1, 2, 3, end=' ')"""
  334. self.check(b, a)
  335. def test_trailing_comma_2(self):
  336. b = """print 1, 2,"""
  337. a = """print(1, 2, end=' ')"""
  338. self.check(b, a)
  339. def test_trailing_comma_3(self):
  340. b = """print 1,"""
  341. a = """print(1, end=' ')"""
  342. self.check(b, a)
  343. # >> stuff
  344. def test_vargs_without_trailing_comma(self):
  345. b = """print >>sys.stderr, 1, 2, 3"""
  346. a = """print(1, 2, 3, file=sys.stderr)"""
  347. self.check(b, a)
  348. def test_with_trailing_comma(self):
  349. b = """print >>sys.stderr, 1, 2,"""
  350. a = """print(1, 2, end=' ', file=sys.stderr)"""
  351. self.check(b, a)
  352. def test_no_trailing_comma(self):
  353. b = """print >>sys.stderr, 1+1"""
  354. a = """print(1+1, file=sys.stderr)"""
  355. self.check(b, a)
  356. def test_spaces_before_file(self):
  357. b = """print >> sys.stderr"""
  358. a = """print(file=sys.stderr)"""
  359. self.check(b, a)
  360. def test_with_future_print_function(self):
  361. s = "from __future__ import print_function\n" \
  362. "print('Hai!', end=' ')"
  363. self.unchanged(s)
  364. b = "print 'Hello, world!'"
  365. a = "print('Hello, world!')"
  366. self.check(b, a)
  367. class Test_exec(FixerTestCase):
  368. fixer = "exec"
  369. def test_prefix_preservation(self):
  370. b = """ exec code in ns1, ns2"""
  371. a = """ exec(code, ns1, ns2)"""
  372. self.check(b, a)
  373. def test_basic(self):
  374. b = """exec code"""
  375. a = """exec(code)"""
  376. self.check(b, a)
  377. def test_with_globals(self):
  378. b = """exec code in ns"""
  379. a = """exec(code, ns)"""
  380. self.check(b, a)
  381. def test_with_globals_locals(self):
  382. b = """exec code in ns1, ns2"""
  383. a = """exec(code, ns1, ns2)"""
  384. self.check(b, a)
  385. def test_complex_1(self):
  386. b = """exec (a.b()) in ns"""
  387. a = """exec((a.b()), ns)"""
  388. self.check(b, a)
  389. def test_complex_2(self):
  390. b = """exec a.b() + c in ns"""
  391. a = """exec(a.b() + c, ns)"""
  392. self.check(b, a)
  393. # These should not be touched
  394. def test_unchanged_1(self):
  395. s = """exec(code)"""
  396. self.unchanged(s)
  397. def test_unchanged_2(self):
  398. s = """exec (code)"""
  399. self.unchanged(s)
  400. def test_unchanged_3(self):
  401. s = """exec(code, ns)"""
  402. self.unchanged(s)
  403. def test_unchanged_4(self):
  404. s = """exec(code, ns1, ns2)"""
  405. self.unchanged(s)
  406. class Test_repr(FixerTestCase):
  407. fixer = "repr"
  408. def test_prefix_preservation(self):
  409. b = """x = `1 + 2`"""
  410. a = """x = repr(1 + 2)"""
  411. self.check(b, a)
  412. def test_simple_1(self):
  413. b = """x = `1 + 2`"""
  414. a = """x = repr(1 + 2)"""
  415. self.check(b, a)
  416. def test_simple_2(self):
  417. b = """y = `x`"""
  418. a = """y = repr(x)"""
  419. self.check(b, a)
  420. def test_complex(self):
  421. b = """z = `y`.__repr__()"""
  422. a = """z = repr(y).__repr__()"""
  423. self.check(b, a)
  424. def test_tuple(self):
  425. b = """x = `1, 2, 3`"""
  426. a = """x = repr((1, 2, 3))"""
  427. self.check(b, a)
  428. def test_nested(self):
  429. b = """x = `1 + `2``"""
  430. a = """x = repr(1 + repr(2))"""
  431. self.check(b, a)
  432. def test_nested_tuples(self):
  433. b = """x = `1, 2 + `3, 4``"""
  434. a = """x = repr((1, 2 + repr((3, 4))))"""
  435. self.check(b, a)
  436. class Test_except(FixerTestCase):
  437. fixer = "except"
  438. def test_prefix_preservation(self):
  439. b = """
  440. try:
  441. pass
  442. except (RuntimeError, ImportError), e:
  443. pass"""
  444. a = """
  445. try:
  446. pass
  447. except (RuntimeError, ImportError) as e:
  448. pass"""
  449. self.check(b, a)
  450. def test_simple(self):
  451. b = """
  452. try:
  453. pass
  454. except Foo, e:
  455. pass"""
  456. a = """
  457. try:
  458. pass
  459. except Foo as e:
  460. pass"""
  461. self.check(b, a)
  462. def test_simple_no_space_before_target(self):
  463. b = """
  464. try:
  465. pass
  466. except Foo,e:
  467. pass"""
  468. a = """
  469. try:
  470. pass
  471. except Foo as e:
  472. pass"""
  473. self.check(b, a)
  474. def test_tuple_unpack(self):
  475. b = """
  476. def foo():
  477. try:
  478. pass
  479. except Exception, (f, e):
  480. pass
  481. except ImportError, e:
  482. pass"""
  483. a = """
  484. def foo():
  485. try:
  486. pass
  487. except Exception as xxx_todo_changeme:
  488. (f, e) = xxx_todo_changeme.args
  489. pass
  490. except ImportError as e:
  491. pass"""
  492. self.check(b, a)
  493. def test_multi_class(self):
  494. b = """
  495. try:
  496. pass
  497. except (RuntimeError, ImportError), e:
  498. pass"""
  499. a = """
  500. try:
  501. pass
  502. except (RuntimeError, ImportError) as e:
  503. pass"""
  504. self.check(b, a)
  505. def test_list_unpack(self):
  506. b = """
  507. try:
  508. pass
  509. except Exception, [a, b]:
  510. pass"""
  511. a = """
  512. try:
  513. pass
  514. except Exception as xxx_todo_changeme:
  515. [a, b] = xxx_todo_changeme.args
  516. pass"""
  517. self.check(b, a)
  518. def test_weird_target_1(self):
  519. b = """
  520. try:
  521. pass
  522. except Exception, d[5]:
  523. pass"""
  524. a = """
  525. try:
  526. pass
  527. except Exception as xxx_todo_changeme:
  528. d[5] = xxx_todo_changeme
  529. pass"""
  530. self.check(b, a)
  531. def test_weird_target_2(self):
  532. b = """
  533. try:
  534. pass
  535. except Exception, a.foo:
  536. pass"""
  537. a = """
  538. try:
  539. pass
  540. except Exception as xxx_todo_changeme:
  541. a.foo = xxx_todo_changeme
  542. pass"""
  543. self.check(b, a)
  544. def test_weird_target_3(self):
  545. b = """
  546. try:
  547. pass
  548. except Exception, a().foo:
  549. pass"""
  550. a = """
  551. try:
  552. pass
  553. except Exception as xxx_todo_changeme:
  554. a().foo = xxx_todo_changeme
  555. pass"""
  556. self.check(b, a)
  557. def test_bare_except(self):
  558. b = """
  559. try:
  560. pass
  561. except Exception, a:
  562. pass
  563. except:
  564. pass"""
  565. a = """
  566. try:
  567. pass
  568. except Exception as a:
  569. pass
  570. except:
  571. pass"""
  572. self.check(b, a)
  573. def test_bare_except_and_else_finally(self):
  574. b = """
  575. try:
  576. pass
  577. except Exception, a:
  578. pass
  579. except:
  580. pass
  581. else:
  582. pass
  583. finally:
  584. pass"""
  585. a = """
  586. try:
  587. pass
  588. except Exception as a:
  589. pass
  590. except:
  591. pass
  592. else:
  593. pass
  594. finally:
  595. pass"""
  596. self.check(b, a)
  597. def test_multi_fixed_excepts_before_bare_except(self):
  598. b = """
  599. try:
  600. pass
  601. except TypeError, b:
  602. pass
  603. except Exception, a:
  604. pass
  605. except:
  606. pass"""
  607. a = """
  608. try:
  609. pass
  610. except TypeError as b:
  611. pass
  612. except Exception as a:
  613. pass
  614. except:
  615. pass"""
  616. self.check(b, a)
  617. def test_one_line_suites(self):
  618. b = """
  619. try: raise TypeError
  620. except TypeError, e:
  621. pass
  622. """
  623. a = """
  624. try: raise TypeError
  625. except TypeError as e:
  626. pass
  627. """
  628. self.check(b, a)
  629. b = """
  630. try:
  631. raise TypeError
  632. except TypeError, e: pass
  633. """
  634. a = """
  635. try:
  636. raise TypeError
  637. except TypeError as e: pass
  638. """
  639. self.check(b, a)
  640. b = """
  641. try: raise TypeError
  642. except TypeError, e: pass
  643. """
  644. a = """
  645. try: raise TypeError
  646. except TypeError as e: pass
  647. """
  648. self.check(b, a)
  649. b = """
  650. try: raise TypeError
  651. except TypeError, e: pass
  652. else: function()
  653. finally: done()
  654. """
  655. a = """
  656. try: raise TypeError
  657. except TypeError as e: pass
  658. else: function()
  659. finally: done()
  660. """
  661. self.check(b, a)
  662. # These should not be touched:
  663. def test_unchanged_1(self):
  664. s = """
  665. try:
  666. pass
  667. except:
  668. pass"""
  669. self.unchanged(s)
  670. def test_unchanged_2(self):
  671. s = """
  672. try:
  673. pass
  674. except Exception:
  675. pass"""
  676. self.unchanged(s)
  677. def test_unchanged_3(self):
  678. s = """
  679. try:
  680. pass
  681. except (Exception, SystemExit):
  682. pass"""
  683. self.unchanged(s)
  684. class Test_raise(FixerTestCase):
  685. fixer = "raise"
  686. def test_basic(self):
  687. b = """raise Exception, 5"""
  688. a = """raise Exception(5)"""
  689. self.check(b, a)
  690. def test_prefix_preservation(self):
  691. b = """raise Exception,5"""
  692. a = """raise Exception(5)"""
  693. self.check(b, a)
  694. b = """raise Exception, 5"""
  695. a = """raise Exception(5)"""
  696. self.check(b, a)
  697. def test_with_comments(self):
  698. b = """raise Exception, 5 # foo"""
  699. a = """raise Exception(5) # foo"""
  700. self.check(b, a)
  701. b = """raise E, (5, 6) % (a, b) # foo"""
  702. a = """raise E((5, 6) % (a, b)) # foo"""
  703. self.check(b, a)
  704. b = """def foo():
  705. raise Exception, 5, 6 # foo"""
  706. a = """def foo():
  707. raise Exception(5).with_traceback(6) # foo"""
  708. self.check(b, a)
  709. def test_None_value(self):
  710. b = """raise Exception(5), None, tb"""
  711. a = """raise Exception(5).with_traceback(tb)"""
  712. self.check(b, a)
  713. def test_tuple_value(self):
  714. b = """raise Exception, (5, 6, 7)"""
  715. a = """raise Exception(5, 6, 7)"""
  716. self.check(b, a)
  717. def test_tuple_detection(self):
  718. b = """raise E, (5, 6) % (a, b)"""
  719. a = """raise E((5, 6) % (a, b))"""
  720. self.check(b, a)
  721. def test_tuple_exc_1(self):
  722. b = """raise (((E1, E2), E3), E4), V"""
  723. a = """raise E1(V)"""
  724. self.check(b, a)
  725. def test_tuple_exc_2(self):
  726. b = """raise (E1, (E2, E3), E4), V"""
  727. a = """raise E1(V)"""
  728. self.check(b, a)
  729. # These should produce a warning
  730. def test_string_exc(self):
  731. s = """raise 'foo'"""
  732. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  733. def test_string_exc_val(self):
  734. s = """raise "foo", 5"""
  735. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  736. def test_string_exc_val_tb(self):
  737. s = """raise "foo", 5, 6"""
  738. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  739. # These should result in traceback-assignment
  740. def test_tb_1(self):
  741. b = """def foo():
  742. raise Exception, 5, 6"""
  743. a = """def foo():
  744. raise Exception(5).with_traceback(6)"""
  745. self.check(b, a)
  746. def test_tb_2(self):
  747. b = """def foo():
  748. a = 5
  749. raise Exception, 5, 6
  750. b = 6"""
  751. a = """def foo():
  752. a = 5
  753. raise Exception(5).with_traceback(6)
  754. b = 6"""
  755. self.check(b, a)
  756. def test_tb_3(self):
  757. b = """def foo():
  758. raise Exception,5,6"""
  759. a = """def foo():
  760. raise Exception(5).with_traceback(6)"""
  761. self.check(b, a)
  762. def test_tb_4(self):
  763. b = """def foo():
  764. a = 5
  765. raise Exception,5,6
  766. b = 6"""
  767. a = """def foo():
  768. a = 5
  769. raise Exception(5).with_traceback(6)
  770. b = 6"""
  771. self.check(b, a)
  772. def test_tb_5(self):
  773. b = """def foo():
  774. raise Exception, (5, 6, 7), 6"""
  775. a = """def foo():
  776. raise Exception(5, 6, 7).with_traceback(6)"""
  777. self.check(b, a)
  778. def test_tb_6(self):
  779. b = """def foo():
  780. a = 5
  781. raise Exception, (5, 6, 7), 6
  782. b = 6"""
  783. a = """def foo():
  784. a = 5
  785. raise Exception(5, 6, 7).with_traceback(6)
  786. b = 6"""
  787. self.check(b, a)
  788. class Test_throw(FixerTestCase):
  789. fixer = "throw"
  790. def test_1(self):
  791. b = """g.throw(Exception, 5)"""
  792. a = """g.throw(Exception(5))"""
  793. self.check(b, a)
  794. def test_2(self):
  795. b = """g.throw(Exception,5)"""
  796. a = """g.throw(Exception(5))"""
  797. self.check(b, a)
  798. def test_3(self):
  799. b = """g.throw(Exception, (5, 6, 7))"""
  800. a = """g.throw(Exception(5, 6, 7))"""
  801. self.check(b, a)
  802. def test_4(self):
  803. b = """5 + g.throw(Exception, 5)"""
  804. a = """5 + g.throw(Exception(5))"""
  805. self.check(b, a)
  806. # These should produce warnings
  807. def test_warn_1(self):
  808. s = """g.throw("foo")"""
  809. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  810. def test_warn_2(self):
  811. s = """g.throw("foo", 5)"""
  812. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  813. def test_warn_3(self):
  814. s = """g.throw("foo", 5, 6)"""
  815. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  816. # These should not be touched
  817. def test_untouched_1(self):
  818. s = """g.throw(Exception)"""
  819. self.unchanged(s)
  820. def test_untouched_2(self):
  821. s = """g.throw(Exception(5, 6))"""
  822. self.unchanged(s)
  823. def test_untouched_3(self):
  824. s = """5 + g.throw(Exception(5, 6))"""
  825. self.unchanged(s)
  826. # These should result in traceback-assignment
  827. def test_tb_1(self):
  828. b = """def foo():
  829. g.throw(Exception, 5, 6)"""
  830. a = """def foo():
  831. g.throw(Exception(5).with_traceback(6))"""
  832. self.check(b, a)
  833. def test_tb_2(self):
  834. b = """def foo():
  835. a = 5
  836. g.throw(Exception, 5, 6)
  837. b = 6"""
  838. a = """def foo():
  839. a = 5
  840. g.throw(Exception(5).with_traceback(6))
  841. b = 6"""
  842. self.check(b, a)
  843. def test_tb_3(self):
  844. b = """def foo():
  845. g.throw(Exception,5,6)"""
  846. a = """def foo():
  847. g.throw(Exception(5).with_traceback(6))"""
  848. self.check(b, a)
  849. def test_tb_4(self):
  850. b = """def foo():
  851. a = 5
  852. g.throw(Exception,5,6)
  853. b = 6"""
  854. a = """def foo():
  855. a = 5
  856. g.throw(Exception(5).with_traceback(6))
  857. b = 6"""
  858. self.check(b, a)
  859. def test_tb_5(self):
  860. b = """def foo():
  861. g.throw(Exception, (5, 6, 7), 6)"""
  862. a = """def foo():
  863. g.throw(Exception(5, 6, 7).with_traceback(6))"""
  864. self.check(b, a)
  865. def test_tb_6(self):
  866. b = """def foo():
  867. a = 5
  868. g.throw(Exception, (5, 6, 7), 6)
  869. b = 6"""
  870. a = """def foo():
  871. a = 5
  872. g.throw(Exception(5, 6, 7).with_traceback(6))
  873. b = 6"""
  874. self.check(b, a)
  875. def test_tb_7(self):
  876. b = """def foo():
  877. a + g.throw(Exception, 5, 6)"""
  878. a = """def foo():
  879. a + g.throw(Exception(5).with_traceback(6))"""
  880. self.check(b, a)
  881. def test_tb_8(self):
  882. b = """def foo():
  883. a = 5
  884. a + g.throw(Exception, 5, 6)
  885. b = 6"""
  886. a = """def foo():
  887. a = 5
  888. a + g.throw(Exception(5).with_traceback(6))
  889. b = 6"""
  890. self.check(b, a)
  891. class Test_long(FixerTestCase):
  892. fixer = "long"
  893. def test_1(self):
  894. b = """x = long(x)"""
  895. a = """x = int(x)"""
  896. self.check(b, a)
  897. def test_2(self):
  898. b = """y = isinstance(x, long)"""
  899. a = """y = isinstance(x, int)"""
  900. self.check(b, a)
  901. def test_3(self):
  902. b = """z = type(x) in (int, long)"""
  903. a = """z = type(x) in (int, int)"""
  904. self.check(b, a)
  905. def test_unchanged(self):
  906. s = """long = True"""
  907. self.unchanged(s)
  908. s = """s.long = True"""
  909. self.unchanged(s)
  910. s = """def long(): pass"""
  911. self.unchanged(s)
  912. s = """class long(): pass"""
  913. self.unchanged(s)
  914. s = """def f(long): pass"""
  915. self.unchanged(s)
  916. s = """def f(g, long): pass"""
  917. self.unchanged(s)
  918. s = """def f(x, long=True): pass"""
  919. self.unchanged(s)
  920. def test_prefix_preservation(self):
  921. b = """x = long( x )"""
  922. a = """x = int( x )"""
  923. self.check(b, a)
  924. class Test_execfile(FixerTestCase):
  925. fixer = "execfile"
  926. def test_conversion(self):
  927. b = """execfile("fn")"""
  928. a = """exec(compile(open("fn").read(), "fn", 'exec'))"""
  929. self.check(b, a)
  930. b = """execfile("fn", glob)"""
  931. a = """exec(compile(open("fn").read(), "fn", 'exec'), glob)"""
  932. self.check(b, a)
  933. b = """execfile("fn", glob, loc)"""
  934. a = """exec(compile(open("fn").read(), "fn", 'exec'), glob, loc)"""
  935. self.check(b, a)
  936. b = """execfile("fn", globals=glob)"""
  937. a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob)"""
  938. self.check(b, a)
  939. b = """execfile("fn", locals=loc)"""
  940. a = """exec(compile(open("fn").read(), "fn", 'exec'), locals=loc)"""
  941. self.check(b, a)
  942. b = """execfile("fn", globals=glob, locals=loc)"""
  943. a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob, locals=loc)"""
  944. self.check(b, a)
  945. def test_spacing(self):
  946. b = """execfile( "fn" )"""
  947. a = """exec(compile(open( "fn" ).read(), "fn", 'exec'))"""
  948. self.check(b, a)
  949. b = """execfile("fn", globals = glob)"""
  950. a = """exec(compile(open("fn").read(), "fn", 'exec'), globals = glob)"""
  951. self.check(b, a)
  952. class Test_isinstance(FixerTestCase):
  953. fixer = "isinstance"
  954. def test_remove_multiple_items(self):
  955. b = """isinstance(x, (int, int, int))"""
  956. a = """isinstance(x, int)"""
  957. self.check(b, a)
  958. b = """isinstance(x, (int, float, int, int, float))"""
  959. a = """isinstance(x, (int, float))"""
  960. self.check(b, a)
  961. b = """isinstance(x, (int, float, int, int, float, str))"""
  962. a = """isinstance(x, (int, float, str))"""
  963. self.check(b, a)
  964. b = """isinstance(foo() + bar(), (x(), y(), x(), int, int))"""
  965. a = """isinstance(foo() + bar(), (x(), y(), x(), int))"""
  966. self.check(b, a)
  967. def test_prefix_preservation(self):
  968. b = """if isinstance( foo(), ( bar, bar, baz )) : pass"""
  969. a = """if isinstance( foo(), ( bar, baz )) : pass"""
  970. self.check(b, a)
  971. def test_unchanged(self):
  972. self.unchanged("isinstance(x, (str, int))")
  973. class Test_dict(FixerTestCase):
  974. fixer = "dict"
  975. def test_prefix_preservation(self):
  976. b = "if d. keys ( ) : pass"
  977. a = "if list(d. keys ( )) : pass"
  978. self.check(b, a)
  979. b = "if d. items ( ) : pass"
  980. a = "if list(d. items ( )) : pass"
  981. self.check(b, a)
  982. b = "if d. iterkeys ( ) : pass"
  983. a = "if iter(d. keys ( )) : pass"
  984. self.check(b, a)
  985. b = "[i for i in d. iterkeys( ) ]"
  986. a = "[i for i in d. keys( ) ]"
  987. self.check(b, a)
  988. b = "if d. viewkeys ( ) : pass"
  989. a = "if d. keys ( ) : pass"
  990. self.check(b, a)
  991. b = "[i for i in d. viewkeys( ) ]"
  992. a = "[i for i in d. keys( ) ]"
  993. self.check(b, a)
  994. def test_trailing_comment(self):
  995. b = "d.keys() # foo"
  996. a = "list(d.keys()) # foo"
  997. self.check(b, a)
  998. b = "d.items() # foo"
  999. a = "list(d.items()) # foo"
  1000. self.check(b, a)
  1001. b = "d.iterkeys() # foo"
  1002. a = "iter(d.keys()) # foo"
  1003. self.check(b, a)
  1004. b = """[i for i in d.iterkeys() # foo
  1005. ]"""
  1006. a = """[i for i in d.keys() # foo
  1007. ]"""
  1008. self.check(b, a)
  1009. b = """[i for i in d.iterkeys() # foo
  1010. ]"""
  1011. a = """[i for i in d.keys() # foo
  1012. ]"""
  1013. self.check(b, a)
  1014. b = "d.viewitems() # foo"
  1015. a = "d.items() # foo"
  1016. self.check(b, a)
  1017. def test_unchanged(self):
  1018. for wrapper in fixer_util.consuming_calls:
  1019. s = "s = %s(d.keys())" % wrapper
  1020. self.unchanged(s)
  1021. s = "s = %s(d.values())" % wrapper
  1022. self.unchanged(s)
  1023. s = "s = %s(d.items())" % wrapper
  1024. self.unchanged(s)
  1025. def test_01(self):
  1026. b = "d.keys()"
  1027. a = "list(d.keys())"
  1028. self.check(b, a)
  1029. b = "a[0].foo().keys()"
  1030. a = "list(a[0].foo().keys())"
  1031. self.check(b, a)
  1032. def test_02(self):
  1033. b = "d.items()"
  1034. a = "list(d.items())"
  1035. self.check(b, a)
  1036. def test_03(self):
  1037. b = "d.values()"
  1038. a = "list(d.values())"
  1039. self.check(b, a)
  1040. def test_04(self):
  1041. b = "d.iterkeys()"
  1042. a = "iter(d.keys())"
  1043. self.check(b, a)
  1044. def test_05(self):
  1045. b = "d.iteritems()"
  1046. a = "iter(d.items())"
  1047. self.check(b, a)
  1048. def test_06(self):
  1049. b = "d.itervalues()"
  1050. a = "iter(d.values())"
  1051. self.check(b, a)
  1052. def test_07(self):
  1053. s = "list(d.keys())"
  1054. self.unchanged(s)
  1055. def test_08(self):
  1056. s = "sorted(d.keys())"
  1057. self.unchanged(s)
  1058. def test_09(self):
  1059. b = "iter(d.keys())"
  1060. a = "iter(list(d.keys()))"
  1061. self.check(b, a)
  1062. def test_10(self):
  1063. b = "foo(d.keys())"
  1064. a = "foo(list(d.keys()))"
  1065. self.check(b, a)
  1066. def test_11(self):
  1067. b = "for i in d.keys(): print i"
  1068. a = "for i in list(d.keys()): print i"
  1069. self.check(b, a)
  1070. def test_12(self):
  1071. b = "for i in d.iterkeys(): print i"
  1072. a = "for i in d.keys(): print i"
  1073. self.check(b, a)
  1074. def test_13(self):
  1075. b = "[i for i in d.keys()]"
  1076. a = "[i for i in list(d.keys())]"
  1077. self.check(b, a)
  1078. def test_14(self):
  1079. b = "[i for i in d.iterkeys()]"
  1080. a = "[i for i in d.keys()]"
  1081. self.check(b, a)
  1082. def test_15(self):
  1083. b = "(i for i in d.keys())"
  1084. a = "(i for i in list(d.keys()))"
  1085. self.check(b, a)
  1086. def test_16(self):
  1087. b = "(i for i in d.iterkeys())"
  1088. a = "(i for i in d.keys())"
  1089. self.check(b, a)
  1090. def test_17(self):
  1091. b = "iter(d.iterkeys())"
  1092. a = "iter(d.keys())"
  1093. self.check(b, a)
  1094. def test_18(self):
  1095. b = "list(d.iterkeys())"
  1096. a = "list(d.keys())"
  1097. self.check(b, a)
  1098. def test_19(self):
  1099. b = "sorted(d.iterkeys())"
  1100. a = "sorted(d.keys())"
  1101. self.check(b, a)
  1102. def test_20(self):
  1103. b = "foo(d.iterkeys())"
  1104. a = "foo(iter(d.keys()))"
  1105. self.check(b, a)
  1106. def test_21(self):
  1107. b = "print h.iterkeys().next()"
  1108. a = "print iter(h.keys()).next()"
  1109. self.check(b, a)
  1110. def test_22(self):
  1111. b = "print h.keys()[0]"
  1112. a = "print list(h.keys())[0]"
  1113. self.check(b, a)
  1114. def test_23(self):
  1115. b = "print list(h.iterkeys().next())"
  1116. a = "print list(iter(h.keys()).next())"
  1117. self.check(b, a)
  1118. def test_24(self):
  1119. b = "for x in h.keys()[0]: print x"
  1120. a = "for x in list(h.keys())[0]: print x"
  1121. self.check(b, a)
  1122. def test_25(self):
  1123. b = "d.viewkeys()"
  1124. a = "d.keys()"
  1125. self.check(b, a)
  1126. def test_26(self):
  1127. b = "d.viewitems()"
  1128. a = "d.items()"
  1129. self.check(b, a)
  1130. def test_27(self):
  1131. b = "d.viewvalues()"
  1132. a = "d.values()"
  1133. self.check(b, a)
  1134. def test_28(self):
  1135. b = "[i for i in d.viewkeys()]"
  1136. a = "[i for i in d.keys()]"
  1137. self.check(b, a)
  1138. def test_29(self):
  1139. b = "(i for i in d.viewkeys())"
  1140. a = "(i for i in d.keys())"
  1141. self.check(b, a)
  1142. def test_30(self):
  1143. b = "iter(d.viewkeys())"
  1144. a = "iter(d.keys())"
  1145. self.check(b, a)
  1146. def test_31(self):
  1147. b = "list(d.viewkeys())"
  1148. a = "list(d.keys())"
  1149. self.check(b, a)
  1150. def test_32(self):
  1151. b = "sorted(d.viewkeys())"
  1152. a = "sorted(d.keys())"
  1153. self.check(b, a)
  1154. class Test_xrange(FixerTestCase):
  1155. fixer = "xrange"
  1156. def test_prefix_preservation(self):
  1157. b = """x = xrange( 10 )"""
  1158. a = """x = range( 10 )"""
  1159. self.check(b, a)
  1160. b = """x = xrange( 1 , 10 )"""
  1161. a = """x = range( 1 , 10 )"""
  1162. self.check(b, a)
  1163. b = """x = xrange( 0 , 10 , 2 )"""
  1164. a = """x = range( 0 , 10 , 2 )"""
  1165. self.check(b, a)
  1166. def test_single_arg(self):
  1167. b = """x = xrange(10)"""
  1168. a = """x = range(10)"""
  1169. self.check(b, a)
  1170. def test_two_args(self):
  1171. b = """x = xrange(1, 10)"""
  1172. a = """x = range(1, 10)"""
  1173. self.check(b, a)
  1174. def test_three_args(self):
  1175. b = """x = xrange(0, 10, 2)"""
  1176. a = """x = range(0, 10, 2)"""
  1177. self.check(b, a)
  1178. def test_wrap_in_list(self):
  1179. b = """x = range(10, 3, 9)"""
  1180. a = """x = list(range(10, 3, 9))"""
  1181. self.check(b, a)
  1182. b = """x = foo(range(10, 3, 9))"""
  1183. a = """x = foo(list(range(10, 3, 9)))"""
  1184. self.check(b, a)
  1185. b = """x = range(10, 3, 9) + [4]"""
  1186. a = """x = list(range(10, 3, 9)) + [4]"""
  1187. self.check(b, a)
  1188. b = """x = range(10)[::-1]"""
  1189. a = """x = list(range(10))[::-1]"""
  1190. self.check(b, a)
  1191. b = """x = range(10) [3]"""
  1192. a = """x = list(range(10)) [3]"""
  1193. self.check(b, a)
  1194. def test_xrange_in_for(self):
  1195. b = """for i in xrange(10):\n j=i"""
  1196. a = """for i in range(10):\n j=i"""
  1197. self.check(b, a)
  1198. b = """[i for i in xrange(10)]"""
  1199. a = """[i for i in range(10)]"""
  1200. self.check(b, a)
  1201. def test_range_in_for(self):
  1202. self.unchanged("for i in range(10): pass")
  1203. self.unchanged("[i for i in range(10)]")
  1204. def test_in_contains_test(self):
  1205. self.unchanged("x in range(10, 3, 9)")
  1206. def test_in_consuming_context(self):
  1207. for call in fixer_util.consuming_calls:
  1208. self.unchanged("a = %s(range(10))" % call)
  1209. class Test_xrange_with_reduce(FixerTestCase):
  1210. def setUp(self):
  1211. super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"])
  1212. def test_double_transform(self):
  1213. b = """reduce(x, xrange(5))"""
  1214. a = """from functools import reduce
  1215. reduce(x, range(5))"""
  1216. self.check(b, a)
  1217. class Test_raw_input(FixerTestCase):
  1218. fixer = "raw_input"
  1219. def test_prefix_preservation(self):
  1220. b = """x = raw_input( )"""
  1221. a = """x = input( )"""
  1222. self.check(b, a)
  1223. b = """x = raw_input( '' )"""
  1224. a = """x = input( '' )"""
  1225. self.check(b, a)
  1226. def test_1(self):
  1227. b = """x = raw_input()"""
  1228. a = """x = input()"""
  1229. self.check(b, a)
  1230. def test_2(self):
  1231. b = """x = raw_input('')"""
  1232. a = """x = input('')"""
  1233. self.check(b, a)
  1234. def test_3(self):
  1235. b = """x = raw_input('prompt')"""
  1236. a = """x = input('prompt')"""
  1237. self.check(b, a)
  1238. def test_4(self):
  1239. b = """x = raw_input(foo(a) + 6)"""
  1240. a = """x = input(foo(a) + 6)"""
  1241. self.check(b, a)
  1242. def test_5(self):
  1243. b = """x = raw_input(invite).split()"""
  1244. a = """x = input(invite).split()"""
  1245. self.check(b, a)
  1246. def test_6(self):
  1247. b = """x = raw_input(invite) . split ()"""
  1248. a = """x = input(invite) . split ()"""
  1249. self.check(b, a)
  1250. def test_8(self):
  1251. b = "x = int(raw_input())"
  1252. a = "x = int(input())"
  1253. self.check(b, a)
  1254. class Test_funcattrs(FixerTestCase):
  1255. fixer = "funcattrs"
  1256. attrs = ["closure", "doc", "name", "defaults", "code", "globals", "dict"]
  1257. def test(self):
  1258. for attr in self.attrs:
  1259. b = "a.func_%s" % attr
  1260. a = "a.__%s__" % attr
  1261. self.check(b, a)
  1262. b = "self.foo.func_%s.foo_bar" % attr
  1263. a = "self.foo.__%s__.foo_bar" % attr
  1264. self.check(b, a)
  1265. def test_unchanged(self):
  1266. for attr in self.attrs:
  1267. s = "foo(func_%s + 5)" % attr
  1268. self.unchanged(s)
  1269. s = "f(foo.__%s__)" % attr
  1270. self.unchanged(s)
  1271. s = "f(foo.__%s__.foo)" % attr
  1272. self.unchanged(s)
  1273. class Test_xreadlines(FixerTestCase):
  1274. fixer = "xreadlines"
  1275. def test_call(self):
  1276. b = "for x in f.xreadlines(): pass"
  1277. a = "for x in f: pass"
  1278. self.check(b, a)
  1279. b = "for x in foo().xreadlines(): pass"
  1280. a = "for x in foo(): pass"
  1281. self.check(b, a)
  1282. b = "for x in (5 + foo()).xreadlines(): pass"
  1283. a = "for x in (5 + foo()): pass"
  1284. self.check(b, a)
  1285. def test_attr_ref(self):
  1286. b = "foo(f.xreadlines + 5)"
  1287. a = "foo(f.__iter__ + 5)"
  1288. self.check(b, a)
  1289. b = "foo(f().xreadlines + 5)"
  1290. a = "foo(f().__iter__ + 5)"
  1291. self.check(b, a)
  1292. b = "foo((5 + f()).xreadlines + 5)"
  1293. a = "foo((5 + f()).__iter__ + 5)"
  1294. self.check(b, a)
  1295. def test_unchanged(self):
  1296. s = "for x in f.xreadlines(5): pass"
  1297. self.unchanged(s)
  1298. s = "for x in f.xreadlines(k=5): pass"
  1299. self.unchanged(s)
  1300. s = "for x in f.xreadlines(*k, **v): pass"
  1301. self.unchanged(s)
  1302. s = "foo(xreadlines)"
  1303. self.unchanged(s)
  1304. class ImportsFixerTests:
  1305. def test_import_module(self):
  1306. for old, new in self.modules.items():
  1307. b = "import %s" % old
  1308. a = "import %s" % new
  1309. self.check(b, a)
  1310. b = "import foo, %s, bar" % old
  1311. a = "import foo, %s, bar" % new
  1312. self.check(b, a)
  1313. def test_import_from(self):
  1314. for old, new in self.modules.items():
  1315. b = "from %s import foo" % old
  1316. a = "from %s import foo" % new
  1317. self.check(b, a)
  1318. b = "from %s import foo, bar" % old
  1319. a = "from %s import foo, bar" % new
  1320. self.check(b, a)
  1321. b = "from %s import (yes, no)" % old
  1322. a = "from %s import (yes, no)" % new
  1323. self.check(b, a)
  1324. def test_import_module_as(self):
  1325. for old, new in self.modules.items():
  1326. b = "import %s as foo_bar" % old
  1327. a = "import %s as foo_bar" % new
  1328. self.check(b, a)
  1329. b = "import %s as foo_bar" % old
  1330. a = "import %s as foo_bar" % new
  1331. self.check(b, a)
  1332. def test_import_from_as(self):
  1333. for old, new in self.modules.items():
  1334. b = "from %s import foo as bar" % old
  1335. a = "from %s import foo as bar" % new
  1336. self.check(b, a)
  1337. def test_star(self):
  1338. for old, new in self.modules.items():
  1339. b = "from %s import *" % old
  1340. a = "from %s import *" % new
  1341. self.check(b, a)
  1342. def test_import_module_usage(self):
  1343. for old, new in self.modules.items():
  1344. b = """
  1345. import %s
  1346. foo(%s.bar)
  1347. """ % (old, old)
  1348. a = """
  1349. import %s
  1350. foo(%s.bar)
  1351. """ % (new, new)
  1352. self.check(b, a)
  1353. b = """
  1354. from %s import x
  1355. %s = 23
  1356. """ % (old, old)
  1357. a = """
  1358. from %s import x
  1359. %s = 23
  1360. """ % (new, old)
  1361. self.check(b, a)
  1362. s = """
  1363. def f():
  1364. %s.method()
  1365. """ % (old,)
  1366. self.unchanged(s)
  1367. # test nested usage
  1368. b = """
  1369. import %s
  1370. %s.bar(%s.foo)
  1371. """ % (old, old, old)
  1372. a = """
  1373. import %s
  1374. %s.bar(%s.foo)
  1375. """ % (new, new, new)
  1376. self.check(b, a)
  1377. b = """
  1378. import %s
  1379. x.%s
  1380. """ % (old, old)
  1381. a = """
  1382. import %s
  1383. x.%s
  1384. """ % (new, old)
  1385. self.check(b, a)
  1386. class Test_imports(FixerTestCase, ImportsFixerTests):
  1387. fixer = "imports"
  1388. from ..fixes.fix_imports import MAPPING as modules
  1389. def test_multiple_imports(self):
  1390. b = """import urlparse, cStringIO"""
  1391. a = """import urllib.parse, io"""
  1392. self.check(b, a)
  1393. def test_multiple_imports_as(self):
  1394. b = """
  1395. import copy_reg as bar, HTMLParser as foo, urlparse
  1396. s = urlparse.spam(bar.foo())
  1397. """
  1398. a = """
  1399. import copyreg as bar, html.parser as foo, urllib.parse
  1400. s = urllib.parse.spam(bar.foo())
  1401. """
  1402. self.check(b, a)
  1403. class Test_imports2(FixerTestCase, ImportsFixerTests):
  1404. fixer = "imports2"
  1405. from ..fixes.fix_imports2 import MAPPING as modules
  1406. class Test_imports_fixer_order(FixerTestCase, ImportsFixerTests):
  1407. def setUp(self):
  1408. super(Test_imports_fixer_order, self).setUp(['imports', 'imports2'])
  1409. from ..fixes.fix_imports2 import MAPPING as mapping2
  1410. self.modules = mapping2.copy()
  1411. from ..fixes.fix_imports import MAPPING as mapping1
  1412. for key in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'):
  1413. self.modules[key] = mapping1[key]
  1414. def test_after_local_imports_refactoring(self):
  1415. for fix in ("imports", "imports2"):
  1416. self.fixer = fix
  1417. self.assert_runs_after("import")
  1418. class Test_urllib(FixerTestCase):
  1419. fixer = "urllib"
  1420. from ..fixes.fix_urllib import MAPPING as modules
  1421. def test_import_module(self):
  1422. for old, changes in self.modules.items():
  1423. b = "import %s" % old
  1424. a = "import %s" % ", ".join(map(itemgetter(0), changes))
  1425. self.check(b, a)
  1426. def test_import_from(self):
  1427. for old, changes in self.modules.items():
  1428. all_members = []
  1429. for new, members in changes:
  1430. for member in members:
  1431. all_members.append(member)
  1432. b = "from %s import %s" % (old, member)
  1433. a = "from %s import %s" % (new, member)
  1434. self.check(b, a)
  1435. s = "from foo import %s" % member
  1436. self.unchanged(s)
  1437. b = "from %s import %s" % (old, ", ".join(members))
  1438. a = "from %s import %s" % (new, ", ".join(members))
  1439. self.check(b, a)
  1440. s = "from foo import %s" % ", ".join(members)
  1441. self.unchanged(s)
  1442. # test the breaking of a module into multiple replacements
  1443. b = "from %s import %s" % (old, ", ".join(all_members))
  1444. a = "\n".join(["from %s import %s" % (new, ", ".join(members))
  1445. for (new, members) in changes])
  1446. self.check(b, a)
  1447. def test_import_module_as(self):
  1448. for old in self.modules:
  1449. s = "import %s as foo" % old
  1450. self.warns_unchanged(s, "This module is now multiple modules")
  1451. def test_import_from_as(self):
  1452. for old, changes in self.modules.items():
  1453. for new, members in changes:
  1454. for member in members:
  1455. b = "from %s import %s as foo_bar" % (old, member)
  1456. a = "from %s import %s as foo_bar" % (new, member)
  1457. self.check(b, a)
  1458. b = "from %s import %s as blah, %s" % (old, member, member)
  1459. a = "from %s import %s as blah, %s" % (new, member, member)
  1460. self.check(b, a)
  1461. def test_star(self):
  1462. for old in self.modules:
  1463. s = "from %s import *" % old
  1464. self.warns_unchanged(s, "Cannot handle star imports")
  1465. def test_indented(self):
  1466. b = """
  1467. def foo():
  1468. from urllib import urlencode, urlopen
  1469. """
  1470. a = """
  1471. def foo():
  1472. from urllib.parse import urlencode
  1473. from urllib.request import urlopen
  1474. """
  1475. self.check(b, a)
  1476. b = """
  1477. def foo():
  1478. other()
  1479. from urllib import urlencode, urlopen
  1480. """
  1481. a = """
  1482. def foo():
  1483. other()
  1484. from urllib.parse import urlencode
  1485. from urllib.request import urlopen
  1486. """
  1487. self.check(b, a)
  1488. def test_import_module_usage(self):
  1489. for old, changes in self.modules.items():
  1490. for new, members in changes:
  1491. for member in members:
  1492. new_import = ", ".join([n for (n, mems)
  1493. in self.modules[old]])
  1494. b = """
  1495. import %s
  1496. foo(%s.%s)
  1497. """ % (old, old, member)
  1498. a = """

Large files files are truncated, but you can click here to view the full file