Changeset 391 for python/trunk/Lib/lib2to3/tests
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 10 edited
- 1 copied
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/lib2to3/tests/data/bom.py
r2 r391 1 1 # coding: utf-8 2 2 print "BOM BOOM!" 3 -
python/trunk/Lib/lib2to3/tests/data/py2_test_grammar.py
r2 r391 317 317 x = 1; pass; del x 318 318 def foo(): 319 # verify stat ments that end with semi-colons319 # verify statements that end with semi-colons 320 320 x = 1; pass; del x; 321 321 foo() -
python/trunk/Lib/lib2to3/tests/data/py3_test_grammar.py
r2 r391 357 357 x = 1; pass; del x 358 358 def foo(): 359 # verify stat ments that end with semi-colons359 # verify statements that end with semi-colons 360 360 x = 1; pass; del x; 361 361 foo() -
python/trunk/Lib/lib2to3/tests/test_fixers.py
r2 r391 869 869 self.check(b, a) 870 870 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 871 876 def test_tuple_value(self): 872 877 b = """raise Exception, (5, 6, 7)""" … … 1401 1406 self.check(b, a) 1402 1407 1403 def test_ 14(self):1408 def test_28(self): 1404 1409 b = "[i for i in d.viewkeys()]" 1405 1410 a = "[i for i in d.keys()]" 1406 1411 self.check(b, a) 1407 1412 1408 def test_ 15(self):1413 def test_29(self): 1409 1414 b = "(i for i in d.viewkeys())" 1410 1415 a = "(i for i in d.keys())" 1411 1416 self.check(b, a) 1412 1417 1413 def test_ 17(self):1418 def test_30(self): 1414 1419 b = "iter(d.viewkeys())" 1415 1420 a = "iter(d.keys())" 1416 1421 self.check(b, a) 1417 1422 1418 def test_ 18(self):1423 def test_31(self): 1419 1424 b = "list(d.viewkeys())" 1420 1425 a = "list(d.keys())" 1421 1426 self.check(b, a) 1422 1427 1423 def test_ 19(self):1428 def test_32(self): 1424 1429 b = "sorted(d.viewkeys())" 1425 1430 a = "sorted(d.keys())" … … 1497 1502 for call in fixer_util.consuming_calls: 1498 1503 self.unchanged("a = %s(range(10))" % call) 1504 1505 class 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 1513 reduce(x, range(5))""" 1514 self.check(b, a) 1499 1515 1500 1516 class Test_raw_input(FixerTestCase): … … 1802 1818 a = "from %s import %s as foo_bar" % (new, member) 1803 1819 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) 1804 1823 1805 1824 def test_star(self): … … 1807 1826 s = "from %s import *" % old 1808 1827 self.warns_unchanged(s, "Cannot handle star imports") 1828 1829 def test_indented(self): 1830 b = """ 1831 def foo(): 1832 from urllib import urlencode, urlopen 1833 """ 1834 a = """ 1835 def foo(): 1836 from urllib.parse import urlencode 1837 from urllib.request import urlopen 1838 """ 1839 self.check(b, a) 1840 1841 b = """ 1842 def foo(): 1843 other() 1844 from urllib import urlencode, urlopen 1845 """ 1846 a = """ 1847 def foo(): 1848 other() 1849 from urllib.parse import urlencode 1850 from urllib.request import urlopen 1851 """ 1852 self.check(b, a) 1853 1854 1809 1855 1810 1856 def test_import_module_usage(self): … … 2779 2825 self.check(b, a) 2780 2826 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 2781 2864 class Test_callable(FixerTestCase): 2782 2865 fixer = "callable" … … 2936 3019 a = """sorted(filter(f, 'abc'), key=blah)[0]""" 2937 3020 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) 2938 3025 a = """for i in filter(f, 'abc'): pass""" 2939 3026 self.unchanged(a) … … 3044 3131 a = """sorted(map(f, 'abc'), key=blah)[0]""" 3045 3132 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) 3046 3137 a = """for i in map(f, 'abc'): pass""" 3047 3138 self.unchanged(a) … … 3106 3197 self.unchanged(a) 3107 3198 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)""" 3108 3203 self.unchanged(a) 3109 3204 a = """for i in zip(a, b): pass""" … … 3578 3673 self.checkall(b, a) 3579 3674 3580 def test_ 2(self):3675 def test_qualified(self): 3581 3676 b = """itertools.ifilterfalse(a, b)""" 3582 3677 a = """itertools.filterfalse(a, b)""" 3583 3678 self.check(b, a) 3584 3679 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): 3586 3685 b = """ifilterfalse(a, b)""" 3587 3686 a = """filterfalse(a, b)""" 3687 self.check(b, a) 3688 3689 b = """izip_longest(a, b)""" 3690 a = """zip_longest(a, b)""" 3588 3691 self.check(b, a) 3589 3692 … … 3598 3701 self.check(b, a) 3599 3702 3703 b = """ itertools.izip_longest(a, b)""" 3704 a = """ itertools.zip_longest(a, b)""" 3705 self.check(b, a) 3706 3600 3707 def test_run_order(self): 3601 3708 self.assert_runs_after('map', 'zip', 'filter') 3709 3602 3710 3603 3711 class Test_itertools_imports(FixerTestCase): … … 3613 3721 self.check(b, a) 3614 3722 3723 b = "from itertools import chain, imap, izip" 3724 a = "from itertools import chain" 3725 self.check(b, a) 3726 3615 3727 def test_comments(self): 3616 3728 b = "#foo\nfrom itertools import imap, izip" … … 3647 3759 self.unchanged(s) 3648 3760 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) 3661 3778 3662 3779 … … 3680 3797 return self.always_exists or (name in self.present_files) 3681 3798 3682 from ..fixes import fix_import3799 from lib2to3.fixes import fix_import 3683 3800 fix_import.exists = fake_exists 3684 3801 … … 3723 3840 self.unchanged(s) 3724 3841 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 3725 3848 def test_in_package(self): 3726 3849 b = "import bar" … … 3736 3859 self.present_files = set(["__init__.py", "bar" + os.path.sep]) 3737 3860 self.check(b, a) 3861 3862 def test_already_relative_import(self): 3863 s = "from . import bar" 3864 self.unchanged(s) 3738 3865 3739 3866 def test_comments_and_indent(self): … … 4279 4406 self.check(b, a) 4280 4407 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 4281 4457 def test_bare_isCallable(self): 4282 4458 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) 4284 4461 4285 4462 def test_bare_sequenceIncludes(self): 4286 4463 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 4493 class 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 3 3 import codecs 4 4 import logging 5 import os 6 import re 7 import shutil 5 8 import StringIO 9 import sys 10 import tempfile 6 11 import unittest 7 12 … … 9 14 10 15 16 TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") 17 PY2_TEST_MODULE = os.path.join(TEST_DATA_DIR, "py2_test_grammar.py") 18 19 11 20 class 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. 12 33 13 34 def tearDown(self): 14 35 # Clean up logging configuration down by main. 15 36 del logging.root.handlers[:] 37 if self.temp_dir: 38 shutil.rmtree(self.temp_dir) 16 39 17 40 def run_2to3_capture(self, args, in_capture, out_capture, err_capture): … … 40 63 self.assertTrue("WARNING: couldn't encode <stdin>'s diff for " 41 64 "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 148 if __name__ == '__main__': 149 unittest.main() -
python/trunk/Lib/lib2to3/tests/test_parser.py
r2 r391 7 7 """ 8 8 9 from __future__ import with_statement 10 9 11 # Testing imports 10 12 from . import support … … 13 15 # Python imports 14 16 import os 15 import io16 17 import sys 17 18 … … 19 20 from lib2to3.pgen2 import tokenize 20 21 from ..pgen2.parse import ParseError 22 from lib2to3.pygram import python_symbols as syms 23 24 25 class 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) 21 32 22 33 … … 63 74 64 75 65 # Adap ated from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef76 # Adaptated from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef 66 77 class TestFunctionAnnotations(GrammarTest): 67 78 def test_1(self): … … 157 168 self.assertTrue(encoding is not None, 158 169 "can't detect encoding for %s" % filepath) 159 with io.open(filepath, "r", encoding=encoding) as fp:170 with open(filepath, "r") as fp: 160 171 source = fp.read() 172 source = source.decode(encoding) 161 173 tree = driver.parse_string(source) 162 174 new = unicode(tree) … … 204 216 205 217 def diff(fn, result, encoding): 206 f = io.open("@", "w", encoding=encoding)218 f = open("@", "w") 207 219 try: 208 f.write(result )220 f.write(result.encode(encoding)) 209 221 finally: 210 222 f.close() 211 223 try: 212 return os.system("diff -u %r @" % fn) 224 fn = fn.replace('"', '\\"') 225 return os.system('diff -u "%s" @' % fn) 213 226 finally: 214 227 os.remove("@") -
python/trunk/Lib/lib2to3/tests/test_pytree.py
r2 r391 10 10 """ 11 11 12 from __future__ import with_statement 13 14 import sys 12 15 import warnings 13 16 … … 29 32 """Unit tests for nodes (Base, Leaf, Node).""" 30 33 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") 45 50 46 51 def test_instantiate_base(self): … … 174 179 self.assertTrue(isinstance(n1.children, list)) 175 180 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 176 202 def test_post_order(self): 177 203 l1 = pytree.Leaf(100, "foo") 178 204 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]) 181 209 182 210 def test_pre_order(self): 183 211 l1 = pytree.Leaf(100, "foo") 184 212 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]) 187 217 188 218 def test_changed(self): -
python/trunk/Lib/lib2to3/tests/test_refactor.py
r2 r391 2 2 Unit tests for refactor.py. 3 3 """ 4 5 from __future__ import with_statement 4 6 5 7 import sys … … 52 54 pygram.python_grammar_no_print_statement) 53 55 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 54 62 def test_fixer_loading_helpers(self): 55 63 contents = ["explicit", "first", "last", "parrot", "preorder"] … … 62 70 ["myfixes.fix_" + name for name in contents]) 63 71 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 81 94 from __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) 100 116 101 117 def test_get_headnode_dict(self): … … 167 183 self.assertEqual(results, expected) 168 184 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 170 195 def read_file(): 171 196 with open(test_file, "rb") as fp: 172 197 return fp.read() 198 173 199 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 175 203 176 204 rt.refactor_file(test_file) 177 205 self.assertEqual(old_contents, read_file()) 178 206 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) 186 212 return new_contents 187 213 … … 189 215 test_file = os.path.join(FIXER_DIR, "parrot_example.py") 190 216 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)) 191 237 192 238 def test_refactor_dir(self): … … 214 260 ".dumb", 215 261 ".after.py", 262 "notpy.npy", 216 263 "sappy"] 217 264 expected = ["hi.py"] … … 224 271 fn = os.path.join(TEST_DATA_DIR, "different_encoding.py") 225 272 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) 226 277 227 278 def test_bom(self): -
python/trunk/Lib/lib2to3/tests/test_util.py
r2 r391 569 569 def test_from_import(self): 570 570 node = parse('bar()') 571 fixer_util.touch_import(" cgi", "escape", node)572 self.assertEqual(str(node), 'from cgiimport escape\nbar()\n\n')571 fixer_util.touch_import("html", "escape", node) 572 self.assertEqual(str(node), 'from html import escape\nbar()\n\n') 573 573 574 574 def test_name_import(self): … … 576 576 fixer_util.touch_import(None, "cgi", node) 577 577 self.assertEqual(str(node), 'import cgi\nbar()\n\n') 578 579 class 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.