PageRenderTime 486ms CodeModel.GetById 152ms app.highlight 15ms RepoModel.GetById 216ms app.codeStats 0ms

/Lib/lib2to3/tests/test_refactor.py

http://unladen-swallow.googlecode.com/
Python | 170 lines | 141 code | 26 blank | 3 comment | 9 complexity | 1733c3da5e35a7ae29ad4096941426a0 MD5 | raw file
  1"""
  2Unit tests for refactor.py.
  3"""
  4
  5import sys
  6import os
  7import operator
  8import StringIO
  9import tempfile
 10import unittest
 11
 12from lib2to3 import refactor, pygram, fixer_base
 13
 14from . import support
 15
 16
 17FIXER_DIR = os.path.join(os.path.dirname(__file__), "data/fixers")
 18
 19sys.path.append(FIXER_DIR)
 20try:
 21    _DEFAULT_FIXERS = refactor.get_fixers_from_package("myfixes")
 22finally:
 23    sys.path.pop()
 24
 25class TestRefactoringTool(unittest.TestCase):
 26
 27    def setUp(self):
 28        sys.path.append(FIXER_DIR)
 29
 30    def tearDown(self):
 31        sys.path.pop()
 32
 33    def check_instances(self, instances, classes):
 34        for inst, cls in zip(instances, classes):
 35            if not isinstance(inst, cls):
 36                self.fail("%s are not instances of %s" % instances, classes)
 37
 38    def rt(self, options=None, fixers=_DEFAULT_FIXERS, explicit=None):
 39        return refactor.RefactoringTool(fixers, options, explicit)
 40
 41    def test_print_function_option(self):
 42        gram = pygram.python_grammar
 43        save = gram.keywords["print"]
 44        try:
 45            rt = self.rt({"print_function" : True})
 46            self.assertRaises(KeyError, operator.itemgetter("print"),
 47                              gram.keywords)
 48        finally:
 49            gram.keywords["print"] = save
 50
 51    def test_fixer_loading_helpers(self):
 52        contents = ["explicit", "first", "last", "parrot", "preorder"]
 53        non_prefixed = refactor.get_all_fix_names("myfixes")
 54        prefixed = refactor.get_all_fix_names("myfixes", False)
 55        full_names = refactor.get_fixers_from_package("myfixes")
 56        self.assertEqual(prefixed, ["fix_" + name for name in contents])
 57        self.assertEqual(non_prefixed, contents)
 58        self.assertEqual(full_names,
 59                         ["myfixes.fix_" + name for name in contents])
 60
 61    def test_get_headnode_dict(self):
 62        class NoneFix(fixer_base.BaseFix):
 63            PATTERN = None
 64
 65        class FileInputFix(fixer_base.BaseFix):
 66            PATTERN = "file_input< any * >"
 67
 68        no_head = NoneFix({}, [])
 69        with_head = FileInputFix({}, [])
 70        d = refactor.get_headnode_dict([no_head, with_head])
 71        expected = {None: [no_head],
 72                    pygram.python_symbols.file_input : [with_head]}
 73        self.assertEqual(d, expected)
 74
 75    def test_fixer_loading(self):
 76        from myfixes.fix_first import FixFirst
 77        from myfixes.fix_last import FixLast
 78        from myfixes.fix_parrot import FixParrot
 79        from myfixes.fix_preorder import FixPreorder
 80
 81        rt = self.rt()
 82        pre, post = rt.get_fixers()
 83
 84        self.check_instances(pre, [FixPreorder])
 85        self.check_instances(post, [FixFirst, FixParrot, FixLast])
 86
 87    def test_naughty_fixers(self):
 88        self.assertRaises(ImportError, self.rt, fixers=["not_here"])
 89        self.assertRaises(refactor.FixerError, self.rt, fixers=["no_fixer_cls"])
 90        self.assertRaises(refactor.FixerError, self.rt, fixers=["bad_order"])
 91
 92    def test_refactor_string(self):
 93        rt = self.rt()
 94        input = "def parrot(): pass\n\n"
 95        tree = rt.refactor_string(input, "<test>")
 96        self.assertNotEqual(str(tree), input)
 97
 98        input = "def f(): pass\n\n"
 99        tree = rt.refactor_string(input, "<test>")
100        self.assertEqual(str(tree), input)
101
102    def test_refactor_stdin(self):
103
104        class MyRT(refactor.RefactoringTool):
105
106            def print_output(self, lines):
107                diff_lines.extend(lines)
108
109        diff_lines = []
110        rt = MyRT(_DEFAULT_FIXERS)
111        save = sys.stdin
112        sys.stdin = StringIO.StringIO("def parrot(): pass\n\n")
113        try:
114            rt.refactor_stdin()
115        finally:
116            sys.stdin = save
117        expected = """--- <stdin> (original)
118+++ <stdin> (refactored)
119@@ -1,2 +1,2 @@
120-def parrot(): pass
121+def cheese(): pass""".splitlines()
122        self.assertEqual(diff_lines[:-1], expected)
123
124    def test_refactor_file(self):
125        test_file = os.path.join(FIXER_DIR, "parrot_example.py")
126        old_contents = open(test_file, "r").read()
127        rt = self.rt()
128
129        rt.refactor_file(test_file)
130        self.assertEqual(old_contents, open(test_file, "r").read())
131
132        rt.refactor_file(test_file, True)
133        try:
134            self.assertNotEqual(old_contents, open(test_file, "r").read())
135        finally:
136            open(test_file, "w").write(old_contents)
137
138    # Docstrings are omitted when Python is passed -OO, so skip this test.
139    if sys.flags.optimize <= 1:
140        def test_refactor_docstring(self):
141            rt = self.rt()
142
143            def example():
144                """
145                >>> example()
146                42
147                """
148            out = rt.refactor_docstring(example.__doc__, "<test>")
149            self.assertEqual(out, example.__doc__)
150
151            def parrot():
152                """
153                >>> def parrot():
154                ...      return 43
155                """
156            out = rt.refactor_docstring(parrot.__doc__, "<test>")
157            self.assertNotEqual(out, parrot.__doc__)
158
159    def test_explicit(self):
160        from myfixes.fix_explicit import FixExplicit
161
162        rt = self.rt(fixers=["myfixes.fix_explicit"])
163        self.assertEqual(len(rt.post_order), 0)
164
165        rt = self.rt(explicit=["myfixes.fix_explicit"])
166        for fix in rt.post_order:
167            if isinstance(fix, FixExplicit):
168                break
169        else:
170            self.fail("explicit fixer not loaded")