blob: 88e05fedfbefc2e836cd550435888f8cc0c26d07 [file] [log] [blame]
Thomas Woutersa9773292006-04-21 09:43:23 +00001# Test the runpy module
2import unittest
3import os
4import os.path
5import sys
Nick Coghlan16eb0fb2009-11-18 11:35:25 +00006import re
Thomas Woutersa9773292006-04-21 09:43:23 +00007import tempfile
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008from test.support import verbose, run_unittest, forget
Nick Coghlan260bd3e2009-11-16 06:49:25 +00009from test.script_helper import (temp_dir, make_script, compile_script,
10 make_pkg, make_zip_script, make_zip_pkg)
Christian Heimescbf3b5c2007-12-03 21:02:03 +000011
Nick Coghlan260bd3e2009-11-16 06:49:25 +000012
13from runpy import _run_code, _run_module_code, run_module, run_path
Christian Heimescbf3b5c2007-12-03 21:02:03 +000014# Note: This module can't safely test _run_module_as_main as it
15# runs its tests in the current process, which would mess with the
16# real __main__ module (usually test.regrtest)
17# See test_cmd_line_script for a test that executes that code path
Thomas Woutersa9773292006-04-21 09:43:23 +000018
19# Set up the test code and expected results
20
21class RunModuleCodeTest(unittest.TestCase):
Nick Coghlan260bd3e2009-11-16 06:49:25 +000022 """Unit tests for runpy._run_code and runpy._run_module_code"""
Thomas Woutersa9773292006-04-21 09:43:23 +000023
24 expected_result = ["Top level assignment", "Lower level reference"]
25 test_source = (
26 "# Check basic code execution\n"
27 "result = ['Top level assignment']\n"
28 "def f():\n"
29 " result.append('Lower level reference')\n"
30 "f()\n"
31 "# Check the sys module\n"
32 "import sys\n"
33 "run_argv0 = sys.argv[0]\n"
Guido van Rossum806c2462007-08-06 23:33:07 +000034 "run_name_in_sys_modules = __name__ in sys.modules\n"
35 "if run_name_in_sys_modules:\n"
36 " module_in_sys_modules = globals() is sys.modules[__name__].__dict__\n"
Thomas Woutersa9773292006-04-21 09:43:23 +000037 "# Check nested operation\n"
38 "import runpy\n"
Guido van Rossum806c2462007-08-06 23:33:07 +000039 "nested = runpy._run_module_code('x=1\\n', mod_name='<run>')\n"
Thomas Woutersa9773292006-04-21 09:43:23 +000040 )
41
Thomas Woutersed03b412007-08-28 21:37:11 +000042 def test_run_code(self):
43 saved_argv0 = sys.argv[0]
44 d = _run_code(self.test_source, {})
Nick Coghlan260bd3e2009-11-16 06:49:25 +000045 self.assertEqual(d["result"], self.expected_result)
46 self.assertIs(d["__name__"], None)
47 self.assertIs(d["__file__"], None)
48 self.assertIs(d["__loader__"], None)
49 self.assertIs(d["__package__"], None)
50 self.assertIs(d["run_argv0"], saved_argv0)
51 self.assertNotIn("run_name", d)
52 self.assertIs(sys.argv[0], saved_argv0)
Thomas Woutersa9773292006-04-21 09:43:23 +000053
54 def test_run_module_code(self):
55 initial = object()
56 name = "<Nonsense>"
57 file = "Some other nonsense"
58 loader = "Now you're just being silly"
Christian Heimescbf3b5c2007-12-03 21:02:03 +000059 package = '' # Treat as a top level module
Thomas Woutersa9773292006-04-21 09:43:23 +000060 d1 = dict(initial=initial)
61 saved_argv0 = sys.argv[0]
Thomas Woutersed03b412007-08-28 21:37:11 +000062 d2 = _run_module_code(self.test_source,
63 d1,
64 name,
65 file,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000066 loader,
67 package)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000068 self.assertNotIn("result", d1)
69 self.assertIs(d2["initial"], initial)
Thomas Woutersed03b412007-08-28 21:37:11 +000070 self.assertEqual(d2["result"], self.expected_result)
71 self.assertEqual(d2["nested"]["x"], 1)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000072 self.assertIs(d2["__name__"], name)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000073 self.assertTrue(d2["run_name_in_sys_modules"])
74 self.assertTrue(d2["module_in_sys_modules"])
Nick Coghlan260bd3e2009-11-16 06:49:25 +000075 self.assertIs(d2["__file__"], file)
76 self.assertIs(d2["run_argv0"], file)
77 self.assertIs(d2["__loader__"], loader)
78 self.assertIs(d2["__package__"], package)
79 self.assertIs(sys.argv[0], saved_argv0)
80 self.assertNotIn(name, sys.modules)
Thomas Woutersed03b412007-08-28 21:37:11 +000081
Thomas Woutersa9773292006-04-21 09:43:23 +000082
83class RunModuleTest(unittest.TestCase):
Nick Coghlan260bd3e2009-11-16 06:49:25 +000084 """Unit tests for runpy.run_module"""
Thomas Woutersa9773292006-04-21 09:43:23 +000085
86 def expect_import_error(self, mod_name):
87 try:
88 run_module(mod_name)
89 except ImportError:
90 pass
91 else:
92 self.fail("Expected import error for " + mod_name)
93
94 def test_invalid_names(self):
Guido van Rossum806c2462007-08-06 23:33:07 +000095 # Builtin module
Thomas Woutersa9773292006-04-21 09:43:23 +000096 self.expect_import_error("sys")
Guido van Rossum806c2462007-08-06 23:33:07 +000097 # Non-existent modules
Thomas Woutersa9773292006-04-21 09:43:23 +000098 self.expect_import_error("sys.imp.eric")
99 self.expect_import_error("os.path.half")
100 self.expect_import_error("a.bee")
101 self.expect_import_error(".howard")
102 self.expect_import_error("..eaten")
Guido van Rossum806c2462007-08-06 23:33:07 +0000103 # Package
104 self.expect_import_error("logging")
Thomas Woutersa9773292006-04-21 09:43:23 +0000105
106 def test_library_module(self):
107 run_module("runpy")
108
Guido van Rossum806c2462007-08-06 23:33:07 +0000109 def _add_pkg_dir(self, pkg_dir):
110 os.mkdir(pkg_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000111 pkg_fname = os.path.join(pkg_dir, "__init__.py")
Guido van Rossum806c2462007-08-06 23:33:07 +0000112 pkg_file = open(pkg_fname, "w")
113 pkg_file.close()
114 return pkg_fname
115
Thomas Woutersa9773292006-04-21 09:43:23 +0000116 def _make_pkg(self, source, depth):
117 pkg_name = "__runpy_pkg__"
Skip Montanaro7a98be22007-08-16 14:35:24 +0000118 test_fname = "runpy_test.py"
Thomas Woutersa9773292006-04-21 09:43:23 +0000119 pkg_dir = sub_dir = tempfile.mkdtemp()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000120 if verbose: print(" Package tree in:", sub_dir)
Thomas Woutersa9773292006-04-21 09:43:23 +0000121 sys.path.insert(0, pkg_dir)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000122 if verbose: print(" Updated sys.path:", sys.path[0])
Thomas Woutersa9773292006-04-21 09:43:23 +0000123 for i in range(depth):
124 sub_dir = os.path.join(sub_dir, pkg_name)
Guido van Rossum806c2462007-08-06 23:33:07 +0000125 pkg_fname = self._add_pkg_dir(sub_dir)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000126 if verbose: print(" Next level in:", sub_dir)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000127 if verbose: print(" Created:", pkg_fname)
Thomas Woutersa9773292006-04-21 09:43:23 +0000128 mod_fname = os.path.join(sub_dir, test_fname)
129 mod_file = open(mod_fname, "w")
130 mod_file.write(source)
131 mod_file.close()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000132 if verbose: print(" Created:", mod_fname)
Thomas Woutersa9773292006-04-21 09:43:23 +0000133 mod_name = (pkg_name+".")*depth + "runpy_test"
134 return pkg_dir, mod_fname, mod_name
135
136 def _del_pkg(self, top, depth, mod_name):
Guido van Rossum806c2462007-08-06 23:33:07 +0000137 for entry in list(sys.modules):
138 if entry.startswith("__runpy_pkg__"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000139 del sys.modules[entry]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000140 if verbose: print(" Removed sys.modules entries")
Thomas Woutersa9773292006-04-21 09:43:23 +0000141 del sys.path[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000142 if verbose: print(" Removed sys.path entry")
Thomas Woutersa9773292006-04-21 09:43:23 +0000143 for root, dirs, files in os.walk(top, topdown=False):
144 for name in files:
145 try:
146 os.remove(os.path.join(root, name))
Guido van Rossumb940e112007-01-10 16:19:56 +0000147 except OSError as ex:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000148 if verbose: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000149 for name in dirs:
150 fullname = os.path.join(root, name)
151 try:
152 os.rmdir(fullname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000153 except OSError as ex:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000154 if verbose: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000155 try:
156 os.rmdir(top)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000157 if verbose: print(" Removed package tree")
Guido van Rossumb940e112007-01-10 16:19:56 +0000158 except OSError as ex:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000159 if verbose: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000160
161 def _check_module(self, depth):
162 pkg_dir, mod_fname, mod_name = (
163 self._make_pkg("x=1\n", depth))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000164 forget(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000165 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000166 if verbose: print("Running from source:", mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000167 d1 = run_module(mod_name) # Read from source
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000168 self.assertTrue("x" in d1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000169 self.assertEqual(d1["x"], 1)
Thomas Woutersa9773292006-04-21 09:43:23 +0000170 del d1 # Ensure __loader__ entry doesn't keep file open
171 __import__(mod_name)
172 os.remove(mod_fname)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000173 if verbose: print("Running from compiled:", mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000174 d2 = run_module(mod_name) # Read from bytecode
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000175 self.assertTrue("x" in d2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000176 self.assertEqual(d2["x"], 1)
Thomas Woutersa9773292006-04-21 09:43:23 +0000177 del d2 # Ensure __loader__ entry doesn't keep file open
178 finally:
179 self._del_pkg(pkg_dir, depth, mod_name)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000180 if verbose: print("Module executed successfully")
Thomas Woutersa9773292006-04-21 09:43:23 +0000181
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000182 def _add_relative_modules(self, base_dir, source, depth):
Guido van Rossum806c2462007-08-06 23:33:07 +0000183 if depth <= 1:
184 raise ValueError("Relative module test needs depth > 1")
185 pkg_name = "__runpy_pkg__"
186 module_dir = base_dir
187 for i in range(depth):
188 parent_dir = module_dir
189 module_dir = os.path.join(module_dir, pkg_name)
190 # Add sibling module
Skip Montanaro7a98be22007-08-16 14:35:24 +0000191 sibling_fname = os.path.join(module_dir, "sibling.py")
Guido van Rossum806c2462007-08-06 23:33:07 +0000192 sibling_file = open(sibling_fname, "w")
193 sibling_file.close()
194 if verbose: print(" Added sibling module:", sibling_fname)
195 # Add nephew module
196 uncle_dir = os.path.join(parent_dir, "uncle")
197 self._add_pkg_dir(uncle_dir)
198 if verbose: print(" Added uncle package:", uncle_dir)
199 cousin_dir = os.path.join(uncle_dir, "cousin")
200 self._add_pkg_dir(cousin_dir)
201 if verbose: print(" Added cousin package:", cousin_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000202 nephew_fname = os.path.join(cousin_dir, "nephew.py")
Guido van Rossum806c2462007-08-06 23:33:07 +0000203 nephew_file = open(nephew_fname, "w")
204 nephew_file.close()
205 if verbose: print(" Added nephew module:", nephew_fname)
206
207 def _check_relative_imports(self, depth, run_name=None):
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000208 contents = r"""\
Guido van Rossum806c2462007-08-06 23:33:07 +0000209from __future__ import absolute_import
210from . import sibling
211from ..uncle.cousin import nephew
212"""
213 pkg_dir, mod_fname, mod_name = (
214 self._make_pkg(contents, depth))
215 try:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000216 self._add_relative_modules(pkg_dir, contents, depth)
217 pkg_name = mod_name.rpartition('.')[0]
Guido van Rossum806c2462007-08-06 23:33:07 +0000218 if verbose: print("Running from source:", mod_name)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000219 d1 = run_module(mod_name, run_name=run_name) # Read from source
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000220 self.assertTrue("__package__" in d1)
221 self.assertTrue(d1["__package__"] == pkg_name)
222 self.assertTrue("sibling" in d1)
223 self.assertTrue("nephew" in d1)
Guido van Rossum806c2462007-08-06 23:33:07 +0000224 del d1 # Ensure __loader__ entry doesn't keep file open
225 __import__(mod_name)
226 os.remove(mod_fname)
227 if verbose: print("Running from compiled:", mod_name)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000228 d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000229 self.assertTrue("__package__" in d2)
230 self.assertTrue(d2["__package__"] == pkg_name)
231 self.assertTrue("sibling" in d2)
232 self.assertTrue("nephew" in d2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000233 del d2 # Ensure __loader__ entry doesn't keep file open
234 finally:
235 self._del_pkg(pkg_dir, depth, mod_name)
236 if verbose: print("Module executed successfully")
237
Thomas Woutersa9773292006-04-21 09:43:23 +0000238 def test_run_module(self):
239 for depth in range(4):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000240 if verbose: print("Testing package depth:", depth)
Thomas Woutersa9773292006-04-21 09:43:23 +0000241 self._check_module(depth)
242
Guido van Rossum806c2462007-08-06 23:33:07 +0000243 def test_explicit_relative_import(self):
244 for depth in range(2, 5):
245 if verbose: print("Testing relative imports at depth:", depth)
246 self._check_relative_imports(depth)
247
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000248 def test_main_relative_import(self):
249 for depth in range(2, 5):
250 if verbose: print("Testing main relative imports at depth:", depth)
251 self._check_relative_imports(depth, "__main__")
252
Thomas Woutersa9773292006-04-21 09:43:23 +0000253
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000254class RunPathTest(unittest.TestCase):
255 """Unit tests for runpy.run_path"""
256 # Based on corresponding tests in test_cmd_line_script
257
258 test_source = """\
259# Script may be run with optimisation enabled, so don't rely on assert
260# statements being executed
261def assertEqual(lhs, rhs):
262 if lhs != rhs:
263 raise AssertionError('%r != %r' % (lhs, rhs))
264def assertIs(lhs, rhs):
265 if lhs is not rhs:
266 raise AssertionError('%r is not %r' % (lhs, rhs))
267# Check basic code execution
268result = ['Top level assignment']
269def f():
270 result.append('Lower level reference')
271f()
272assertEqual(result, ['Top level assignment', 'Lower level reference'])
273# Check the sys module
274import sys
275assertIs(globals(), sys.modules[__name__].__dict__)
276argv0 = sys.argv[0]
277"""
278
279 def _make_test_script(self, script_dir, script_basename, source=None):
280 if source is None:
281 source = self.test_source
282 return make_script(script_dir, script_basename, source)
283
284 def _check_script(self, script_name, expected_name, expected_file,
285 expected_argv0, expected_package):
286 result = run_path(script_name)
287 self.assertEqual(result["__name__"], expected_name)
288 self.assertEqual(result["__file__"], expected_file)
289 self.assertIn("argv0", result)
290 self.assertEqual(result["argv0"], expected_argv0)
291 self.assertEqual(result["__package__"], expected_package)
292
293 def _check_import_error(self, script_name, msg):
Nick Coghlan16eb0fb2009-11-18 11:35:25 +0000294 msg = re.escape(msg)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000295 self.assertRaisesRegexp(ImportError, msg, run_path, script_name)
296
297 def test_basic_script(self):
298 with temp_dir() as script_dir:
299 mod_name = 'script'
300 script_name = self._make_test_script(script_dir, mod_name)
301 self._check_script(script_name, "<run_path>", script_name,
302 script_name, None)
303
304 def test_script_compiled(self):
305 with temp_dir() as script_dir:
306 mod_name = 'script'
307 script_name = self._make_test_script(script_dir, mod_name)
308 compiled_name = compile_script(script_name)
309 os.remove(script_name)
310 self._check_script(compiled_name, "<run_path>", compiled_name,
311 compiled_name, None)
312
313 def test_directory(self):
314 with temp_dir() as script_dir:
315 mod_name = '__main__'
316 script_name = self._make_test_script(script_dir, mod_name)
317 self._check_script(script_dir, "<run_path>", script_name,
318 script_dir, '')
319
320 def test_directory_compiled(self):
321 with temp_dir() as script_dir:
322 mod_name = '__main__'
323 script_name = self._make_test_script(script_dir, mod_name)
324 compiled_name = compile_script(script_name)
325 os.remove(script_name)
326 self._check_script(script_dir, "<run_path>", compiled_name,
327 script_dir, '')
328
329 def test_directory_error(self):
330 with temp_dir() as script_dir:
331 mod_name = 'not_main'
332 script_name = self._make_test_script(script_dir, mod_name)
333 msg = "can't find '__main__' module in %r" % script_dir
334 self._check_import_error(script_dir, msg)
335
336 def test_zipfile(self):
337 with temp_dir() as script_dir:
338 mod_name = '__main__'
339 script_name = self._make_test_script(script_dir, mod_name)
340 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
341 self._check_script(zip_name, "<run_path>", fname, zip_name, '')
342
343 def test_zipfile_compiled(self):
344 with temp_dir() as script_dir:
345 mod_name = '__main__'
346 script_name = self._make_test_script(script_dir, mod_name)
347 compiled_name = compile_script(script_name)
348 zip_name, fname = make_zip_script(script_dir, 'test_zip', compiled_name)
349 self._check_script(zip_name, "<run_path>", fname, zip_name, '')
350
351 def test_zipfile_error(self):
352 with temp_dir() as script_dir:
353 mod_name = 'not_main'
354 script_name = self._make_test_script(script_dir, mod_name)
355 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
356 msg = "can't find '__main__' module in %r" % zip_name
357 self._check_import_error(zip_name, msg)
358
359 def test_main_recursion_error(self):
360 with temp_dir() as script_dir, temp_dir() as dummy_dir:
361 mod_name = '__main__'
362 source = ("import runpy\n"
363 "runpy.run_path(%r)\n") % dummy_dir
364 script_name = self._make_test_script(script_dir, mod_name, source)
365 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
366 msg = "recursion depth exceeded"
367 self.assertRaisesRegexp(RuntimeError, msg, run_path, zip_name)
368
369
370
Thomas Woutersa9773292006-04-21 09:43:23 +0000371def test_main():
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000372 run_unittest(RunModuleCodeTest, RunModuleTest, RunPathTest)
Thomas Woutersa9773292006-04-21 09:43:23 +0000373
374if __name__ == "__main__":
375 test_main()