blob: 16e2e120903735b7870d867cc661aff1865a9626 [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
Brett Cannonfd074152012-04-14 14:10:13 -04008import importlib
Barry Warsaw28a691b2010-04-17 00:19:56 +00009import py_compile
Brett Cannon31f59292011-02-21 19:29:56 +000010from test.support import (
Victor Stinnerbf816222011-06-30 23:25:47 +020011 forget, make_legacy_pyc, run_unittest, unload, verbose, no_tracing,
12 create_empty_file)
Barry Warsaw28a691b2010-04-17 00:19:56 +000013from test.script_helper import (
14 make_pkg, make_script, make_zip_pkg, make_zip_script, temp_dir)
Christian Heimescbf3b5c2007-12-03 21:02:03 +000015
Nick Coghlan8ecf5042012-07-15 21:19:18 +100016
Nick Coghlan761bb112012-07-14 23:59:22 +100017import runpy
Nick Coghlan260bd3e2009-11-16 06:49:25 +000018from runpy import _run_code, _run_module_code, run_module, run_path
Christian Heimescbf3b5c2007-12-03 21:02:03 +000019# Note: This module can't safely test _run_module_as_main as it
20# runs its tests in the current process, which would mess with the
21# real __main__ module (usually test.regrtest)
22# See test_cmd_line_script for a test that executes that code path
Thomas Woutersa9773292006-04-21 09:43:23 +000023
Thomas Woutersa9773292006-04-21 09:43:23 +000024
Nick Coghlan761bb112012-07-14 23:59:22 +100025# Set up the test code and expected results
26example_source = """\
27# Check basic code execution
28result = ['Top level assignment']
29def f():
30 result.append('Lower level reference')
31f()
32del f
33# Check the sys module
34import sys
35run_argv0 = sys.argv[0]
36run_name_in_sys_modules = __name__ in sys.modules
37module_in_sys_modules = (run_name_in_sys_modules and
38 globals() is sys.modules[__name__].__dict__)
39# Check nested operation
40import runpy
41nested = runpy._run_module_code('x=1\\n', mod_name='<run>')
42"""
43
44implicit_namespace = {
45 "__name__": None,
46 "__file__": None,
47 "__cached__": None,
48 "__package__": None,
49 "__doc__": None,
50}
51example_namespace = {
52 "sys": sys,
53 "runpy": runpy,
54 "result": ["Top level assignment", "Lower level reference"],
55 "run_argv0": sys.argv[0],
56 "run_name_in_sys_modules": False,
57 "module_in_sys_modules": False,
58 "nested": dict(implicit_namespace,
59 x=1, __name__="<run>", __loader__=None),
60}
61example_namespace.update(implicit_namespace)
62
63class CodeExecutionMixin:
64 # Issue #15230 (run_path not handling run_name correctly) highlighted a
65 # problem with the way arguments were being passed from higher level APIs
66 # down to lower level code. This mixin makes it easier to ensure full
67 # testing occurs at those upper layers as well, not just at the utility
68 # layer
69
70 def assertNamespaceMatches(self, result_ns, expected_ns):
71 """Check two namespaces match.
72
73 Ignores any unspecified interpreter created names
74 """
75 # Impls are permitted to add extra names, so filter them out
76 for k in list(result_ns):
77 if k.startswith("__") and k.endswith("__"):
78 if k not in expected_ns:
79 result_ns.pop(k)
80 if k not in expected_ns["nested"]:
81 result_ns["nested"].pop(k)
82 # Don't use direct dict comparison - the diffs are too hard to debug
83 self.assertEqual(set(result_ns), set(expected_ns))
84 for k in result_ns:
85 actual = (k, result_ns[k])
86 expected = (k, expected_ns[k])
87 self.assertEqual(actual, expected)
88
89 def check_code_execution(self, create_namespace, expected_namespace):
90 """Check that an interface runs the example code correctly
91
92 First argument is a callable accepting the initial globals and
93 using them to create the actual namespace
94 Second argument is the expected result
95 """
96 sentinel = object()
97 expected_ns = expected_namespace.copy()
98 run_name = expected_ns["__name__"]
99 saved_argv0 = sys.argv[0]
100 saved_mod = sys.modules.get(run_name, sentinel)
101 # Check without initial globals
102 result_ns = create_namespace(None)
103 self.assertNamespaceMatches(result_ns, expected_ns)
104 self.assertIs(sys.argv[0], saved_argv0)
105 self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
106 # And then with initial globals
107 initial_ns = {"sentinel": sentinel}
108 expected_ns["sentinel"] = sentinel
109 result_ns = create_namespace(initial_ns)
110 self.assertIsNot(result_ns, initial_ns)
111 self.assertNamespaceMatches(result_ns, expected_ns)
112 self.assertIs(sys.argv[0], saved_argv0)
113 self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
114
115
116class ExecutionLayerTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000117 """Unit tests for runpy._run_code and runpy._run_module_code"""
Thomas Woutersa9773292006-04-21 09:43:23 +0000118
Thomas Woutersed03b412007-08-28 21:37:11 +0000119 def test_run_code(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000120 expected_ns = example_namespace.copy()
121 expected_ns.update({
122 "__loader__": None,
123 })
124 def create_ns(init_globals):
125 return _run_code(example_source, {}, init_globals)
126 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersa9773292006-04-21 09:43:23 +0000127
128 def test_run_module_code(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000129 mod_name = "<Nonsense>"
130 mod_fname = "Some other nonsense"
131 mod_loader = "Now you're just being silly"
132 mod_package = '' # Treat as a top level module
133 expected_ns = example_namespace.copy()
134 expected_ns.update({
135 "__name__": mod_name,
136 "__file__": mod_fname,
137 "__loader__": mod_loader,
138 "__package__": mod_package,
139 "run_argv0": mod_fname,
140 "run_name_in_sys_modules": True,
141 "module_in_sys_modules": True,
142 })
143 def create_ns(init_globals):
144 return _run_module_code(example_source,
145 init_globals,
146 mod_name,
147 mod_fname,
148 mod_loader,
149 mod_package)
150 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersed03b412007-08-28 21:37:11 +0000151
Nick Coghlan8ecf5042012-07-15 21:19:18 +1000152# TODO: Use self.addCleanup to get rid of a lot of try-finally blocks
Nick Coghlan761bb112012-07-14 23:59:22 +1000153class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000154 """Unit tests for runpy.run_module"""
Thomas Woutersa9773292006-04-21 09:43:23 +0000155
156 def expect_import_error(self, mod_name):
157 try:
158 run_module(mod_name)
159 except ImportError:
160 pass
161 else:
162 self.fail("Expected import error for " + mod_name)
163
164 def test_invalid_names(self):
Guido van Rossum806c2462007-08-06 23:33:07 +0000165 # Builtin module
Thomas Woutersa9773292006-04-21 09:43:23 +0000166 self.expect_import_error("sys")
Guido van Rossum806c2462007-08-06 23:33:07 +0000167 # Non-existent modules
Thomas Woutersa9773292006-04-21 09:43:23 +0000168 self.expect_import_error("sys.imp.eric")
169 self.expect_import_error("os.path.half")
170 self.expect_import_error("a.bee")
171 self.expect_import_error(".howard")
172 self.expect_import_error("..eaten")
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000173 # Package without __main__.py
174 self.expect_import_error("multiprocessing")
Thomas Woutersa9773292006-04-21 09:43:23 +0000175
176 def test_library_module(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000177 self.assertEqual(run_module("runpy")["__name__"], "runpy")
Thomas Woutersa9773292006-04-21 09:43:23 +0000178
Guido van Rossum806c2462007-08-06 23:33:07 +0000179 def _add_pkg_dir(self, pkg_dir):
180 os.mkdir(pkg_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000181 pkg_fname = os.path.join(pkg_dir, "__init__.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200182 create_empty_file(pkg_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000183 return pkg_fname
184
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000185 def _make_pkg(self, source, depth, mod_base="runpy_test"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000186 pkg_name = "__runpy_pkg__"
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000187 test_fname = mod_base+os.extsep+"py"
Nick Coghlaneb3e62f2012-07-17 20:42:39 +1000188 pkg_dir = sub_dir = os.path.realpath(tempfile.mkdtemp())
Nick Coghlan761bb112012-07-14 23:59:22 +1000189 if verbose > 1: print(" Package tree in:", sub_dir)
Thomas Woutersa9773292006-04-21 09:43:23 +0000190 sys.path.insert(0, pkg_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000191 if verbose > 1: print(" Updated sys.path:", sys.path[0])
Thomas Woutersa9773292006-04-21 09:43:23 +0000192 for i in range(depth):
193 sub_dir = os.path.join(sub_dir, pkg_name)
Guido van Rossum806c2462007-08-06 23:33:07 +0000194 pkg_fname = self._add_pkg_dir(sub_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000195 if verbose > 1: print(" Next level in:", sub_dir)
196 if verbose > 1: print(" Created:", pkg_fname)
Thomas Woutersa9773292006-04-21 09:43:23 +0000197 mod_fname = os.path.join(sub_dir, test_fname)
198 mod_file = open(mod_fname, "w")
199 mod_file.write(source)
200 mod_file.close()
Nick Coghlan761bb112012-07-14 23:59:22 +1000201 if verbose > 1: print(" Created:", mod_fname)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000202 mod_name = (pkg_name+".")*depth + mod_base
Thomas Woutersa9773292006-04-21 09:43:23 +0000203 return pkg_dir, mod_fname, mod_name
204
205 def _del_pkg(self, top, depth, mod_name):
Guido van Rossum806c2462007-08-06 23:33:07 +0000206 for entry in list(sys.modules):
207 if entry.startswith("__runpy_pkg__"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000208 del sys.modules[entry]
Nick Coghlan761bb112012-07-14 23:59:22 +1000209 if verbose > 1: print(" Removed sys.modules entries")
Thomas Woutersa9773292006-04-21 09:43:23 +0000210 del sys.path[0]
Nick Coghlan761bb112012-07-14 23:59:22 +1000211 if verbose > 1: print(" Removed sys.path entry")
Thomas Woutersa9773292006-04-21 09:43:23 +0000212 for root, dirs, files in os.walk(top, topdown=False):
213 for name in files:
214 try:
215 os.remove(os.path.join(root, name))
Guido van Rossumb940e112007-01-10 16:19:56 +0000216 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000217 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000218 for name in dirs:
219 fullname = os.path.join(root, name)
220 try:
221 os.rmdir(fullname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000222 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000223 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000224 try:
225 os.rmdir(top)
Nick Coghlan761bb112012-07-14 23:59:22 +1000226 if verbose > 1: print(" Removed package tree")
Guido van Rossumb940e112007-01-10 16:19:56 +0000227 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000228 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000229
Nick Coghlan761bb112012-07-14 23:59:22 +1000230 def _fix_ns_for_legacy_pyc(self, ns, alter_sys):
231 char_to_add = "c" if __debug__ else "o"
232 ns["__file__"] += char_to_add
233 if alter_sys:
234 ns["run_argv0"] += char_to_add
235
236
237 def _check_module(self, depth, alter_sys=False):
Thomas Woutersa9773292006-04-21 09:43:23 +0000238 pkg_dir, mod_fname, mod_name = (
Nick Coghlan761bb112012-07-14 23:59:22 +1000239 self._make_pkg(example_source, depth))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000240 forget(mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000241 expected_ns = example_namespace.copy()
242 expected_ns.update({
243 "__name__": mod_name,
244 "__file__": mod_fname,
245 "__package__": mod_name.rpartition(".")[0],
246 })
247 if alter_sys:
248 expected_ns.update({
249 "run_argv0": mod_fname,
250 "run_name_in_sys_modules": True,
251 "module_in_sys_modules": True,
252 })
253 def create_ns(init_globals):
254 return run_module(mod_name, init_globals, alter_sys=alter_sys)
Thomas Woutersa9773292006-04-21 09:43:23 +0000255 try:
Nick Coghlan761bb112012-07-14 23:59:22 +1000256 if verbose > 1: print("Running from source:", mod_name)
257 self.check_code_execution(create_ns, expected_ns)
Brett Cannonfd074152012-04-14 14:10:13 -0400258 importlib.invalidate_caches()
Thomas Woutersa9773292006-04-21 09:43:23 +0000259 __import__(mod_name)
260 os.remove(mod_fname)
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200261 if not sys.dont_write_bytecode:
262 make_legacy_pyc(mod_fname)
263 unload(mod_name) # In case loader caches paths
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200264 importlib.invalidate_caches()
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200265 if verbose > 1: print("Running from compiled:", mod_name)
266 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
267 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersa9773292006-04-21 09:43:23 +0000268 finally:
269 self._del_pkg(pkg_dir, depth, mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000270 if verbose > 1: print("Module executed successfully")
Thomas Woutersa9773292006-04-21 09:43:23 +0000271
Nick Coghlan761bb112012-07-14 23:59:22 +1000272 def _check_package(self, depth, alter_sys=False):
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000273 pkg_dir, mod_fname, mod_name = (
Nick Coghlan761bb112012-07-14 23:59:22 +1000274 self._make_pkg(example_source, depth, "__main__"))
275 pkg_name = mod_name.rpartition(".")[0]
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000276 forget(mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000277 expected_ns = example_namespace.copy()
278 expected_ns.update({
279 "__name__": mod_name,
280 "__file__": mod_fname,
281 "__package__": pkg_name,
282 })
283 if alter_sys:
284 expected_ns.update({
285 "run_argv0": mod_fname,
286 "run_name_in_sys_modules": True,
287 "module_in_sys_modules": True,
288 })
289 def create_ns(init_globals):
290 return run_module(pkg_name, init_globals, alter_sys=alter_sys)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000291 try:
Nick Coghlan761bb112012-07-14 23:59:22 +1000292 if verbose > 1: print("Running from source:", pkg_name)
293 self.check_code_execution(create_ns, expected_ns)
Brett Cannonfd074152012-04-14 14:10:13 -0400294 importlib.invalidate_caches()
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000295 __import__(mod_name)
296 os.remove(mod_fname)
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200297 if not sys.dont_write_bytecode:
298 make_legacy_pyc(mod_fname)
299 unload(mod_name) # In case loader caches paths
300 if verbose > 1: print("Running from compiled:", pkg_name)
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200301 importlib.invalidate_caches()
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200302 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
303 self.check_code_execution(create_ns, expected_ns)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000304 finally:
305 self._del_pkg(pkg_dir, depth, pkg_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000306 if verbose > 1: print("Package executed successfully")
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000307
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000308 def _add_relative_modules(self, base_dir, source, depth):
Guido van Rossum806c2462007-08-06 23:33:07 +0000309 if depth <= 1:
310 raise ValueError("Relative module test needs depth > 1")
311 pkg_name = "__runpy_pkg__"
312 module_dir = base_dir
313 for i in range(depth):
314 parent_dir = module_dir
315 module_dir = os.path.join(module_dir, pkg_name)
316 # Add sibling module
Skip Montanaro7a98be22007-08-16 14:35:24 +0000317 sibling_fname = os.path.join(module_dir, "sibling.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200318 create_empty_file(sibling_fname)
Nick Coghlan761bb112012-07-14 23:59:22 +1000319 if verbose > 1: print(" Added sibling module:", sibling_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000320 # Add nephew module
321 uncle_dir = os.path.join(parent_dir, "uncle")
322 self._add_pkg_dir(uncle_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000323 if verbose > 1: print(" Added uncle package:", uncle_dir)
Guido van Rossum806c2462007-08-06 23:33:07 +0000324 cousin_dir = os.path.join(uncle_dir, "cousin")
325 self._add_pkg_dir(cousin_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000326 if verbose > 1: print(" Added cousin package:", cousin_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000327 nephew_fname = os.path.join(cousin_dir, "nephew.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200328 create_empty_file(nephew_fname)
Nick Coghlan761bb112012-07-14 23:59:22 +1000329 if verbose > 1: print(" Added nephew module:", nephew_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000330
331 def _check_relative_imports(self, depth, run_name=None):
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000332 contents = r"""\
Guido van Rossum806c2462007-08-06 23:33:07 +0000333from __future__ import absolute_import
334from . import sibling
335from ..uncle.cousin import nephew
336"""
337 pkg_dir, mod_fname, mod_name = (
338 self._make_pkg(contents, depth))
Nick Coghlan761bb112012-07-14 23:59:22 +1000339 if run_name is None:
340 expected_name = mod_name
341 else:
342 expected_name = run_name
Guido van Rossum806c2462007-08-06 23:33:07 +0000343 try:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000344 self._add_relative_modules(pkg_dir, contents, depth)
345 pkg_name = mod_name.rpartition('.')[0]
Nick Coghlan761bb112012-07-14 23:59:22 +1000346 if verbose > 1: print("Running from source:", mod_name)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000347 d1 = run_module(mod_name, run_name=run_name) # Read from source
Nick Coghlan761bb112012-07-14 23:59:22 +1000348 self.assertEqual(d1["__name__"], expected_name)
349 self.assertEqual(d1["__package__"], pkg_name)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000350 self.assertIn("sibling", d1)
351 self.assertIn("nephew", d1)
Guido van Rossum806c2462007-08-06 23:33:07 +0000352 del d1 # Ensure __loader__ entry doesn't keep file open
Brett Cannonfd074152012-04-14 14:10:13 -0400353 importlib.invalidate_caches()
Guido van Rossum806c2462007-08-06 23:33:07 +0000354 __import__(mod_name)
355 os.remove(mod_fname)
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200356 if not sys.dont_write_bytecode:
357 make_legacy_pyc(mod_fname)
358 unload(mod_name) # In case the loader caches paths
359 if verbose > 1: print("Running from compiled:", mod_name)
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200360 importlib.invalidate_caches()
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200361 d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
362 self.assertEqual(d2["__name__"], expected_name)
363 self.assertEqual(d2["__package__"], pkg_name)
364 self.assertIn("sibling", d2)
365 self.assertIn("nephew", d2)
366 del d2 # Ensure __loader__ entry doesn't keep file open
Guido van Rossum806c2462007-08-06 23:33:07 +0000367 finally:
368 self._del_pkg(pkg_dir, depth, mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000369 if verbose > 1: print("Module executed successfully")
Guido van Rossum806c2462007-08-06 23:33:07 +0000370
Thomas Woutersa9773292006-04-21 09:43:23 +0000371 def test_run_module(self):
372 for depth in range(4):
Nick Coghlan761bb112012-07-14 23:59:22 +1000373 if verbose > 1: print("Testing package depth:", depth)
Thomas Woutersa9773292006-04-21 09:43:23 +0000374 self._check_module(depth)
375
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000376 def test_run_package(self):
377 for depth in range(1, 4):
Nick Coghlan761bb112012-07-14 23:59:22 +1000378 if verbose > 1: print("Testing package depth:", depth)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000379 self._check_package(depth)
380
Nick Coghlan761bb112012-07-14 23:59:22 +1000381 def test_run_module_alter_sys(self):
382 for depth in range(4):
383 if verbose > 1: print("Testing package depth:", depth)
384 self._check_module(depth, alter_sys=True)
385
386 def test_run_package_alter_sys(self):
387 for depth in range(1, 4):
388 if verbose > 1: print("Testing package depth:", depth)
389 self._check_package(depth, alter_sys=True)
390
Guido van Rossum806c2462007-08-06 23:33:07 +0000391 def test_explicit_relative_import(self):
392 for depth in range(2, 5):
Nick Coghlan761bb112012-07-14 23:59:22 +1000393 if verbose > 1: print("Testing relative imports at depth:", depth)
Guido van Rossum806c2462007-08-06 23:33:07 +0000394 self._check_relative_imports(depth)
395
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000396 def test_main_relative_import(self):
397 for depth in range(2, 5):
Nick Coghlan761bb112012-07-14 23:59:22 +1000398 if verbose > 1: print("Testing main relative imports at depth:", depth)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000399 self._check_relative_imports(depth, "__main__")
400
Nick Coghlan761bb112012-07-14 23:59:22 +1000401 def test_run_name(self):
402 depth = 1
403 run_name = "And now for something completely different"
404 pkg_dir, mod_fname, mod_name = (
405 self._make_pkg(example_source, depth))
406 forget(mod_name)
407 expected_ns = example_namespace.copy()
408 expected_ns.update({
409 "__name__": run_name,
410 "__file__": mod_fname,
411 "__package__": mod_name.rpartition(".")[0],
412 })
413 def create_ns(init_globals):
414 return run_module(mod_name, init_globals, run_name)
415 try:
416 self.check_code_execution(create_ns, expected_ns)
417 finally:
418 self._del_pkg(pkg_dir, depth, mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000419
Nick Coghlan8ecf5042012-07-15 21:19:18 +1000420 def test_pkgutil_walk_packages(self):
421 # This is a dodgy hack to use the test_runpy infrastructure to test
422 # issue #15343. Issue #15348 declares this is indeed a dodgy hack ;)
423 import pkgutil
424 max_depth = 4
425 base_name = "__runpy_pkg__"
426 package_suffixes = ["uncle", "uncle.cousin"]
427 module_suffixes = ["uncle.cousin.nephew", base_name + ".sibling"]
428 expected_packages = set()
429 expected_modules = set()
430 for depth in range(1, max_depth):
431 pkg_name = ".".join([base_name] * depth)
432 expected_packages.add(pkg_name)
433 for name in package_suffixes:
434 expected_packages.add(pkg_name + "." + name)
435 for name in module_suffixes:
436 expected_modules.add(pkg_name + "." + name)
437 pkg_name = ".".join([base_name] * max_depth)
438 expected_packages.add(pkg_name)
439 expected_modules.add(pkg_name + ".runpy_test")
440 pkg_dir, mod_fname, mod_name = (
441 self._make_pkg("", max_depth))
442 self.addCleanup(self._del_pkg, pkg_dir, max_depth, mod_name)
443 for depth in range(2, max_depth+1):
444 self._add_relative_modules(pkg_dir, "", depth)
445 for finder, mod_name, ispkg in pkgutil.walk_packages([pkg_dir]):
446 self.assertIsInstance(finder,
447 importlib.machinery.FileFinder)
448 if ispkg:
449 expected_packages.remove(mod_name)
450 else:
451 expected_modules.remove(mod_name)
452 self.assertEqual(len(expected_packages), 0, expected_packages)
453 self.assertEqual(len(expected_modules), 0, expected_modules)
Nick Coghlan761bb112012-07-14 23:59:22 +1000454
455class RunPathTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000456 """Unit tests for runpy.run_path"""
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000457
458 def _make_test_script(self, script_dir, script_basename, source=None):
459 if source is None:
Nick Coghlan761bb112012-07-14 23:59:22 +1000460 source = example_source
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000461 return make_script(script_dir, script_basename, source)
462
463 def _check_script(self, script_name, expected_name, expected_file,
Nick Coghlan761bb112012-07-14 23:59:22 +1000464 expected_argv0):
465 # First check is without run_name
466 def create_ns(init_globals):
467 return run_path(script_name, init_globals)
468 expected_ns = example_namespace.copy()
469 expected_ns.update({
470 "__name__": expected_name,
471 "__file__": expected_file,
472 "__package__": "",
473 "run_argv0": expected_argv0,
474 "run_name_in_sys_modules": True,
475 "module_in_sys_modules": True,
476 })
477 self.check_code_execution(create_ns, expected_ns)
478 # Second check makes sure run_name works in all cases
479 run_name = "prove.issue15230.is.fixed"
480 def create_ns(init_globals):
481 return run_path(script_name, init_globals, run_name)
482 expected_ns["__name__"] = run_name
483 expected_ns["__package__"] = run_name.rpartition(".")[0]
484 self.check_code_execution(create_ns, expected_ns)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000485
486 def _check_import_error(self, script_name, msg):
Nick Coghlan16eb0fb2009-11-18 11:35:25 +0000487 msg = re.escape(msg)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000488 self.assertRaisesRegex(ImportError, msg, run_path, script_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000489
490 def test_basic_script(self):
491 with temp_dir() as script_dir:
492 mod_name = 'script'
493 script_name = self._make_test_script(script_dir, mod_name)
494 self._check_script(script_name, "<run_path>", script_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000495 script_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000496
497 def test_script_compiled(self):
498 with temp_dir() as script_dir:
499 mod_name = 'script'
500 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000501 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000502 os.remove(script_name)
503 self._check_script(compiled_name, "<run_path>", compiled_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000504 compiled_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000505
506 def test_directory(self):
507 with temp_dir() as script_dir:
508 mod_name = '__main__'
509 script_name = self._make_test_script(script_dir, mod_name)
510 self._check_script(script_dir, "<run_path>", script_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000511 script_dir)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000512
513 def test_directory_compiled(self):
514 with temp_dir() as script_dir:
515 mod_name = '__main__'
516 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000517 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000518 os.remove(script_name)
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200519 if not sys.dont_write_bytecode:
520 legacy_pyc = make_legacy_pyc(script_name)
521 self._check_script(script_dir, "<run_path>", legacy_pyc,
522 script_dir)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000523
524 def test_directory_error(self):
525 with temp_dir() as script_dir:
526 mod_name = 'not_main'
527 script_name = self._make_test_script(script_dir, mod_name)
528 msg = "can't find '__main__' module in %r" % script_dir
529 self._check_import_error(script_dir, msg)
530
531 def test_zipfile(self):
532 with temp_dir() as script_dir:
533 mod_name = '__main__'
534 script_name = self._make_test_script(script_dir, mod_name)
535 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000536 self._check_script(zip_name, "<run_path>", fname, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000537
538 def test_zipfile_compiled(self):
539 with temp_dir() as script_dir:
540 mod_name = '__main__'
541 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000542 compiled_name = py_compile.compile(script_name, doraise=True)
543 zip_name, fname = make_zip_script(script_dir, 'test_zip',
544 compiled_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000545 self._check_script(zip_name, "<run_path>", fname, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000546
547 def test_zipfile_error(self):
548 with temp_dir() as script_dir:
549 mod_name = 'not_main'
550 script_name = self._make_test_script(script_dir, mod_name)
551 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
552 msg = "can't find '__main__' module in %r" % zip_name
553 self._check_import_error(zip_name, msg)
554
Brett Cannon31f59292011-02-21 19:29:56 +0000555 @no_tracing
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000556 def test_main_recursion_error(self):
557 with temp_dir() as script_dir, temp_dir() as dummy_dir:
558 mod_name = '__main__'
559 source = ("import runpy\n"
560 "runpy.run_path(%r)\n") % dummy_dir
561 script_name = self._make_test_script(script_dir, mod_name, source)
562 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
563 msg = "recursion depth exceeded"
Ezio Melottied3a7d22010-12-01 02:32:32 +0000564 self.assertRaisesRegex(RuntimeError, msg, run_path, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000565
Victor Stinner6c471022011-07-04 01:45:39 +0200566 def test_encoding(self):
567 with temp_dir() as script_dir:
568 filename = os.path.join(script_dir, 'script.py')
569 with open(filename, 'w', encoding='latin1') as f:
570 f.write("""
571#coding:latin1
Benjamin Peterson951a9e32012-10-12 11:44:10 -0400572s = "non-ASCII: h\xe9"
Victor Stinner6c471022011-07-04 01:45:39 +0200573""")
574 result = run_path(filename)
Benjamin Peterson951a9e32012-10-12 11:44:10 -0400575 self.assertEqual(result['s'], "non-ASCII: h\xe9")
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000576
577
Thomas Woutersa9773292006-04-21 09:43:23 +0000578if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400579 unittest.main()