blob: f30c1e8630958d0f233bfd0c21e102ab6d2bb281 [file] [log] [blame]
Benjamin Petersond61de7f2008-09-27 22:17:35 +00001"""
2Unit tests for refactor.py.
3"""
4
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +00005from __future__ import with_statement
6
Benjamin Petersond61de7f2008-09-27 22:17:35 +00007import sys
8import os
Benjamin Peterson20211002009-11-25 18:34:42 +00009import codecs
Benjamin Petersond61de7f2008-09-27 22:17:35 +000010import operator
11import io
12import tempfile
Benjamin Peterson3059b002009-07-20 16:42:03 +000013import shutil
Benjamin Petersond61de7f2008-09-27 22:17:35 +000014import unittest
Benjamin Peterson3059b002009-07-20 16:42:03 +000015import warnings
Benjamin Petersond61de7f2008-09-27 22:17:35 +000016
17from lib2to3 import refactor, pygram, fixer_base
Benjamin Peterson3059b002009-07-20 16:42:03 +000018from lib2to3.pgen2 import token
Benjamin Petersond61de7f2008-09-27 22:17:35 +000019
20from . import support
21
22
Benjamin Petersond481e3d2009-05-09 19:42:23 +000023TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
24FIXER_DIR = os.path.join(TEST_DATA_DIR, "fixers")
Benjamin Petersond61de7f2008-09-27 22:17:35 +000025
26sys.path.append(FIXER_DIR)
27try:
28 _DEFAULT_FIXERS = refactor.get_fixers_from_package("myfixes")
29finally:
30 sys.path.pop()
31
Benjamin Petersond481e3d2009-05-09 19:42:23 +000032_2TO3_FIXERS = refactor.get_fixers_from_package("lib2to3.fixes")
33
Benjamin Petersond61de7f2008-09-27 22:17:35 +000034class TestRefactoringTool(unittest.TestCase):
35
36 def setUp(self):
37 sys.path.append(FIXER_DIR)
38
39 def tearDown(self):
40 sys.path.pop()
41
42 def check_instances(self, instances, classes):
43 for inst, cls in zip(instances, classes):
44 if not isinstance(inst, cls):
45 self.fail("%s are not instances of %s" % instances, classes)
46
47 def rt(self, options=None, fixers=_DEFAULT_FIXERS, explicit=None):
48 return refactor.RefactoringTool(fixers, options, explicit)
49
50 def test_print_function_option(self):
Benjamin Peterson20211002009-11-25 18:34:42 +000051 rt = self.rt({"print_function" : True})
Serhiy Storchaka8bdc1302013-11-14 23:49:58 +020052 self.assertIs(rt.grammar, pygram.python_grammar_no_print_statement)
53 self.assertIs(rt.driver.grammar,
54 pygram.python_grammar_no_print_statement)
Benjamin Petersond61de7f2008-09-27 22:17:35 +000055
Gregory P. Smith58f23ff2012-02-12 15:50:21 -080056 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
Benjamin Petersond61de7f2008-09-27 22:17:35 +000062 def test_fixer_loading_helpers(self):
63 contents = ["explicit", "first", "last", "parrot", "preorder"]
64 non_prefixed = refactor.get_all_fix_names("myfixes")
65 prefixed = refactor.get_all_fix_names("myfixes", False)
66 full_names = refactor.get_fixers_from_package("myfixes")
67 self.assertEqual(prefixed, ["fix_" + name for name in contents])
68 self.assertEqual(non_prefixed, contents)
69 self.assertEqual(full_names,
70 ["myfixes.fix_" + name for name in contents])
71
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +000072 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
Benjamin Peterson3059b002009-07-20 16:42:03 +000094from __future__ import print_function"""
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +000095 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)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000116
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000117 def test_get_headnode_dict(self):
118 class NoneFix(fixer_base.BaseFix):
Benjamin Peterson3059b002009-07-20 16:42:03 +0000119 pass
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000120
121 class FileInputFix(fixer_base.BaseFix):
122 PATTERN = "file_input< any * >"
123
Benjamin Peterson3059b002009-07-20 16:42:03 +0000124 class SimpleFix(fixer_base.BaseFix):
125 PATTERN = "'name'"
126
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000127 no_head = NoneFix({}, [])
128 with_head = FileInputFix({}, [])
Benjamin Peterson3059b002009-07-20 16:42:03 +0000129 simple = SimpleFix({}, [])
130 d = refactor._get_headnode_dict([no_head, with_head, simple])
131 top_fixes = d.pop(pygram.python_symbols.file_input)
132 self.assertEqual(top_fixes, [with_head, no_head])
133 name_fixes = d.pop(token.NAME)
134 self.assertEqual(name_fixes, [simple, no_head])
135 for fixes in d.values():
136 self.assertEqual(fixes, [no_head])
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000137
138 def test_fixer_loading(self):
139 from myfixes.fix_first import FixFirst
140 from myfixes.fix_last import FixLast
141 from myfixes.fix_parrot import FixParrot
142 from myfixes.fix_preorder import FixPreorder
143
144 rt = self.rt()
145 pre, post = rt.get_fixers()
146
147 self.check_instances(pre, [FixPreorder])
148 self.check_instances(post, [FixFirst, FixParrot, FixLast])
149
150 def test_naughty_fixers(self):
151 self.assertRaises(ImportError, self.rt, fixers=["not_here"])
152 self.assertRaises(refactor.FixerError, self.rt, fixers=["no_fixer_cls"])
153 self.assertRaises(refactor.FixerError, self.rt, fixers=["bad_order"])
154
155 def test_refactor_string(self):
156 rt = self.rt()
157 input = "def parrot(): pass\n\n"
158 tree = rt.refactor_string(input, "<test>")
159 self.assertNotEqual(str(tree), input)
160
161 input = "def f(): pass\n\n"
162 tree = rt.refactor_string(input, "<test>")
163 self.assertEqual(str(tree), input)
164
165 def test_refactor_stdin(self):
166
167 class MyRT(refactor.RefactoringTool):
168
Benjamin Peterson3059b002009-07-20 16:42:03 +0000169 def print_output(self, old_text, new_text, filename, equal):
170 results.extend([old_text, new_text, filename, equal])
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000171
Benjamin Peterson3059b002009-07-20 16:42:03 +0000172 results = []
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000173 rt = MyRT(_DEFAULT_FIXERS)
174 save = sys.stdin
175 sys.stdin = io.StringIO("def parrot(): pass\n\n")
176 try:
177 rt.refactor_stdin()
178 finally:
179 sys.stdin = save
Benjamin Peterson3059b002009-07-20 16:42:03 +0000180 expected = ["def parrot(): pass\n\n",
181 "def cheese(): pass\n\n",
182 "<stdin>", False]
183 self.assertEqual(results, expected)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000184
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800185 def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS,
186 options=None, mock_log_debug=None,
187 actually_write=True):
Éric Araujo548c0542011-07-31 17:58:46 +0200188 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
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000195 def read_file():
196 with open(test_file, "rb") as fp:
197 return fp.read()
Éric Araujo548c0542011-07-31 17:58:46 +0200198
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000199 old_contents = read_file()
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800200 rt = self.rt(fixers=fixers, options=options)
201 if mock_log_debug:
202 rt.log_debug = mock_log_debug
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000203
204 rt.refactor_file(test_file)
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000205 self.assertEqual(old_contents, read_file())
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000206
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800207 if not actually_write:
208 return
Éric Araujo548c0542011-07-31 17:58:46 +0200209 rt.refactor_file(test_file, True)
210 new_contents = read_file()
211 self.assertNotEqual(old_contents, new_contents)
Benjamin Peterson20211002009-11-25 18:34:42 +0000212 return new_contents
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000213
214 def test_refactor_file(self):
215 test_file = os.path.join(FIXER_DIR, "parrot_example.py")
216 self.check_file_refactoring(test_file, _DEFAULT_FIXERS)
217
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800218 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:
Victor Stinner3634bfb2012-02-13 23:31:26 +0100233 self.assertRegex(message, message_regex)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800234 break
235 else:
236 self.fail("%r not matched in %r" % (message_regex, debug_messages))
237
Benjamin Peterson3059b002009-07-20 16:42:03 +0000238 def test_refactor_dir(self):
239 def check(structure, expected):
240 def mock_refactor_file(self, f, *args):
241 got.append(f)
242 save_func = refactor.RefactoringTool.refactor_file
243 refactor.RefactoringTool.refactor_file = mock_refactor_file
244 rt = self.rt()
245 got = []
246 dir = tempfile.mkdtemp(prefix="2to3-test_refactor")
247 try:
248 os.mkdir(os.path.join(dir, "a_dir"))
249 for fn in structure:
250 open(os.path.join(dir, fn), "wb").close()
251 rt.refactor_dir(dir)
252 finally:
253 refactor.RefactoringTool.refactor_file = save_func
254 shutil.rmtree(dir)
255 self.assertEqual(got,
256 [os.path.join(dir, path) for path in expected])
257 check([], [])
258 tree = ["nothing",
259 "hi.py",
260 ".dumb",
261 ".after.py",
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000262 "notpy.npy",
Benjamin Peterson3059b002009-07-20 16:42:03 +0000263 "sappy"]
264 expected = ["hi.py"]
265 check(tree, expected)
266 tree = ["hi.py",
Benjamin Petersonc8832652009-07-21 12:51:07 +0000267 os.path.join("a_dir", "stuff.py")]
Benjamin Peterson3059b002009-07-20 16:42:03 +0000268 check(tree, tree)
269
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000270 def test_file_encoding(self):
271 fn = os.path.join(TEST_DATA_DIR, "different_encoding.py")
272 self.check_file_refactoring(fn)
273
Serhiy Storchakadafea852013-09-16 23:51:56 +0300274 def test_false_file_encoding(self):
275 fn = os.path.join(TEST_DATA_DIR, "false_encoding.py")
276 data = self.check_file_refactoring(fn)
277
Benjamin Peterson20211002009-11-25 18:34:42 +0000278 def test_bom(self):
279 fn = os.path.join(TEST_DATA_DIR, "bom.py")
280 data = self.check_file_refactoring(fn)
281 self.assertTrue(data.startswith(codecs.BOM_UTF8))
282
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000283 def test_crlf_newlines(self):
284 old_sep = os.linesep
285 os.linesep = "\r\n"
286 try:
287 fn = os.path.join(TEST_DATA_DIR, "crlf.py")
288 fixes = refactor.get_fixers_from_package("lib2to3.fixes")
289 self.check_file_refactoring(fn, fixes)
290 finally:
291 os.linesep = old_sep
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000292
293 def test_refactor_docstring(self):
294 rt = self.rt()
295
Benjamin Peterson54551092010-02-24 02:28:05 +0000296 doc = """
297>>> example()
29842
299"""
300 out = rt.refactor_docstring(doc, "<test>")
301 self.assertEqual(out, doc)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000302
Benjamin Peterson54551092010-02-24 02:28:05 +0000303 doc = """
304>>> def parrot():
305... return 43
306"""
307 out = rt.refactor_docstring(doc, "<test>")
308 self.assertNotEqual(out, doc)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000309
310 def test_explicit(self):
311 from myfixes.fix_explicit import FixExplicit
312
313 rt = self.rt(fixers=["myfixes.fix_explicit"])
314 self.assertEqual(len(rt.post_order), 0)
315
316 rt = self.rt(explicit=["myfixes.fix_explicit"])
Benjamin Peterson5cff9312008-11-28 23:01:28 +0000317 for fix in rt.post_order:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000318 if isinstance(fix, FixExplicit):
319 break
320 else:
321 self.fail("explicit fixer not loaded")