~ubuntu-branches/ubuntu/lucid/python2.6/lucid

« back to all changes in this revision

Viewing changes to Lib/lib2to3/tests/test_fixers.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2010-03-11 13:30:19 UTC
  • mto: (10.1.13 sid)
  • mto: This revision was merged to the branch mainline in revision 44.
  • Revision ID: james.westby@ubuntu.com-20100311133019-sblbooa3uqrkoe70
Tags: upstream-2.6.5~rc2
ImportĀ upstreamĀ versionĀ 2.6.5~rc2

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python2.5
2
1
""" Test suite for the fixer modules """
3
 
# Author: Collin Winter
4
 
 
5
 
# Testing imports
6
 
try:
7
 
    from tests import support
8
 
except ImportError:
9
 
    import support
10
2
 
11
3
# Python imports
12
4
import os
16
8
 
17
9
# Local imports
18
10
from lib2to3 import pygram, pytree, refactor, fixer_util
 
11
from lib2to3.tests import support
19
12
 
20
13
 
21
14
class FixerTestCase(support.TestCase):
22
 
    def setUp(self, fix_list=None):
 
15
 
 
16
    # Other test cases can subclass this class and replace "fixer_pkg" with
 
17
    # their own.
 
18
    def setUp(self, fix_list=None, fixer_pkg="lib2to3", options=None):
23
19
        if fix_list is None:
24
20
            fix_list = [self.fixer]
25
 
        options = {"print_function" : False}
26
 
        self.refactor = support.get_refactorer(fix_list, options)
 
21
        self.refactor = support.get_refactorer(fixer_pkg, fix_list, options)
27
22
        self.fixer_log = []
28
 
        self.filename = "<string>"
 
23
        self.filename = u"<string>"
29
24
 
30
25
        for fixer in chain(self.refactor.pre_order,
31
26
                           self.refactor.post_order):
35
30
        before = support.reformat(before)
36
31
        after = support.reformat(after)
37
32
        tree = self.refactor.refactor_string(before, self.filename)
38
 
        self.failUnlessEqual(after, str(tree))
 
33
        self.assertEqual(after, unicode(tree))
39
34
        return tree
40
35
 
41
36
    def check(self, before, after, ignore_warnings=False):
42
37
        tree = self._check(before, after)
43
 
        self.failUnless(tree.was_changed)
 
38
        self.assertTrue(tree.was_changed)
44
39
        if not ignore_warnings:
45
 
            self.failUnlessEqual(self.fixer_log, [])
 
40
            self.assertEqual(self.fixer_log, [])
46
41
 
47
42
    def warns(self, before, after, message, unchanged=False):
48
43
        tree = self._check(before, after)
49
 
        self.failUnless(message in "".join(self.fixer_log))
 
44
        self.assertTrue(message in "".join(self.fixer_log))
50
45
        if not unchanged:
51
 
            self.failUnless(tree.was_changed)
 
46
            self.assertTrue(tree.was_changed)
52
47
 
53
48
    def warns_unchanged(self, before, message):
54
49
        self.warns(before, before, message, unchanged=True)
56
51
    def unchanged(self, before, ignore_warnings=False):
57
52
        self._check(before, before)
58
53
        if not ignore_warnings:
59
 
            self.failUnlessEqual(self.fixer_log, [])
 
54
            self.assertEqual(self.fixer_log, [])
60
55
 
61
56
    def assert_runs_after(self, *names):
62
57
        fixes = [self.fixer]
63
58
        fixes.extend(names)
64
 
        options = {"print_function" : False}
65
 
        r = support.get_refactorer(fixes, options)
 
59
        r = support.get_refactorer("lib2to3", fixes)
66
60
        (pre, post) = r.get_fixers()
67
61
        n = "fix_" + self.fixer
68
62
        if post and post[-1].__class__.__module__.endswith(n):
345
339
        a = "from functools import reduce\nreduce(a, b, c)"
346
340
        self.check(b, a)
347
341
 
 
342
    def test_bug_7253(self):
 
343
        # fix_tuple_params was being bad and orphaning nodes in the tree.
 
