blob: 45c839e87b395c28f20e4069bc336fecebc9e80c [file] [log] [blame]
Nick Coghlane2ebb2d2006-03-15 11:00:26 +00001# Test the runpy module
2import unittest
3import os
4import os.path
5import sys
6import tempfile
Brett Cannondbed7a72007-08-23 14:53:17 +00007from test.test_support import verbose, run_unittest, forget
Nick Coghlan49868cb2009-11-15 07:30:34 +00008from test.script_helper import (temp_dir, make_script, compile_script,
9 make_pkg, make_zip_script, make_zip_pkg)
Nick Coghlanef01d822007-12-03 12:55:17 +000010
Nick Coghlan49868cb2009-11-15 07:30:34 +000011
12from runpy import _run_code, _run_module_code, run_module, run_path
Nick Coghlanef01d822007-12-03 12:55:17 +000013# Note: This module can't safely test _run_module_as_main as it
14# runs its tests in the current process, which would mess with the
15# real __main__ module (usually test.regrtest)
16# See test_cmd_line_script for a test that executes that code path
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000017
18# Set up the test code and expected results
19
20class RunModuleCodeTest(unittest.TestCase):
Nick Coghlan49868cb2009-11-15 07:30:34 +000021 """Unit tests for runpy._run_code and runpy._run_module_code"""
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000022
23 expected_result = ["Top level assignment", "Lower level reference"]
24 test_source = (
25 "# Check basic code execution\n"
26 "result = ['Top level assignment']\n"
27 "def f():\n"
28 " result.append('Lower level reference')\n"
29 "f()\n"
30 "# Check the sys module\n"
31 "import sys\n"
32 "run_argv0 = sys.argv[0]\n"
Nick Coghlan4f82a032007-07-24 13:07:38 +000033 "run_name_in_sys_modules = __name__ in sys.modules\n"
34 "if run_name_in_sys_modules:\n"
35 " module_in_sys_modules = globals() is sys.modules[__name__].__dict__\n"
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000036 "# Check nested operation\n"
37 "import runpy\n"
Nick Coghlan1a42ece2007-08-25 10:50:41 +000038 "nested = runpy._run_module_code('x=1\\n', mod_name='<run>')\n"
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000039 )
40
Nick Coghlan1a42ece2007-08-25 10:50:41 +000041 def test_run_code(self):
42 saved_argv0 = sys.argv[0]
43 d = _run_code(self.test_source, {})
Nick Coghlan49868cb2009-11-15 07:30:34 +000044 self.assertEqual(d["result"], self.expected_result)
45 self.assertIs(d["__name__"], None)
46 self.assertIs(d["__file__"], None)
47 self.assertIs(d["__loader__"], None)
48 self.assertIs(d["__package__"], None)
49 self.assertIs(d["run_argv0"], saved_argv0)
50 self.assertNotIn("run_name", d)
51 self.assertIs(sys.argv[0], saved_argv0)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000052
53 def test_run_module_code(self):
54 initial = object()
Nick Coghlan56829d52006-07-06 12:53:04 +000055 name = "<Nonsense>"
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000056 file = "Some other nonsense"
57 loader = "Now you're just being silly"
Nick Coghlanef01d822007-12-03 12:55:17 +000058 package = '' # Treat as a top level module
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000059 d1 = dict(initial=initial)
60 saved_argv0 = sys.argv[0]
Nick Coghlan3af0e782007-08-25 04:32:07 +000061 d2 = _run_module_code(self.test_source,
62 d1,
63 name,
64 file,
Nick Coghlanef01d822007-12-03 12:55:17 +000065 loader,
66 package)
Nick Coghlan49868cb2009-11-15 07:30:34 +000067 self.assertNotIn("result", d1)
68 self.assertIs(d2["initial"], initial)
69 self.assertEqual(d2["result"], self.expected_result)
70 self.assertEqual(d2["nested"]["x"], 1)
71 self.assertIs(d2["__name__"], name)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000072 self.assertTrue(d2["run_name_in_sys_modules"])
73 self.assertTrue(d2["module_in_sys_modules"])
Nick Coghlan49868cb2009-11-15 07:30:34 +000074 self.assertIs(d2["__file__"], file)
75 self.assertIs(d2["run_argv0"], file)
76 self.assertIs(d2["__loader__"], loader)
77 self.assertIs(d2["__package__"], package)
78 self.assertIs(sys.argv[0], saved_argv0)
79 self.assertNotIn(name, sys.modules)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000080
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000081
82class RunModuleTest(unittest.TestCase):
Nick Coghlan49868cb2009-11-15 07:30:34 +000083 """Unit tests for runpy.run_module"""
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000084
85 def expect_import_error(self, mod_name):
86 try:
87 run_module(mod_name)
88 except ImportError:
89 pass
90 else:
91 self.fail("Expected import error for " + mod_name)
92
93 def test_invalid_names(self):
Nick Coghlanae21fc62007-07-23 13:41:45 +000094 # Builtin module
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000095 self.expect_import_error("sys")
Nick Coghlanae21fc62007-07-23 13:41:45 +000096 # Non-existent modules
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000097 self.expect_import_error("sys.imp.eric")
98 self.expect_import_error("os.path.half")
99 self.expect_import_error("a.bee")
100 self.expect_import_error(".howard")
101 self.expect_import_error("..eaten")
Nick Coghlan2733d882009-11-07 08:13:55 +0000102 # Package without __main__.py
103 self.expect_import_error("multiprocessing")
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000104
105 def test_library_module(self):
106 run_module("runpy")
107
Nick Coghlanf17a2e42007-07-22 10:18:07 +0000108 def _add_pkg_dir(self, pkg_dir):
109 os.mkdir(pkg_dir)
110 pkg_fname = os.path.join(pkg_dir, "__init__"+os.extsep+"py")
111 pkg_file = open(pkg_fname, "w")
112 pkg_file.close()
113 return pkg_fname
114
Nick Coghlan2733d882009-11-07 08:13:55 +0000115 def _make_pkg(self, source, depth, mod_base="runpy_test"):
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000116 pkg_name = "__runpy_pkg__"
Nick Coghlan2733d882009-11-07 08:13:55 +0000117 test_fname = mod_base+os.extsep+"py"
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000118 pkg_dir = sub_dir = tempfile.mkdtemp()
119 if verbose: print " Package tree in:", sub_dir
120 sys.path.insert(0, pkg_dir)
121 if verbose: print " Updated sys.path:", sys.path[0]
122 for i in range(depth):
123 sub_dir = os.path.join(sub_dir, pkg_name)
Nick Coghlanf17a2e42007-07-22 10:18:07 +0000124 pkg_fname = self._add_pkg_dir(sub_dir)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000125 if verbose: print " Next level in:", sub_dir
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000126 if verbose: print " Created:", pkg_fname
127 mod_fname = os.path.join(sub_dir, test_fname)
128 mod_file = open(mod_fname, "w")
129 mod_file.write(source)
130 mod_file.close()
131 if verbose: print " Created:", mod_fname
Nick Coghlan2733d882009-11-07 08:13:55 +0000132 mod_name = (pkg_name+".")*depth + mod_base
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000133 return pkg_dir, mod_fname, mod_name
134
135 def _del_pkg(self, top, depth, mod_name):
Nick Coghlanae21fc62007-07-23 13:41:45 +0000136 for entry in list(sys.modules):
137 if entry.startswith("__runpy_pkg__"):
Nick Coghlan586b83c2006-03-15 13:11:54 +0000138 del sys.modules[entry]
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000139 if verbose: print " Removed sys.modules entries"
140 del sys.path[0]
141 if verbose: print " Removed sys.path entry"
Nick Coghlan5424ad82006-03-15 12:40:38 +0000142 for root, dirs, files in os.walk(top, topdown=False):
143 for name in files:
Nick Coghlan586b83c2006-03-15 13:11:54 +0000144 try:
145 os.remove(os.path.join(root, name))
146 except OSError, ex:
147 if verbose: print ex # Persist with cleaning up
Nick Coghlan5424ad82006-03-15 12:40:38 +0000148 for name in dirs:
Nick Coghlan586b83c2006-03-15 13:11:54 +0000149 fullname = os.path.join(root, name)
150 try:
151 os.rmdir(fullname)
152 except OSError, ex:
153 if verbose: print ex # Persist with cleaning up
154 try:
155 os.rmdir(top)
156 if verbose: print " Removed package tree"
157 except OSError, ex:
158 if verbose: print ex # Persist with cleaning up
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000159
160 def _check_module(self, depth):
161 pkg_dir, mod_fname, mod_name = (
162 self._make_pkg("x=1\n", depth))
Brett Cannondbed7a72007-08-23 14:53:17 +0000163 forget(mod_name)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000164 try:
165 if verbose: print "Running from source:", mod_name
166 d1 = run_module(mod_name) # Read from source
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000167 self.assertTrue("x" in d1)
168 self.assertTrue(d1["x"] == 1)
Nick Coghlan5424ad82006-03-15 12:40:38 +0000169 del d1 # Ensure __loader__ entry doesn't keep file open
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000170 __import__(mod_name)
171 os.remove(mod_fname)
172 if verbose: print "Running from compiled:", mod_name
173 d2 = run_module(mod_name) # Read from bytecode
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000174 self.assertTrue("x" in d2)
175 self.assertTrue(d2["x"] == 1)
Nick Coghlan5424ad82006-03-15 12:40:38 +0000176 del d2 # Ensure __loader__ entry doesn't keep file open
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000177 finally:
178 self._del_pkg(pkg_dir, depth, mod_name)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000179 if verbose: print "Module executed successfully"
180
Nick Coghlan2733d882009-11-07 08:13:55 +0000181 def _check_package(self, depth):
182 pkg_dir, mod_fname, mod_name = (
183 self._make_pkg("x=1\n", depth, "__main__"))
184 pkg_name, _, _ = mod_name.rpartition(".")
185 forget(mod_name)
186 try:
187 if verbose: print "Running from source:", pkg_name
188 d1 = run_module(pkg_name) # Read from source
189 self.assertTrue("x" in d1)
190 self.assertTrue(d1["x"] == 1)
191 del d1 # Ensure __loader__ entry doesn't keep file open
192 __import__(mod_name)
193 os.remove(mod_fname)
194 if verbose: print "Running from compiled:", pkg_name
195 d2 = run_module(pkg_name) # Read from bytecode
196 self.assertTrue("x" in d2)
197 self.assertTrue(d2["x"] == 1)
198 del d2 # Ensure __loader__ entry doesn't keep file open
199 finally:
200 self._del_pkg(pkg_dir, depth, pkg_name)
201 if verbose: print "Package executed successfully"
202
Nick Coghlanef01d822007-12-03 12:55:17 +0000203 def _add_relative_modules(self, base_dir, source, depth):
Nick Coghlanf17a2e42007-07-22 10:18:07 +0000204 if depth <= 1:
205 raise ValueError("Relative module test needs depth > 1")
206 pkg_name = "__runpy_pkg__"
207 module_dir = base_dir
208 for i in range(depth):
209 parent_dir = module_dir
210 module_dir = os.path.join(module_dir, pkg_name)
211 # Add sibling module
212 sibling_fname = os.path.join(module_dir, "sibling"+os.extsep+"py")
213 sibling_file = open(sibling_fname, "w")
214 sibling_file.close()
215 if verbose: print " Added sibling module:", sibling_fname
216 # Add nephew module
217 uncle_dir = os.path.join(parent_dir, "uncle")
218 self._add_pkg_dir(uncle_dir)
219 if verbose: print " Added uncle package:", uncle_dir
220 cousin_dir = os.path.join(uncle_dir, "cousin")
221 self._add_pkg_dir(cousin_dir)
222 if verbose: print " Added cousin package:", cousin_dir
223 nephew_fname = os.path.join(cousin_dir, "nephew"+os.extsep+"py")
224 nephew_file = open(nephew_fname, "w")
225 nephew_file.close()
226 if verbose: print " Added nephew module:", nephew_fname
227
228 def _check_relative_imports(self, depth, run_name=None):
Nick Coghlanef01d822007-12-03 12:55:17 +0000229 contents = r"""\
Nick Coghlanf17a2e42007-07-22 10:18:07 +0000230from __future__ import absolute_import
231from . import sibling
232from ..uncle.cousin import nephew
233"""
234 pkg_dir, mod_fname, mod_name = (
235 self._make_pkg(contents, depth))
236 try:
Nick Coghlanef01d822007-12-03 12:55:17 +0000237 self._add_relative_modules(pkg_dir, contents, depth)
238 pkg_name = mod_name.rpartition('.')[0]
Nick Coghlanf17a2e42007-07-22 10:18:07 +0000239 if verbose: print "Running from source:", mod_name
Nick Coghlanef01d822007-12-03 12:55:17 +0000240 d1 = run_module(mod_name, run_name=run_name) # Read from source
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000241 self.assertTrue("__package__" in d1)
242 self.assertTrue(d1["__package__"] == pkg_name)
243 self.assertTrue("sibling" in d1)
244 self.assertTrue("nephew" in d1)
Nick Coghlanf17a2e42007-07-22 10:18:07 +0000245 del d1 # Ensure __loader__ entry doesn't keep file open
246 __import__(mod_name)
247 os.remove(mod_fname)
248 if verbose: print "Running from compiled:", mod_name
Nick Coghlanef01d822007-12-03 12:55:17 +0000249 d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000250 self.assertTrue("__package__" in d2)
251 self.assertTrue(d2["__package__"] == pkg_name)
252 self.assertTrue("sibling" in d2)
253 self.assertTrue("nephew" in d2)
Nick Coghlanf17a2e42007-07-22 10:18:07 +0000254 del d2 # Ensure __loader__ entry doesn't keep file open
255 finally:
256 self._del_pkg(pkg_dir, depth, mod_name)
257 if verbose: print "Module executed successfully"
258
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000259 def test_run_module(self):
260 for depth in range(4):
261 if verbose: print "Testing package depth:", depth
262 self._check_module(depth)
263
Nick Coghlan2733d882009-11-07 08:13:55 +0000264 def test_run_package(self):
265 for depth in range(1, 4):
266 if verbose: print "Testing package depth:", depth
267 self._check_package(depth)
268
Nick Coghlanf17a2e42007-07-22 10:18:07 +0000269 def test_explicit_relative_import(self):
270 for depth in range(2, 5):
271 if verbose: print "Testing relative imports at depth:", depth
272 self._check_relative_imports(depth)
273
Nick Coghlanef01d822007-12-03 12:55:17 +0000274 def test_main_relative_import(self):
275 for depth in range(2, 5):
276 if verbose: print "Testing main relative imports at depth:", depth
277 self._check_relative_imports(depth, "__main__")
278
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000279
Nick Coghlan49868cb2009-11-15 07:30:34 +0000280class RunPathTest(unittest.TestCase):
281 """Unit tests for runpy.run_path"""
282 # Based on corresponding tests in test_cmd_line_script
283
284 test_source = """\
285# Script may be run with optimisation enabled, so don't rely on assert
286# statements being executed
287def assertEqual(lhs, rhs):
288 if lhs != rhs:
289 raise AssertionError('%r != %r' % (lhs, rhs))
290def assertIs(lhs, rhs):
291 if lhs is not rhs:
292 raise AssertionError('%r is not %r' % (lhs, rhs))
293# Check basic code execution
294result = ['Top level assignment']
295def f():
296 result.append('Lower level reference')
297f()
298assertEqual(result, ['Top level assignment', 'Lower level reference'])
299# Check the sys module
300import sys
301assertIs(globals(), sys.modules[__name__].__dict__)
302argv0 = sys.argv[0]
303"""
304
305 def _make_test_script(self, script_dir, script_basename, source=None):
306 if source is None:
307 source = self.test_source
308 return make_script(script_dir, script_basename, source)
309
310 def _check_script(self, script_name, expected_name, expected_file,
311 expected_argv0, expected_package):
312 result = run_path(script_name)
313 self.assertEqual(result["__name__"], expected_name)
314 self.assertEqual(result["__file__"], expected_file)
315 self.assertIn("argv0", result)
316 self.assertEqual(result["argv0"], expected_argv0)
317 self.assertEqual(result["__package__"], expected_package)
318
319 def _check_import_error(self, script_name, msg):
Nick Coghlan4b953ba2009-11-16 03:57:32 +0000320 # Double backslashes to handle path separators on Windows
321 msg = msg.replace("\\", "\\\\")
Nick Coghlan49868cb2009-11-15 07:30:34 +0000322 self.assertRaisesRegexp(ImportError, msg, run_path, script_name)
323
324 def test_basic_script(self):
325 with temp_dir() as script_dir:
326 mod_name = 'script'
327 script_name = self._make_test_script(script_dir, mod_name)
328 self._check_script(script_name, "<run_path>", script_name,
329 script_name, None)
330
331 def test_script_compiled(self):
332 with temp_dir() as script_dir:
333 mod_name = 'script'
334 script_name = self._make_test_script(script_dir, mod_name)
335 compiled_name = compile_script(script_name)
336 os.remove(script_name)
337 self._check_script(compiled_name, "<run_path>", compiled_name,
338 compiled_name, None)
339
340 def test_directory(self):
341 with temp_dir() as script_dir:
342 mod_name = '__main__'
343 script_name = self._make_test_script(script_dir, mod_name)
344 self._check_script(script_dir, "<run_path>", script_name,
345 script_dir, '')
346
347 def test_directory_compiled(self):
348 with temp_dir() as script_dir:
349 mod_name = '__main__'
350 script_name = self._make_test_script(script_dir, mod_name)
351 compiled_name = compile_script(script_name)
352 os.remove(script_name)
353 self._check_script(script_dir, "<run_path>", compiled_name,
354 script_dir, '')
355
356 def test_directory_error(self):
357 with temp_dir() as script_dir:
358 mod_name = 'not_main'
359 script_name = self._make_test_script(script_dir, mod_name)
360 msg = "can't find '__main__' module in %r" % script_dir
361 self._check_import_error(script_dir, msg)
362
363 def test_zipfile(self):
364 with temp_dir() as script_dir:
365 mod_name = '__main__'
366 script_name = self._make_test_script(script_dir, mod_name)
367 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
368 self._check_script(zip_name, "<run_path>", fname, zip_name, '')
369
370 def test_zipfile_compiled(self):
371 with temp_dir() as script_dir:
372 mod_name = '__main__'
373 script_name = self._make_test_script(script_dir, mod_name)
374 compiled_name = compile_script(script_name)
375 zip_name, fname = make_zip_script(script_dir, 'test_zip', compiled_name)
376 self._check_script(zip_name, "<run_path>", fname, zip_name, '')
377
378 def test_zipfile_error(self):
379 with temp_dir() as script_dir:
380 mod_name = 'not_main'
381 script_name = self._make_test_script(script_dir, mod_name)
382 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
383 msg = "can't find '__main__' module in %r" % zip_name
384 self._check_import_error(zip_name, msg)
385
386 def test_main_recursion_error(self):
387 with temp_dir() as script_dir, temp_dir() as dummy_dir:
388 mod_name = '__main__'
389 source = ("import runpy\n"
390 "runpy.run_path(%r)\n") % dummy_dir
391 script_name = self._make_test_script(script_dir, mod_name, source)
392 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
393 msg = "recursion depth exceeded"
394 self.assertRaisesRegexp(RuntimeError, msg, run_path, zip_name)
395
396
397
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000398def test_main():
Nick Coghlan49868cb2009-11-15 07:30:34 +0000399 run_unittest(RunModuleCodeTest, RunModuleTest, RunPathTest)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000400
401if __name__ == "__main__":
Tim Petersf99b8162006-03-15 18:08:37 +0000402 test_main()