Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
10 edited
1 copied

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/lib2to3/tests/data/bom.py

    r2 r391  
    11# coding: utf-8
    22print "BOM BOOM!"
    3 
  • python/trunk/Lib/lib2to3/tests/data/py2_test_grammar.py

    r2 r391  
    317317        x = 1; pass; del x
    318318        def foo():
    319             # verify statments that end with semi-colons
     319            # verify statements that end with semi-colons
    320320            x = 1; pass; del x;
    321321        foo()
  • python/trunk/Lib/lib2to3/tests/data/py3_test_grammar.py

    r2 r391  
    357357        x = 1; pass; del x
    358358        def foo():
    359             # verify statments that end with semi-colons
     359            # verify statements that end with semi-colons
    360360            x = 1; pass; del x;
    361361        foo()
  • python/trunk/Lib/lib2to3/tests/test_fixers.py

    r2 r391  
    869869        self.check(b, a)
    870870
     871    def test_None_value(self):
     872        b = """raise Exception(5), None, tb"""
     873        a = """raise Exception(5).with_traceback(tb)"""
     874        self.check(b, a)
     875
    871876    def test_tuple_value(self):
    872877        b = """raise Exception, (5, 6, 7)"""
     
    14011406        self.check(b, a)
    14021407
    1403     def test_14(self):
     1408    def test_28(self):
    14041409        b = "[i for i in d.viewkeys()]"
    14051410        a = "[i for i in d.keys()]"
    14061411        self.check(b, a)
    14071412
    1408     def test_15(self):
     1413    def test_29(self):
    14091414        b = "(i for i in d.viewkeys())"
    14101415        a = "(i for i in d.keys())"
    14111416        self.check(b, a)
    14121417
    1413     def test_17(self):
     1418    def test_30(self):
    14141419        b = "iter(d.viewkeys())"
    14151420        a = "iter(d.keys())"
    14161421        self.check(b, a)
    14171422
    1418     def test_18(self):
     1423    def test_31(self):
    14191424        b = "list(d.viewkeys())"
    14201425        a = "list(d.keys())"
    14211426        self.check(b, a)
    14221427
    1423     def test_19(self):
     1428    def test_32(self):
    14241429        b = "sorted(d.viewkeys())"
    14251430        a = "sorted(d.keys())"
     
    14971502        for call in fixer_util.consuming_calls:
    14981503            self.unchanged("a = %s(range(10))" % call)
     1504
     1505class Test_xrange_with_reduce(FixerTestCase):
     1506
     1507    def setUp(self):
     1508        super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"])
     1509
     1510    def test_double_transform(self):
     1511        b = """reduce(x, xrange(5))"""
     1512        a = """from functools import reduce
     1513reduce(x, range(5))"""
     1514        self.check(b, a)
    14991515
    15001516class Test_raw_input(FixerTestCase):
     
    18021818                    a = "from %s import %s as foo_bar" % (new, member)
    18031819                    self.check(b, a)
     1820                    b = "from %s import %s as blah, %s" % (old, member, member)
     1821                    a = "from %s import %s as blah, %s" % (new, member, member)
     1822                    self.check(b, a)
    18041823
    18051824    def test_star(self):
     
    18071826            s = "from %s import *" % old
    18081827            self.warns_unchanged(s, "Cannot handle star imports")
     1828
     1829    def test_indented(self):
     1830        b = """
     1831def foo():
     1832    from urllib import urlencode, urlopen
     1833"""
     1834        a = """
     1835def foo():
     1836    from urllib.parse import urlencode
     1837    from urllib.request import urlopen
     1838"""
     1839        self.check(b, a)
     1840
     1841        b = """
     1842def foo():
     1843    other()
     1844    from urllib import urlencode, urlopen
     1845"""
     1846        a = """
     1847def foo():
     1848    other()
     1849    from urllib.parse import urlencode
     1850    from urllib.request import urlopen
     1851"""
     1852        self.check(b, a)
     1853
     1854
    18091855
    18101856    def test_import_module_usage(self):
     
    27792825        self.check(b, a)
    27802826
     2827    def test_native_literal_escape_u(self):
     2828        b = """'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2829        a = """'\\\\\\\\u20ac\\\\U0001d121\\\\u20ac'"""
     2830        self.check(b, a)
     2831
     2832        b = """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2833        a = """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2834        self.check(b, a)
     2835
     2836    def test_bytes_literal_escape_u(self):
     2837        b = """b'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2838        a = """b'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2839        self.check(b, a)
     2840
     2841        b = """br'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2842        a = """br'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2843        self.check(b, a)
     2844
     2845    def test_unicode_literal_escape_u(self):
     2846        b = """u'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2847        a = """'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2848        self.check(b, a)
     2849
     2850        b = """ur'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2851        a = """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2852        self.check(b, a)
     2853
     2854    def test_native_unicode_literal_escape_u(self):
     2855        f = 'from __future__ import unicode_literals\n'
     2856        b = f + """'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2857        a = f + """'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2858        self.check(b, a)
     2859
     2860        b = f + """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2861        a = f + """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
     2862        self.check(b, a)
     2863
    27812864class Test_callable(FixerTestCase):
    27822865    fixer = "callable"
     
    29363019        a = """sorted(filter(f, 'abc'), key=blah)[0]"""
    29373020        self.unchanged(a)
     3021        a = """enumerate(filter(f, 'abc'))"""
     3022        self.unchanged(a)
     3023        a = """enumerate(filter(f, 'abc'), start=1)"""
     3024        self.unchanged(a)
    29383025        a = """for i in filter(f, 'abc'): pass"""
    29393026        self.unchanged(a)
     
    30443131        a = """sorted(map(f, 'abc'), key=blah)[0]"""
    30453132        self.unchanged(a)
     3133        a = """enumerate(map(f, 'abc'))"""
     3134        self.unchanged(a)
     3135        a = """enumerate(map(f, 'abc'), start=1)"""
     3136        self.unchanged(a)
    30463137        a = """for i in map(f, 'abc'): pass"""
    30473138        self.unchanged(a)
     
    31063197        self.unchanged(a)
    31073198        a = """sorted(zip(a, b), key=blah)[0]"""
     3199        self.unchanged(a)
     3200        a = """enumerate(zip(a, b))"""
     3201        self.unchanged(a)
     3202        a = """enumerate(zip(a, b), start=1)"""
    31083203        self.unchanged(a)
    31093204        a = """for i in zip(a, b): pass"""
     
    35783673        self.checkall(b, a)
    35793674
    3580     def test_2(self):
     3675    def test_qualified(self):
    35813676        b = """itertools.ifilterfalse(a, b)"""
    35823677        a = """itertools.filterfalse(a, b)"""
    35833678        self.check(b, a)
    35843679
    3585     def test_4(self):
     3680        b = """itertools.izip_longest(a, b)"""
     3681        a = """itertools.zip_longest(a, b)"""
     3682        self.check(b, a)
     3683
     3684    def test_2(self):
    35863685        b = """ifilterfalse(a, b)"""
    35873686        a = """filterfalse(a, b)"""
     3687        self.check(b, a)
     3688
     3689        b = """izip_longest(a, b)"""
     3690        a = """zip_longest(a, b)"""
    35883691        self.check(b, a)
    35893692
     
    35983701        self.check(b, a)
    35993702
     3703        b = """    itertools.izip_longest(a, b)"""
     3704        a = """    itertools.zip_longest(a, b)"""
     3705        self.check(b, a)
     3706
    36003707    def test_run_order(self):
    36013708        self.assert_runs_after('map', 'zip', 'filter')
     3709
    36023710
    36033711class Test_itertools_imports(FixerTestCase):
     
    36133721        self.check(b, a)
    36143722
     3723        b = "from itertools import chain, imap, izip"
     3724        a = "from itertools import chain"
     3725        self.check(b, a)
     3726
    36153727    def test_comments(self):
    36163728        b = "#foo\nfrom itertools import imap, izip"
     
    36473759        self.unchanged(s)
    36483760
    3649     def test_ifilter(self):
    3650         b = "from itertools import ifilterfalse"
    3651         a = "from itertools import filterfalse"
    3652         self.check(b, a)
    3653 
    3654         b = "from itertools import imap, ifilterfalse, foo"
    3655         a = "from itertools import filterfalse, foo"
    3656         self.check(b, a)
    3657 
    3658         b = "from itertools import bar, ifilterfalse, foo"
    3659         a = "from itertools import bar, filterfalse, foo"
    3660         self.check(b, a)
     3761    def test_ifilter_and_zip_longest(self):
     3762        for name in "filterfalse", "zip_longest":
     3763            b = "from itertools import i%s" % (name,)
     3764            a = "from itertools import %s" % (name,)
     3765            self.check(b, a)
     3766
     3767            b = "from itertools import imap, i%s, foo" % (name,)
     3768            a = "from itertools import %s, foo" % (name,)
     3769            self.check(b, a)
     3770
     3771            b = "from itertools import bar, i%s, foo" % (name,)
     3772            a = "from itertools import bar, %s, foo" % (name,)
     3773            self.check(b, a)
     3774
     3775    def test_import_star(self):
     3776        s = "from itertools import *"
     3777        self.unchanged(s)
    36613778
    36623779
     
    36803797            return self.always_exists or (name in self.present_files)
    36813798
    3682         from ..fixes import fix_import
     3799        from lib2to3.fixes import fix_import
    36833800        fix_import.exists = fake_exists
    36843801
     
    37233840        self.unchanged(s)
    37243841
     3842    def test_with_absolute_import_enabled(self):
     3843        s = "from __future__ import absolute_import\nimport bar"
     3844        self.always_exists = False
     3845        self.present_files = set(["__init__.py", "bar.py"])
     3846        self.unchanged(s)
     3847
    37253848    def test_in_package(self):
    37263849        b = "import bar"
     
    37363859        self.present_files = set(["__init__.py", "bar" + os.path.sep])
    37373860        self.check(b, a)
     3861
     3862    def test_already_relative_import(self):
     3863        s = "from . import bar"
     3864        self.unchanged(s)
    37383865
    37393866    def test_comments_and_indent(self):
     
    42794406        self.check(b, a)
    42804407
     4408        b = "operator .sequenceIncludes(x, y)"
     4409        a = "operator .contains(x, y)"
     4410        self.check(b, a)
     4411
     4412        b = "operator.  sequenceIncludes(x, y)"
     4413        a = "operator.  contains(x, y)"
     4414        self.check(b, a)
     4415
     4416    def test_operator_isSequenceType(self):
     4417        b = "operator.isSequenceType(x)"
     4418        a = "import collections\nisinstance(x, collections.Sequence)"
     4419        self.check(b, a)
     4420
     4421    def test_operator_isMappingType(self):
     4422        b = "operator.isMappingType(x)"
     4423        a = "import collections\nisinstance(x, collections.Mapping)"
     4424        self.check(b, a)
     4425
     4426    def test_operator_isNumberType(self):
     4427        b = "operator.isNumberType(x)"
     4428        a = "import numbers\nisinstance(x, numbers.Number)"
     4429        self.check(b, a)
     4430
     4431    def test_operator_repeat(self):
     4432        b = "operator.repeat(x, n)"
     4433        a = "operator.mul(x, n)"
     4434        self.check(b, a)
     4435
     4436        b = "operator .repeat(x, n)"
     4437        a = "operator .mul(x, n)"
     4438        self.check(b, a)
     4439
     4440        b = "operator.  repeat(x, n)"
     4441        a = "operator.  mul(x, n)"
     4442        self.check(b, a)
     4443
     4444    def test_operator_irepeat(self):
     4445        b = "operator.irepeat(x, n)"
     4446        a = "operator.imul(x, n)"
     4447        self.check(b, a)
     4448
     4449        b = "operator .irepeat(x, n)"
     4450        a = "operator .imul(x, n)"
     4451        self.check(b, a)
     4452
     4453        b = "operator.  irepeat(x, n)"
     4454        a = "operator.  imul(x, n)"
     4455        self.check(b, a)
     4456
    42814457    def test_bare_isCallable(self):
    42824458        s = "isCallable(x)"
    4283         self.warns_unchanged(s, "You should use hasattr(x, '__call__') here.")
     4459        t = "You should use 'hasattr(x, '__call__')' here."
     4460        self.warns_unchanged(s, t)
    42844461
    42854462    def test_bare_sequenceIncludes(self):
    42864463        s = "sequenceIncludes(x, y)"
    4287         self.warns_unchanged(s, "You should use operator.contains here.")
     4464        t = "You should use 'operator.contains(x, y)' here."
     4465        self.warns_unchanged(s, t)
     4466
     4467    def test_bare_operator_isSequenceType(self):
     4468        s = "isSequenceType(z)"
     4469        t = "You should use 'isinstance(z, collections.Sequence)' here."
     4470        self.warns_unchanged(s, t)
     4471
     4472    def test_bare_operator_isMappingType(self):
     4473        s = "isMappingType(x)"
     4474        t = "You should use 'isinstance(x, collections.Mapping)' here."
     4475        self.warns_unchanged(s, t)
     4476
     4477    def test_bare_operator_isNumberType(self):
     4478        s = "isNumberType(y)"
     4479        t = "You should use 'isinstance(y, numbers.Number)' here."
     4480        self.warns_unchanged(s, t)
     4481
     4482    def test_bare_operator_repeat(self):
     4483        s = "repeat(x, n)"
     4484        t = "You should use 'operator.mul(x, n)' here."
     4485        self.warns_unchanged(s, t)
     4486
     4487    def test_bare_operator_irepeat(self):
     4488        s = "irepeat(y, 187)"
     4489        t = "You should use 'operator.imul(y, 187)' here."
     4490        self.warns_unchanged(s, t)
     4491
     4492
     4493class Test_exitfunc(FixerTestCase):
     4494
     4495    fixer = "exitfunc"
     4496
     4497    def test_simple(self):
     4498        b = """
     4499            import sys
     4500            sys.exitfunc = my_atexit
     4501            """
     4502        a = """
     4503            import sys
     4504            import atexit
     4505            atexit.register(my_atexit)
     4506            """
     4507        self.check(b, a)
     4508
     4509    def test_names_import(self):
     4510        b = """
     4511            import sys, crumbs
     4512            sys.exitfunc = my_func
     4513            """
     4514        a = """
     4515            import sys, crumbs, atexit
     4516            atexit.register(my_func)
     4517            """
     4518        self.check(b, a)
     4519
     4520    def test_complex_expression(self):
     4521        b = """
     4522            import sys
     4523            sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
     4524            """
     4525        a = """
     4526            import sys
     4527            import atexit
     4528            atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
     4529            """
     4530        self.check(b, a)
     4531
     4532    def test_comments(self):
     4533        b = """
     4534            import sys # Foo
     4535            sys.exitfunc = f # Blah
     4536            """
     4537        a = """
     4538            import sys
     4539            import atexit # Foo
     4540            atexit.register(f) # Blah
     4541            """
     4542        self.check(b, a)
     4543
     4544        b = """
     4545            import apples, sys, crumbs, larry # Pleasant comments
     4546            sys.exitfunc = func
     4547            """
     4548        a = """
     4549            import apples, sys, crumbs, larry, atexit # Pleasant comments
     4550            atexit.register(func)
     4551            """
     4552        self.check(b, a)
     4553
     4554    def test_in_a_function(self):
     4555        b = """
     4556            import sys
     4557            def f():
     4558                sys.exitfunc = func
     4559            """
     4560        a = """
     4561            import sys
     4562            import atexit
     4563            def f():
     4564                atexit.register(func)
     4565             """
     4566        self.check(b, a)
     4567
     4568    def test_no_sys_import(self):
     4569        b = """sys.exitfunc = f"""
     4570        a = """atexit.register(f)"""
     4571        msg = ("Can't find sys import; Please add an atexit import at the "
     4572            "top of your file.")
     4573        self.warns(b, a, msg)
     4574
     4575
     4576    def test_unchanged(self):
     4577        s = """f(sys.exitfunc)"""
     4578        self.unchanged(s)
  • python/trunk/Lib/lib2to3/tests/test_main.py

    r2 r391  
    33import codecs
    44import logging
     5import os
     6import re
     7import shutil
    58import StringIO
     9import sys
     10import tempfile
    611import unittest
    712
     
    914
    1015
     16TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
     17PY2_TEST_MODULE = os.path.join(TEST_DATA_DIR, "py2_test_grammar.py")
     18
     19
    1120class TestMain(unittest.TestCase):
     21
     22    if not hasattr(unittest.TestCase, 'assertNotRegex'):
     23        # This method was only introduced in 3.2.
     24        def assertNotRegex(self, text, regexp, msg=None):
     25            import re
     26            if not hasattr(regexp, 'search'):
     27                regexp = re.compile(regexp)
     28            if regexp.search(text):
     29                self.fail("regexp %s MATCHED text %r" % (regexp.pattern, text))
     30
     31    def setUp(self):
     32        self.temp_dir = None  # tearDown() will rmtree this directory if set.
    1233
    1334    def tearDown(self):
    1435        # Clean up logging configuration down by main.
    1536        del logging.root.handlers[:]
     37        if self.temp_dir:
     38            shutil.rmtree(self.temp_dir)
    1639
    1740    def run_2to3_capture(self, args, in_capture, out_capture, err_capture):
     
    4063        self.assertTrue("WARNING: couldn't encode <stdin>'s diff for "
    4164                        "your terminal" in err.getvalue())
     65
     66    def setup_test_source_trees(self):
     67        """Setup a test source tree and output destination tree."""
     68        self.temp_dir = tempfile.mkdtemp()  # tearDown() cleans this up.
     69        self.py2_src_dir = os.path.join(self.temp_dir, "python2_project")
     70        self.py3_dest_dir = os.path.join(self.temp_dir, "python3_project")
     71        os.mkdir(self.py2_src_dir)
     72        os.mkdir(self.py3_dest_dir)
     73        # Turn it into a package with a few files.
     74        self.setup_files = []
     75        open(os.path.join(self.py2_src_dir, "__init__.py"), "w").close()
     76        self.setup_files.append("__init__.py")
     77        shutil.copy(PY2_TEST_MODULE, self.py2_src_dir)
     78        self.setup_files.append(os.path.basename(PY2_TEST_MODULE))
     79        self.trivial_py2_file = os.path.join(self.py2_src_dir, "trivial.py")
     80        self.init_py2_file = os.path.join(self.py2_src_dir, "__init__.py")
     81        with open(self.trivial_py2_file, "w") as trivial:
     82            trivial.write("print 'I need a simple conversion.'")
     83        self.setup_files.append("trivial.py")
     84
     85    def test_filename_changing_on_output_single_dir(self):
     86        """2to3 a single directory with a new output dir and suffix."""
     87        self.setup_test_source_trees()
     88        out = StringIO.StringIO()
     89        err = StringIO.StringIO()
     90        suffix = "TEST"
     91        ret = self.run_2to3_capture(
     92                ["-n", "--add-suffix", suffix, "--write-unchanged-files",
     93                 "--no-diffs", "--output-dir",
     94                 self.py3_dest_dir, self.py2_src_dir],
     95                StringIO.StringIO(""), out, err)
     96        self.assertEqual(ret, 0)
     97        stderr = err.getvalue()
     98        self.assertIn(" implies -w.", stderr)
     99        self.assertIn(
     100                "Output in %r will mirror the input directory %r layout" % (
     101                        self.py3_dest_dir, self.py2_src_dir), stderr)
     102        self.assertEqual(set(name+suffix for name in self.setup_files),
     103                         set(os.listdir(self.py3_dest_dir)))
     104        for name in self.setup_files:
     105            self.assertIn("Writing converted %s to %s" % (
     106                    os.path.join(self.py2_src_dir, name),
     107                    os.path.join(self.py3_dest_dir, name+suffix)), stderr)
     108        sep = re.escape(os.sep)
     109        self.assertRegexpMatches(
     110                stderr, r"No changes to .*/__init__\.py".replace("/", sep))
     111        self.assertNotRegex(
     112                stderr, r"No changes to .*/trivial\.py".replace("/", sep))
     113
     114    def test_filename_changing_on_output_two_files(self):
     115        """2to3 two files in one directory with a new output dir."""
     116        self.setup_test_source_trees()
     117        err = StringIO.StringIO()
     118        py2_files = [self.trivial_py2_file, self.init_py2_file]
     119        expected_files = set(os.path.basename(name) for name in py2_files)
     120        ret = self.run_2to3_capture(
     121                ["-n", "-w", "--write-unchanged-files",
     122                 "--no-diffs", "--output-dir", self.py3_dest_dir] + py2_files,
     123                StringIO.StringIO(""), StringIO.StringIO(), err)
     124        self.assertEqual(ret, 0)
     125        stderr = err.getvalue()
     126        self.assertIn(
     127                "Output in %r will mirror the input directory %r layout" % (
     128                        self.py3_dest_dir, self.py2_src_dir), stderr)
     129        self.assertEqual(expected_files, set(os.listdir(self.py3_dest_dir)))
     130
     131    def test_filename_changing_on_output_single_file(self):
     132        """2to3 a single file with a new output dir."""
     133        self.setup_test_source_trees()
     134        err = StringIO.StringIO()
     135        ret = self.run_2to3_capture(
     136                ["-n", "-w", "--no-diffs", "--output-dir", self.py3_dest_dir,
     137                 self.trivial_py2_file],
     138                StringIO.StringIO(""), StringIO.StringIO(), err)
     139        self.assertEqual(ret, 0)
     140        stderr = err.getvalue()
     141        self.assertIn(
     142                "Output in %r will mirror the input directory %r layout" % (
     143                        self.py3_dest_dir, self.py2_src_dir), stderr)
     144        self.assertEqual(set([os.path.basename(self.trivial_py2_file)]),
     145                         set(os.listdir(self.py3_dest_dir)))
     146
     147
     148if __name__ == '__main__':
     149    unittest.main()
  • python/trunk/Lib/lib2to3/tests/test_parser.py

    r2 r391  
    77"""
    88
     9from __future__ import with_statement
     10
    911# Testing imports
    1012from . import support
     
    1315# Python imports
    1416import os
    15 import io
    1617import sys
    1718
     
    1920from lib2to3.pgen2 import tokenize
    2021from ..pgen2.parse import ParseError
     22from lib2to3.pygram import python_symbols as syms
     23
     24
     25class TestDriver(support.TestCase):
     26
     27    def test_formfeed(self):
     28        s = """print 1\n\x0Cprint 2\n"""
     29        t = driver.parse_string(s)
     30        self.assertEqual(t.children[0].children[0].type, syms.print_stmt)
     31        self.assertEqual(t.children[1].children[0].type, syms.print_stmt)
    2132
    2233
     
    6374
    6475
    65 # Adapated from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef
     76# Adaptated from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef
    6677class TestFunctionAnnotations(GrammarTest):
    6778    def test_1(self):
     
    157168            self.assertTrue(encoding is not None,
    158169                            "can't detect encoding for %s" % filepath)
    159             with io.open(filepath, "r", encoding=encoding) as fp:
     170            with open(filepath, "r") as fp:
    160171                source = fp.read()
     172                source = source.decode(encoding)
    161173            tree = driver.parse_string(source)
    162174            new = unicode(tree)
     
    204216
    205217def diff(fn, result, encoding):
    206     f = io.open("@", "w", encoding=encoding)
     218    f = open("@", "w")
    207219    try:
    208         f.write(result)
     220        f.write(result.encode(encoding))
    209221    finally:
    210222        f.close()
    211223    try:
    212         return os.system("diff -u %r @" % fn)
     224        fn = fn.replace('"', '\\"')
     225        return os.system('diff -u "%s" @' % fn)
    213226    finally:
    214227        os.remove("@")
  • python/trunk/Lib/lib2to3/tests/test_pytree.py

    r2 r391  
    1010"""
    1111
     12from __future__ import with_statement
     13
     14import sys
    1215import warnings
    1316
     
    2932    """Unit tests for nodes (Base, Leaf, Node)."""
    3033
    31     def test_deprecated_prefix_methods(self):
    32         l = pytree.Leaf(100, "foo")
    33         with warnings.catch_warnings(record=True) as w:
    34             warnings.simplefilter("always", DeprecationWarning)
    35             self.assertEqual(l.get_prefix(), "")
    36             l.set_prefix("hi")
    37         self.assertEqual(l.prefix, "hi")
    38         self.assertEqual(len(w), 2)
    39         for warning in w:
    40             self.assertTrue(warning.category is DeprecationWarning)
    41         self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \
    42                              "use the prefix property")
    43         self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \
    44                              "use the prefix property")
     34    if sys.version_info >= (2,6):
     35        # warnings.catch_warnings is new in 2.6.
     36        def test_deprecated_prefix_methods(self):
     37            l = pytree.Leaf(100, "foo")
     38            with warnings.catch_warnings(record=True) as w:
     39                warnings.simplefilter("always", DeprecationWarning)
     40                self.assertEqual(l.get_prefix(), "")
     41                l.set_prefix("hi")
     42            self.assertEqual(l.prefix, "hi")
     43            self.assertEqual(len(w), 2)
     44            for warning in w:
     45                self.assertTrue(warning.category is DeprecationWarning)
     46            self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \
     47                                 "use the prefix property")
     48            self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \
     49                                 "use the prefix property")
    4550
    4651    def test_instantiate_base(self):
     
    174179        self.assertTrue(isinstance(n1.children, list))
    175180
     181    def test_leaves(self):
     182        l1 = pytree.Leaf(100, "foo")
     183        l2 = pytree.Leaf(100, "bar")
     184        l3 = pytree.Leaf(100, "fooey")
     185        n2 = pytree.Node(1000, [l1, l2])
     186        n3 = pytree.Node(1000, [l3])
     187        n1 = pytree.Node(1000, [n2, n3])
     188
     189        self.assertEqual(list(n1.leaves()), [l1, l2, l3])
     190
     191    def test_depth(self):
     192        l1 = pytree.Leaf(100, "foo")
     193        l2 = pytree.Leaf(100, "bar")
     194        n2 = pytree.Node(1000, [l1, l2])
     195        n3 = pytree.Node(1000, [])
     196        n1 = pytree.Node(1000, [n2, n3])
     197
     198        self.assertEqual(l1.depth(), 2)
     199        self.assertEqual(n3.depth(), 1)
     200        self.assertEqual(n1.depth(), 0)
     201
    176202    def test_post_order(self):
    177203        l1 = pytree.Leaf(100, "foo")
    178204        l2 = pytree.Leaf(100, "bar")
    179         n1 = pytree.Node(1000, [l1, l2])
    180         self.assertEqual(list(n1.post_order()), [l1, l2, n1])
     205        l3 = pytree.Leaf(100, "fooey")
     206        c1 = pytree.Node(1000, [l1, l2])
     207        n1 = pytree.Node(1000, [c1, l3])
     208        self.assertEqual(list(n1.post_order()), [l1, l2, c1, l3, n1])
    181209
    182210    def test_pre_order(self):
    183211        l1 = pytree.Leaf(100, "foo")
    184212        l2 = pytree.Leaf(100, "bar")
    185         n1 = pytree.Node(1000, [l1, l2])
    186         self.assertEqual(list(n1.pre_order()), [n1, l1, l2])
     213        l3 = pytree.Leaf(100, "fooey")
     214        c1 = pytree.Node(1000, [l1, l2])
     215        n1 = pytree.Node(1000, [c1, l3])
     216        self.assertEqual(list(n1.pre_order()), [n1, c1, l1, l2, l3])
    187217
    188218    def test_changed(self):
  • python/trunk/Lib/lib2to3/tests/test_refactor.py

    r2 r391  
    22Unit tests for refactor.py.
    33"""
     4
     5from __future__ import with_statement
    46
    57import sys
     
    5254                        pygram.python_grammar_no_print_statement)
    5355
     56    def test_write_unchanged_files_option(self):
     57        rt = self.rt()
     58        self.assertFalse(rt.write_unchanged_files)
     59        rt = self.rt({"write_unchanged_files" : True})
     60        self.assertTrue(rt.write_unchanged_files)
     61
    5462    def test_fixer_loading_helpers(self):
    5563        contents = ["explicit", "first", "last", "parrot", "preorder"]
     
    6270                         ["myfixes.fix_" + name for name in contents])
    6371
    64     def test_detect_future_print(self):
    65         run = refactor._detect_future_print
    66         self.assertFalse(run(""))
    67         self.assertTrue(run("from __future__ import print_function"))
    68         self.assertFalse(run("from __future__ import generators"))
    69         self.assertFalse(run("from __future__ import generators, feature"))
    70         input = "from __future__ import generators, print_function"
    71         self.assertTrue(run(input))
    72         input ="from __future__ import print_function, generators"
    73         self.assertTrue(run(input))
    74         input = "from __future__ import (print_function,)"
    75         self.assertTrue(run(input))
    76         input = "from __future__ import (generators, print_function)"
    77         self.assertTrue(run(input))
    78         input = "from __future__ import (generators, nested_scopes)"
    79         self.assertFalse(run(input))
    80         input = """from __future__ import generators
     72    def test_detect_future_features(self):
     73        run = refactor._detect_future_features
     74        fs = frozenset
     75        empty = fs()
     76        self.assertEqual(run(""), empty)
     77        self.assertEqual(run("from __future__ import print_function"),
     78                         fs(("print_function",)))
     79        self.assertEqual(run("from __future__ import generators"),
     80                         fs(("generators",)))
     81        self.assertEqual(run("from __future__ import generators, feature"),
     82                         fs(("generators", "feature")))
     83        inp = "from __future__ import generators, print_function"
     84        self.assertEqual(run(inp), fs(("generators", "print_function")))
     85        inp ="from __future__ import print_function, generators"
     86        self.assertEqual(run(inp), fs(("print_function", "generators")))
     87        inp = "from __future__ import (print_function,)"
     88        self.assertEqual(run(inp), fs(("print_function",)))
     89        inp = "from __future__ import (generators, print_function)"
     90        self.assertEqual(run(inp), fs(("generators", "print_function")))
     91        inp = "from __future__ import (generators, nested_scopes)"
     92        self.assertEqual(run(inp), fs(("generators", "nested_scopes")))
     93        inp = """from __future__ import generators
    8194from __future__ import print_function"""
    82         self.assertTrue(run(input))
    83         self.assertFalse(run("from"))
    84         self.assertFalse(run("from 4"))
    85         self.assertFalse(run("from x"))
    86         self.assertFalse(run("from x 5"))
    87         self.assertFalse(run("from x im"))
    88         self.assertFalse(run("from x import"))
    89         self.assertFalse(run("from x import 4"))
    90         input = "'docstring'\nfrom __future__ import print_function"
    91         self.assertTrue(run(input))
    92         input = "'docstring'\n'somng'\nfrom __future__ import print_function"
    93         self.assertFalse(run(input))
    94         input = "# comment\nfrom __future__ import print_function"
    95         self.assertTrue(run(input))
    96         input = "# comment\n'doc'\nfrom __future__ import print_function"
    97         self.assertTrue(run(input))
    98         input = "class x: pass\nfrom __future__ import print_function"
    99         self.assertFalse(run(input))
     95        self.assertEqual(run(inp), fs(("generators", "print_function")))
     96        invalid = ("from",
     97                   "from 4",
     98                   "from x",
     99                   "from x 5",
     100                   "from x im",
     101                   "from x import",
     102                   "from x import 4",
     103                   )
     104        for inp in invalid:
     105            self.assertEqual(run(inp), empty)
     106        inp = "'docstring'\nfrom __future__ import print_function"
     107        self.assertEqual(run(inp), fs(("print_function",)))
     108        inp = "'docstring'\n'somng'\nfrom __future__ import print_function"
     109        self.assertEqual(run(inp), empty)
     110        inp = "# comment\nfrom __future__ import print_function"
     111        self.assertEqual(run(inp), fs(("print_function",)))
     112        inp = "# comment\n'doc'\nfrom __future__ import print_function"
     113        self.assertEqual(run(inp), fs(("print_function",)))
     114        inp = "class x: pass\nfrom __future__ import print_function"
     115        self.assertEqual(run(inp), empty)
    100116
    101117    def test_get_headnode_dict(self):
     
    167183        self.assertEqual(results, expected)
    168184
    169     def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS):
     185    def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS,
     186                               options=None, mock_log_debug=None,
     187                               actually_write=True):
     188        tmpdir = tempfile.mkdtemp(prefix="2to3-test_refactor")
     189        self.addCleanup(shutil.rmtree, tmpdir)
     190        # make a copy of the tested file that we can write to
     191        shutil.copy(test_file, tmpdir)
     192        test_file = os.path.join(tmpdir, os.path.basename(test_file))
     193        os.chmod(test_file, 0o644)
     194
    170195        def read_file():
    171196            with open(test_file, "rb") as fp:
    172197                return fp.read()
     198
    173199        old_contents = read_file()
    174         rt = self.rt(fixers=fixers)
     200        rt = self.rt(fixers=fixers, options=options)
     201        if mock_log_debug:
     202            rt.log_debug = mock_log_debug
    175203
    176204        rt.refactor_file(test_file)
    177205        self.assertEqual(old_contents, read_file())
    178206
    179         try:
    180             rt.refactor_file(test_file, True)
    181             new_contents = read_file()
    182             self.assertNotEqual(old_contents, new_contents)
    183         finally:
    184             with open(test_file, "wb") as fp:
    185                 fp.write(old_contents)
     207        if not actually_write:
     208            return
     209        rt.refactor_file(test_file, True)
     210        new_contents = read_file()
     211        self.assertNotEqual(old_contents, new_contents)
    186212        return new_contents
    187213
     
    189215        test_file = os.path.join(FIXER_DIR, "parrot_example.py")
    190216        self.check_file_refactoring(test_file, _DEFAULT_FIXERS)
     217
     218    def test_refactor_file_write_unchanged_file(self):
     219        test_file = os.path.join(FIXER_DIR, "parrot_example.py")
     220        debug_messages = []
     221        def recording_log_debug(msg, *args):
     222            debug_messages.append(msg % args)
     223        self.check_file_refactoring(test_file, fixers=(),
     224                                    options={"write_unchanged_files": True},
     225                                    mock_log_debug=recording_log_debug,
     226                                    actually_write=False)
     227        # Testing that it logged this message when write=False was passed is
     228        # sufficient to see that it did not bail early after "No changes".
     229        message_regex = r"Not writing changes to .*%s%s" % (
     230                os.sep, os.path.basename(test_file))
     231        for message in debug_messages:
     232            if "Not writing changes" in message:
     233                self.assertRegexpMatches(message, message_regex)
     234                break
     235        else:
     236            self.fail("%r not matched in %r" % (message_regex, debug_messages))
    191237
    192238    def test_refactor_dir(self):
     
    214260                ".dumb",
    215261                ".after.py",
     262                "notpy.npy",
    216263                "sappy"]
    217264        expected = ["hi.py"]
     
    224271        fn = os.path.join(TEST_DATA_DIR, "different_encoding.py")
    225272        self.check_file_refactoring(fn)
     273
     274    def test_false_file_encoding(self):
     275        fn = os.path.join(TEST_DATA_DIR, "false_encoding.py")
     276        data = self.check_file_refactoring(fn)
    226277
    227278    def test_bom(self):
  • python/trunk/Lib/lib2to3/tests/test_util.py

    r2 r391  
    569569    def test_from_import(self):
    570570        node = parse('bar()')
    571         fixer_util.touch_import("cgi", "escape", node)
    572         self.assertEqual(str(node), 'from cgi import escape\nbar()\n\n')
     571        fixer_util.touch_import("html", "escape", node)
     572        self.assertEqual(str(node), 'from html import escape\nbar()\n\n')
    573573
    574574    def test_name_import(self):
     
    576576        fixer_util.touch_import(None, "cgi", node)
    577577        self.assertEqual(str(node), 'import cgi\nbar()\n\n')
     578
     579class Test_find_indentation(support.TestCase):
     580
     581    def test_nothing(self):
     582        fi = fixer_util.find_indentation
     583        node = parse("node()")
     584        self.assertEqual(fi(node), u"")
     585        node = parse("")
     586        self.assertEqual(fi(node), u"")
     587
     588    def test_simple(self):
     589        fi = fixer_util.find_indentation
     590        node = parse("def f():\n    x()")
     591        self.assertEqual(fi(node), u"")
     592        self.assertEqual(fi(node.children[0].children[4].children[2]), u"    ")
     593        node = parse("def f():\n    x()\n    y()")
     594        self.assertEqual(fi(node.children[0].children[4].children[4]), u"    ")
Note: See TracChangeset for help on using the changeset viewer.