344
        b = "def x(arg): reduce(sum, [])"
 
345
        a = "from functools import reduce\ndef x(arg): reduce(sum, [])"
 
346
        self.check(b, a)
 
347
 
348
348
    def test_call_with_lambda(self):
349
349
        b = "reduce(lambda x, y: x + y, seq)"
350
350
        a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)"
382
382
        self.unchanged(s)
383
383
 
384
384
    def test_idempotency_print_as_function(self):
385
 
        print_stmt = pygram.python_grammar.keywords.pop("print")
386
 
        try:
387
 
            s = """print(1, 1+1, 1+1+1)"""
388
 
            self.unchanged(s)
389
 
 
390
 
            s = """print()"""
391
 
            self.unchanged(s)
392
 
 
393
 
            s = """print('')"""
394
 
            self.unchanged(s)
395
 
        finally:
396
 
            pygram.python_grammar.keywords["print"] = print_stmt
 
385
        self.refactor.driver.grammar = pygram.python_grammar_no_print_statement
 
386
        s = """print(1, 1+1, 1+1+1)"""
 
387
        self.unchanged(s)
 
388
 
 
389
        s = """print()"""
 
390
        self.unchanged(s)
 
391
 
 
392
        s = """print('')"""
 
393
        self.unchanged(s)
397
394
 
398
395
    def test_1(self):
399
396
        b = """print 1, 1+1, 1+1+1"""
419
416
    def test_5(self):
420
417
        b = """print; print whatever;"""
421
418
        a = """print(); print(whatever);"""
 
419
        self.check(b, a)
422
420
 
423
421
    def test_tuple(self):
424
422
        b = """print (a, b, c)"""
464
462
        a = """print(file=sys.stderr)"""
465
463
        self.check(b, a)
466
464
 
467
 
    # With from __future__ import print_function
468
465
    def test_with_future_print_function(self):
469
 
        # XXX: These tests won't actually do anything until the parser
470
 
        #      is fixed so it won't crash when it sees print(x=y).
471
 
        #      When #2412 is fixed, the try/except block can be taken
472
 
        #      out and the tests can be run like normal.
473
 
        # MvL: disable entirely for now, so that it doesn't print to stdout
474
 
        return
475
 
        try:
476
 
            s = "from __future__ import print_function\n"\
477
 
                "print('Hai!', end=' ')"
478
 
            self.unchanged(s)
479
 
 
480
 
            b = "print 'Hello, world!'"
481
 
            a = "print('Hello, world!')"
482
 
            self.check(b, a)
483
 
 
484
 
            s = "from __future__ import *\n"\
485
 
                "print('Hai!', end=' ')"
486
 
            self.unchanged(s)
487
 
        except:
488
 
            return
489
 
        else:
490
 
            self.assertFalse(True, "#2421 has been fixed -- printing tests "\
491
 
                                   "need to be updated!")
 
466
        s = "from __future__ import print_function\n" \
 
467
            "print('Hai!', end=' ')"
 
468
        self.unchanged(s)
 
469
 
 
470
        b = "print 'Hello, world!'"
 
471
        a = "print('Hello, world!')"
 
472
        self.check(b, a)
 
473
 
492
474
 
493
475
class Test_exec(FixerTestCase):
494
476
    fixer = "exec"
782
764
                pass"""
783
765
        self.check(b, a)
784
766
 
 
767
    def test_one_line_suites(self):
 
768
        b = """
 
769
            try: raise TypeError
 
770
            except TypeError, e:
 
771
                pass
 
772
            """
 
773
        a = """
 
774
            try: raise TypeError
 
775
            except TypeError as e:
 
776
                pass
 
777
            """
 
778
        self.check(b, a)
 
779
        b = """
 
780
            try:
 
781
                raise TypeError
 
782
            except TypeError, e: pass
 
783
            """
 
784
        a = """
 
785
            try:
 
786
                raise TypeError
 
787
            except TypeError as e: pass
 
788
            """
 
789
        self.check(b, a)
 
790
        b = """
 
