/Lib/lib2to3/tests/test_fixers.py

http://unladen-swallow.googlecode.com/ · Python · 4023 lines · 3232 code · 731 blank · 60 comment · 60 complexity · 8a68ab4c442c928a298d8ab47967b6e0 MD5 · raw file

Large files are truncated click here to view the full file

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