791
            try: raise TypeError
 
792
            except TypeError, e: pass
 
793
            """
 
794
        a = """
 
795
            try: raise TypeError
 
796
            except TypeError as e: pass
 
797
            """
 
798
        self.check(b, a)
 
799
        b = """
 
800
            try: raise TypeError
 
801
            except TypeError, e: pass
 
802
            else: function()
 
803
            finally: done()
 
804
            """
 
805
        a = """
 
806
            try: raise TypeError
 
807
            except TypeError as e: pass
 
808
            else: function()
 
809
            finally: done()
 
810
            """
 
811
        self.check(b, a)
 
812
 
785
813
    # These should not be touched:
786
814
 
787
815
    def test_unchanged_1(self):
1187
1215
        a = "[i for i in    d.  keys(  )  ]"
1188
1216
        self.check(b, a)
1189
1217
 
 
1218
        b = "if   d. viewkeys  ( )  : pass"
 
1219
        a = "if   d. keys  ( )  : pass"
 
1220
        self.check(b, a)
 
1221
 
 
1222
        b = "[i for i in    d.  viewkeys(  )  ]"
 
1223
        a = "[i for i in    d.  keys(  )  ]"
 
1224
        self.check(b, a)
 
1225
 
1190
1226
    def test_trailing_comment(self):
1191
1227
        b = "d.keys() # foo"
1192
1228
        a = "list(d.keys()) # foo"
1206
1242
               ]"""
1207
1243
        self.check(b, a)
1208
1244
 
 
1245
        b = """[i for i in d.iterkeys() # foo
 
1246
               ]"""
 
1247
        a = """[i for i in d.keys() # foo
 
1248
               ]"""
 
1249
        self.check(b, a)
 
1250
 
 
1251
        b = "d.viewitems()  # foo"
 
1252
        a = "d.items()  # foo"
 
1253
        self.check(b, a)
 
1254
 
1209
1255
    def test_unchanged(self):
1210
1256
        for wrapper in fixer_util.consuming_calls:
1211
1257
            s = "s = %s(d.keys())" % wrapper
1339
1385
        a = "for x in list(h.keys())[0]: print x"
1340
1386
        self.check(b, a)
1341
1387
 
 
1388
    def test_25(self):
 
1389
        b = "d.viewkeys()"
 
1390
        a = "d.keys()"
 
1391
        self.check(b, a)
 
1392
 
 
1393
    def test_26(self):
 
1394
        b = "d.viewitems()"
 
1395
        a = "d.items()"
 
1396
        self.check(b, a)
 
1397
 
 
1398
    def test_27(self):
 
1399
        b = "d.viewvalues()"
 
1400
        a = "d.values()"
 
1401
        self.check(b, a)
 
1402
 
 
1403
    def test_14(self):
 
1404
        b = "[i for i in d.viewkeys()]"
 
1405
        a = "[i for i in d.keys()]"
 
1406
        self.check(b, a)
 
1407
 
 
1408
    def test_15(self):
 
1409
        b = "(i for i in d.viewkeys())"
 
1410
        a = "(i for i in d.keys())"
 
1411
        self.check(b, a)
 
1412
 
 
1413
    def test_17(self):
 
1414
        b = "iter(d.viewkeys())"
 
1415
        a = "iter(d.keys())"
 
1416
        self.check(b, a)
 
1417
 
 
1418
    def test_18(self):
 
1419
        b = "list(d.viewkeys())"
 
1420
        a = "list(d.keys())"
 
1421
        self.check(b, a)
 
1422
 
 
1423
    def test_19(self):
 
1424
        b = "sorted(d.viewkeys())"
 
1425
        a = "sorted(d.keys())"
 
1426
        self.check(b, a)
 
1427
 
1342
1428
class Test_xrange(FixerTestCase):
1343
1429
    fixer = "xrange"
1344
1430
 
1661
1747
        for key in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'):
1662
1748
            self.modules[key] = mapping1[key]
1663
1749
 
 
1750
    def test_after_local_imports_refactoring(self):
 
1751
        for fix in ("imports", "imports2"):
 
1752
            self.fixer = fix
 
1753
            self.assert_runs_after("import")
 
1754
 
1664
1755
 
1665
1756
class Test_urllib(FixerTestCase):
1666
1757
    fixer = "urllib"
1720
1811
        for old, changes in self.modules.items():
1721
1812
            for new, members in changes:
1722
1813
                for member in members:
 
1814
                    new_import = ", ".join([n for (n, mems)
 
1815
                                            in self.modules[old]])
1723
1816
                    b = """
1724
1817
                        import %s
1725
1818
                        foo(%s.%s)
1727
1820
                    a = """
1728
1821
                        import %s
1729
1822
                        foo(%s.%s)
1730
 
                        """ % (", ".join([n for (n, mems)
1731
 
                                           in self.modules[old]]),
1732
 
                                         new, member)
 
1823
                        """ % (new_import, new, member)
 
1824
                    self.check(b, a)
 
1825
                    b = """
 
1826
                        import %s
 
1827
                        %s.%s(%s.%s)
 
1828
                        """ % (old, old, member, old, member)
 
1829
                    a = """
 
1830
                        import %s
 
1831
                        %s.%s(%s.%s)
 
1832
                        """ % (new_import, new, member, new, member)
1733
1833
                    self.check(b, a)
1734
1834
 
1735
1835
 
2640
2740
class Test_unicode(FixerTestCase):
2641
2741
    fixer = "unicode"
2642
2742
 
 
2743
    def test_whitespace(self):
 
2744
        b = """unicode( x)"""
 
2745
        a = """str( x)"""
 
2746
        self.check(b, a)
 
2747
 
 
2748
        b = """ unicode(x )"""
 
2749
        a = """ str(x )"""
 
2750
        self.check(b, a)
 
2751
 
 
2752
        b = """ u'h'"""
 
2753
        a = """ 'h'"""
 
2754
        self.check(b, a)
 
2755
 
2643
2756
    def test_unicode_call(self):
2644
2757
        b = """unicode(x, y, z)"""
2645
2758
        a = """str(x, y, z)"""
2646
2759
        self.check(b, a)
2647
2760
 
 
2761
    def test_unichr(self):
 
2762
        b = """unichr(u'h')"""
 
2763
        a = """chr('h')"""
 
2764
        self.check(b, a)
 
2765
 
2648
2766
    def test_unicode_literal_1(self):
2649
2767
        b = '''u"x"'''
2650
2768
        a = '''"x"'''
2656
2774
        self.check(b, a)
2657
2775
 
2658
2776
    def test_unicode_literal_3(self):
2659
 
        b = """UR'''x'''"""
2660
 
        a = """R'''x'''"""
 
2777
        b = """UR'''x''' """
 
2778
        a = """R'''x''' """
2661
2779
        self.check(b, a)
2662
2780
 
2663
2781
class Test_callable(FixerTestCase):
2665
2783
 
2666
2784
    def test_prefix_preservation(self):
2667
2785
        b = """callable(    x)"""
2668
 
        a = """hasattr(    x, '__call__')"""
 
2786
        a = """import collections\nisinstance(    x, collections.Callable)"""
2669
2787
        self.check(b, a)
2670
2788
 
2671
2789
        b = """if     callable(x): pass"""
2672
 
        a = """if     hasattr(x, '__call__'): pass"""
 
2790
        a = """import collections
 
2791
if     isinstance(x, collections.Callable): pass"""
2673
2792
        self.check(b, a)
2674
2793
 
2675
2794
    def test_callable_call(self):
2676
2795
        b = """callable(x)"""
2677
 
        a = """hasattr(x, '__call__')"""
 
2796
        a = """import collections\nisinstance(x, collections.Callable)"""
 
2797
        self.check(b, a)
 
2798
 
 
2799
    def test_global_import(self):
 
2800
        b = """
 
2801
def spam(foo):
 
2802
    callable(foo)"""[1:]
 
2803
        a = """
 
2804
import collections
 
2805
def spam(foo):
 
2806
    isinstance(foo, collections.Callable)"""[1:]
 
2807
        self.check(b, a)
 
2808
 
 
2809
        b = """
 
2810
import collections
 
2811
def spam(foo):
 
2812
    callable(foo)"""[1:]
 
2813
        # same output if it was already imported
 
2814
        self.check(b, a)
 
2815
 
 
2816
        b = """
 
2817
from collections import *
 
2818
def spam(foo):
 
2819
    callable(foo)"""[1:]
 
2820
        a = """
 
2821
from collections import *
 
2822
import collections
 
2823
def spam(foo):
 
2824
    isinstance(foo, collections.Callable)"""[1:]
 
2825
        self.check(b, a)
 
2826
 
 
2827
        b = """
 
2828
do_stuff()
 
2829
do_some_other_stuff()
 
2830
assert callable(do_stuff)"""[1:]
 
2831
        a = """
 
2832
import collections
 
2833
do_stuff()
 
2834
do_some_other_stuff()
 
2835
assert isinstance(do_stuff, collections.Callable)"""[1:]
 
2836
        self.check(b, a)
 
2837
 
 
2838
        b = """
 
2839
if isinstance(do_stuff, Callable):
 
2840
    assert callable(do_stuff)
 
2841
    do_stuff(do_stuff)
 
2842
    if not callable(do_stuff):
 
2843
        exit(1)
 
2844
    else:
 
2845
        assert callable(do_stuff)
 
2846
else:
 
2847
    assert not callable(do_stuff)"""[1:]
 
2848
        a = """
 
2849
import collections
 
2850
if isinstance(do_stuff, Callable):
 
2851
    assert isinstance(do_stuff, collections.Callable)
 
2852
    do_stuff(do_stuff)
 
2853
    if not isinstance(do_stuff, collections.Callable):
 
2854
        exit(1)
 
2855
    else:
 
2856
        assert isinstance(do_stuff, collections.Callable)
 
2857
else:
 
2858
    assert not isinstance(do_stuff, collections.Callable)"""[1:]
2678
2859
        self.check(b, a)
2679
2860
 
2680
2861
    def test_callable_should_not_change(self):
2789
2970
        a = """x = list(map(f, 'abc'))   #   foo"""
2790
2971
        self.check(b, a)
2791
2972
 
 
2973
    def test_None_with_multiple_arguments(self):
 
2974
        s = """x = map(None, a, b, c)"""
 
2975
        self.warns_unchanged(s, "cannot convert map(None, ...) with "
 
2976
                             "multiple arguments")
 
2977
 
2792
2978
    def test_map_basic(self):
2793
2979
        b = """x = map(f, 'abc')"""
2794
2980
        a = """x = list(map(f, 'abc'))"""
2802
2988
        a = """x = list('abc')"""
2803
2989
        self.check(b, a)
2804
2990
 
2805
 
        b = """x = map(None, 'abc', 'def')"""
2806
 
        a = """x = list(map(None, 'abc', 'def'))"""
2807
 
        self.check(b, a)
2808
 
 
2809
2991
        b = """x = map(lambda x: x+1, range(4))"""
2810
2992
        a = """x = [x+1 for x in range(4)]"""
2811
2993
        self.check(b, a)
3193
3375
            """
3194
3376
        self.check(b, a)
3195
3377
 
 
3378
        b = r"""
 
3379
            try:
 
3380
                m = list(s)
 
3381
                m.sort()
 
3382
            except: pass
 
3383
            """
 
3384
 
 
3385
        a = r"""
 
3386
            try:
 
3387
                m = sorted(s)
 
3388
            except: pass
 
3389
            """
 
3390
        self.check(b, a)
 
3391
 
 
3392
        b = r"""
 
3393
            try:
 
3394
                m = list(s)
 
3395
                # foo
 
3396
                m.sort()
 
3397
            except: pass
 
3398
            """
 
3399
 
 
3400
        a = r"""
 
3401
            try:
 
3402
                m = sorted(s)
 
3403
                # foo
 
3404
            except: pass
 
3405
            """
 
3406
        self.check(b, a)
 
3407
 
 
3408
        b = r"""
 
3409
            m = list(s)
 
3410
            # more comments
 
3411
            m.sort()"""
 
3412
 
 
3413
        a = r"""
 
3414
            m = sorted(s)
 
3415
            # more comments"""
 
3416
        self.check(b, a)
 
3417
 
3196
3418
    def test_sort_simple_expr(self):
3197
3419
        b = """
3198
3420
            v = t
3306
3528
        a = """x = memoryview(y)"""
3307
3529
        self.check(b, a)
3308
3530
 
 
3531
    def test_slicing(self):
 
3532
        b = """buffer(y)[4:5]"""
 
3533
        a = """memoryview(y)[4:5]"""
 
3534
        self.check(b, a)
 
3535
 
3309
3536
class Test_future(FixerTestCase):
3310
3537
    fixer = "future"
3311
3538
 
3404
3631
        a = "from itertools import bar as bang"
3405
3632
        self.check(b, a)
3406
3633
 
 
3634
        b = "from itertools import izip as _zip, imap, bar"
 
3635
        a = "from itertools import bar"
 
3636
        self.check(b, a)
 
3637
 
 
3638
        b = "from itertools import imap as _map"
 
3639
        a = ""
 
3640
        self.check(b, a)
 
3641
 
 
3642
        b = "from itertools import imap as _map, izip as _zip"
 
3643
        a = ""
 
3644
        self.check(b, a)
 
3645
 
3407
3646
        s = "from itertools import bar as bang"
3408
3647
        self.unchanged(s)
3409
3648
 
3425
3664
        s = "from itertools import foo"
3426
3665
        self.unchanged(s)
3427
3666
 
 
3667
 
3428
3668
class Test_import(FixerTestCase):
3429
3669
    fixer = "import"
3430
3670
 
3459
3699
 
3460
3700
        self.always_exists = False
3461
3701
        self.present_files = set(['__init__.py'])
3462
 
        expected_extensions = ('.py', os.path.pathsep, '.pyc', '.so',
3463
 
                               '.sl', '.pyd')
 
3702
        expected_extensions = ('.py', os.path.sep, '.pyc', '.so', '.sl', '.pyd')
3464
3703
        names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))
3465
3704
 
3466
3705
        for name in names_to_test:
3490
3729
        self.present_files = set(["__init__.py", "bar.py"])
3491
3730
        self.check(b, a)
3492
3731
 
 
3732
    def test_import_from_package(self):
 
3733
        b = "import bar"
 
3734
        a = "from . import bar"
 
3735
        self.always_exists = False
 
3736
        self.present_files = set(["__init__.py", "bar" + os.path.sep])
 
3737
        self.check(b, a)
 
3738
 
3493
3739
    def test_comments_and_indent(self):
3494
3740
        b = "import bar # Foo"
3495
3741
        a = "from . import bar # Foo"
4018
4264
        self.check(b, a)
4019
4265
 
4020
4266
 
4021
 
if __name__ == "__main__":
4022
 
    import __main__
4023
 
    support.run_all_tests(__main__)
 
4267
class Test_operator(FixerTestCase):
 
4268
 
 
4269
    fixer = "operator"
 
4270
 
 
4271
    def test_operator_isCallable(self):
 
4272
        b = "operator.isCallable(x)"
 
4273
        a = "hasattr(x, '__call__')"
 
4274
        self.check(b, a)
 
4275
 
 
4276
    def test_operator_sequenceIncludes(self):
 
4277
        b = "operator.sequenceIncludes(x, y)"
 
4278
        a = "operator.contains(x, y)"
 
4279
        self.check(b, a)
 
4280
 
 
4281
    def test_bare_isCallable(self):
 
4282
        s = "isCallable(x)"
 
4283
        self.warns_unchanged(s, "You should use hasattr(x, '__call__') here.")
 
4284
 
 
4285
    def test_bare_sequenceIncludes(self):
 
4286
        s = "sequenceIncludes(x, y)"
 
4287
        self.warns_unchanged(s, "You should use operator.contains here.")