blob: f19c4ab7ebe9ca82934f0170083a1edfe533f51e [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,
Eric Snowb523f842013-11-22 09:05:39 -070050# "__spec__": None, # XXX Uncomment.
Nick Coghlan761bb112012-07-14 23:59:22 +100051}
52example_namespace = {
53 "sys": sys,
54 "runpy": runpy,
55 "result": ["Top level assignment", "Lower level reference"],
56 "run_argv0": sys.argv[0],
57 "run_name_in_sys_modules": False,
58 "module_in_sys_modules": False,
59 "nested": dict(implicit_namespace,
Eric Snowb523f842013-11-22 09:05:39 -070060 x=1, __name__="<run>", __loader__=None, __spec__=None),
Nick Coghlan761bb112012-07-14 23:59:22 +100061}
62example_namespace.update(implicit_namespace)
63
64class CodeExecutionMixin:
65 # Issue #15230 (run_path not handling run_name correctly) highlighted a
66 # problem with the way arguments were being passed from higher level APIs
67 # down to lower level code. This mixin makes it easier to ensure full
68 # testing occurs at those upper layers as well, not just at the utility
69 # layer
70
71 def assertNamespaceMatches(self, result_ns, expected_ns):
72 """Check two namespaces match.
73
74 Ignores any unspecified interpreter created names
75 """
76 # Impls are permitted to add extra names, so filter them out
77 for k in list(result_ns):
78 if k.startswith("__") and k.endswith("__"):
79 if k not in expected_ns:
80 result_ns.pop(k)
81 if k not in expected_ns["nested"]:
82 result_ns["nested"].pop(k)
83 # Don't use direct dict comparison - the diffs are too hard to debug
84 self.assertEqual(set(result_ns), set(expected_ns))
85 for k in result_ns:
86 actual = (k, result_ns[k])
87 expected = (k, expected_ns[k])
88 self.assertEqual(actual, expected)
89
90 def check_code_execution(self, create_namespace, expected_namespace):
91 """Check that an interface runs the example code correctly
92
93 First argument is a callable accepting the initial globals and
94 using them to create the actual namespace
95 Second argument is the expected result
96 """
97 sentinel = object()
98 expected_ns = expected_namespace.copy()
99 run_name = expected_ns["__name__"]
100 saved_argv0 = sys.argv[0]
101 saved_mod = sys.modules.get(run_name, sentinel)
102 # Check without initial globals
103 result_ns = create_namespace(None)
104 self.assertNamespaceMatches(result_ns, expected_ns)
105 self.assertIs(sys.argv[0], saved_argv0)
106 self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
107 # And then with initial globals
108 initial_ns = {"sentinel": sentinel}
109 expected_ns["sentinel"] = sentinel
110 result_ns = create_namespace(initial_ns)
111 self.assertIsNot(result_ns, initial_ns)
112 self.assertNamespaceMatches(result_ns, expected_ns)
113 self.assertIs(sys.argv[0], saved_argv0)
114 self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
115
116
117class ExecutionLayerTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000118 """Unit tests for runpy._run_code and runpy._run_module_code"""
Thomas Woutersa9773292006-04-21 09:43:23 +0000119
Thomas Woutersed03b412007-08-28 21:37:11 +0000120 def test_run_code(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000121 expected_ns = example_namespace.copy()
122 expected_ns.update({
123 "__loader__": None,
124 })
125 def create_ns(init_globals):
126 return _run_code(example_source, {}, init_globals)
127 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersa9773292006-04-21 09:43:23 +0000128
129 def test_run_module_code(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000130 mod_name = "<Nonsense>"
131 mod_fname = "Some other nonsense"
132 mod_loader = "Now you're just being silly"
133 mod_package = '' # Treat as a top level module
134 expected_ns = example_namespace.copy()
135 expected_ns.update({
136 "__name__": mod_name,
137 "__file__": mod_fname,
138 "__loader__": mod_loader,
139 "__package__": mod_package,
140 "run_argv0": mod_fname,
141 "run_name_in_sys_modules": True,
142 "module_in_sys_modules": True,
143 })
144 def create_ns(init_globals):
145 return _run_module_code(example_source,
146 init_globals,
147 mod_name,
148 mod_fname,
149 mod_loader,
150 mod_package)
151 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersed03b412007-08-28 21:37:11 +0000152
Nick Coghlan8ecf5042012-07-15 21:19:18 +1000153# TODO: Use self.addCleanup to get rid of a lot of try-finally blocks
Nick Coghlan761bb112012-07-14 23:59:22 +1000154class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000155 """Unit tests for runpy.run_module"""
Thomas Woutersa9773292006-04-21 09:43:23 +0000156
157 def expect_import_error(self, mod_name):
158 try:
159 run_module(mod_name)
160 except ImportError:
161 pass
162 else:
163 self.fail("Expected import error for " + mod_name)
164
165 def test_invalid_names(self):
Guido van Rossum806c2462007-08-06 23:33:07 +0000166 # Builtin module
Thomas Woutersa9773292006-04-21 09:43:23 +0000167 self.expect_import_error("sys")
Guido van Rossum806c2462007-08-06 23:33:07 +0000168 # Non-existent modules
Thomas Woutersa9773292006-04-21 09:43:23 +0000169 self.expect_import_error("sys.imp.eric")
170 self.expect_import_error("os.path.half")
171 self.expect_import_error("a.bee")
172 self.expect_import_error(".howard")
173 self.expect_import_error("..eaten")
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000174 # Package without __main__.py
175 self.expect_import_error("multiprocessing")
Thomas Woutersa9773292006-04-21 09:43:23 +0000176
177 def test_library_module(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000178 self.assertEqual(run_module("runpy")["__name__"], "runpy")
Thomas Woutersa9773292006-04-21 09:43:23 +0000179
Guido van Rossum806c2462007-08-06 23:33:07 +0000180 def _add_pkg_dir(self, pkg_dir):
181 os.mkdir(pkg_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000182 pkg_fname = os.path.join(pkg_dir, "__init__.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200183 create_empty_file(pkg_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000184 return pkg_fname
185
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000186 def _make_pkg(self, source, depth, mod_base="runpy_test"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000187 pkg_name = "__runpy_pkg__"
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000188 test_fname = mod_base+os.extsep+"py"
Nick Coghlaneb3e62f2012-07-17 20:42:39 +1000189 pkg_dir = sub_dir = os.path.realpath(tempfile.mkdtemp())
Nick Coghlan761bb112012-07-14 23:59:22 +1000190 if verbose > 1: print(" Package tree in:", sub_dir)
Thomas Woutersa9773292006-04-21 09:43:23 +0000191 sys.path.insert(0, pkg_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000192 if verbose > 1: print(" Updated sys.path:", sys.path[0])
Thomas Woutersa9773292006-04-21 09:43:23 +0000193 for i in range(depth):
194 sub_dir = os.path.join(sub_dir, pkg_name)
Guido van Rossum806c2462007-08-06 23:33:07 +0000195 pkg_fname = self._add_pkg_dir(sub_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000196 if verbose > 1: print(" Next level in:", sub_dir)
197 if verbose > 1: print(" Created:", pkg_fname)
Thomas Woutersa9773292006-04-21 09:43:23 +0000198 mod_fname = os.path.join(sub_dir, test_fname)
199 mod_file = open(mod_fname, "w")
200 mod_file.write(source)
201 mod_file.close()
Nick Coghlan761bb112012-07-14 23:59:22 +1000202 if verbose > 1: print(" Created:", mod_fname)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000203 mod_name = (pkg_name+".")*depth + mod_base
Thomas Woutersa9773292006-04-21 09:43:23 +0000204 return pkg_dir, mod_fname, mod_name
205
206 def _del_pkg(self, top, depth, mod_name):
Guido van Rossum806c2462007-08-06 23:33:07 +0000207 for entry in list(sys.modules):
208 if entry.startswith("__runpy_pkg__"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000209 del sys.modules[entry]
Nick Coghlan761bb112012-07-14 23:59:22 +1000210 if verbose > 1: print(" Removed sys.modules entries")
Thomas Woutersa9773292006-04-21 09:43:23 +0000211 del sys.path[0]
Nick Coghlan761bb112012-07-14 23:59:22 +1000212 if verbose > 1: print(" Removed sys.path entry")
Thomas Woutersa9773292006-04-21 09:43:23 +0000213 for root, dirs, files in os.walk(top, topdown=False):
214 for name in files:
215 try:
216 os.remove(os.path.join(root, name))
Guido van Rossumb940e112007-01-10 16:19:56 +0000217 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000218 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000219 for name in dirs:
220 fullname = os.path.join(root, name)
221 try:
222 os.rmdir(fullname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000223 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000224 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000225 try:
226 os.rmdir(top)
Nick Coghlan761bb112012-07-14 23:59:22 +1000227 if verbose > 1: print(" Removed package tree")
Guido van Rossumb940e112007-01-10 16:19:56 +0000228 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000229 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000230
Nick Coghlan761bb112012-07-14 23:59:22 +1000231 def _fix_ns_for_legacy_pyc(self, ns, alter_sys):
232 char_to_add = "c" if __debug__ else "o"
233 ns["__file__"] += char_to_add
234 if alter_sys:
235 ns["run_argv0"] += char_to_add
236
237
238 def _check_module(self, depth, alter_sys=False):
Thomas Woutersa9773292006-04-21 09:43:23 +0000239 pkg_dir, mod_fname, mod_name = (
Nick Coghlan761bb112012-07-14 23:59:22 +1000240 self._make_pkg(example_source, depth))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000241 forget(mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000242 expected_ns = example_namespace.copy()
243 expected_ns.update({
244 "__name__": mod_name,
245 "__file__": mod_fname,
246 "__package__": mod_name.rpartition(".")[0],
Eric Snowb523f842013-11-22 09:05:39 -0700247# "__spec__": None, # XXX Needs to be set.
Nick Coghlan761bb112012-07-14 23:59:22 +1000248 })
249 if alter_sys:
250 expected_ns.update({
251 "run_argv0": mod_fname,
252 "run_name_in_sys_modules": True,
253 "module_in_sys_modules": True,
254 })
255 def create_ns(init_globals):
256 return run_module(mod_name, init_globals, alter_sys=alter_sys)
Thomas Woutersa9773292006-04-21 09:43:23 +0000257 try:
Nick Coghlan761bb112012-07-14 23:59:22 +1000258 if verbose > 1: print("Running from source:", mod_name)
259 self.check_code_execution(create_ns, expected_ns)
Brett Cannonfd074152012-04-14 14:10:13 -0400260 importlib.invalidate_caches()
Thomas Woutersa9773292006-04-21 09:43:23 +0000261 __import__(mod_name)
262 os.remove(mod_fname)
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200263 if not sys.dont_write_bytecode:
264 make_legacy_pyc(mod_fname)
265 unload(mod_name) # In case loader caches paths
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200266 importlib.invalidate_caches()
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200267 if verbose > 1: print("Running from compiled:", mod_name)
268 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
269 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersa9773292006-04-21 09:43:23 +0000270 finally:
271 self._del_pkg(pkg_dir, depth, mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000272 if verbose > 1: print("Module executed successfully")
Thomas Woutersa9773292006-04-21 09:43:23 +0000273
Nick Coghlan761bb112012-07-14 23:59:22 +1000274 def _check_package(self, depth, alter_sys=False):
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000275 pkg_dir, mod_fname, mod_name = (
Nick Coghlan761bb112012-07-14 23:59:22 +1000276 self._make_pkg(example_source, depth, "__main__"))
277 pkg_name = mod_name.rpartition(".")[0]
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000278 forget(mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000279 expected_ns = example_namespace.copy()
280 expected_ns.update({
281 "__name__": mod_name,
282 "__file__": mod_fname,
283 "__package__": pkg_name,
Eric Snowb523f842013-11-22 09:05:39 -0700284# "__spec__": None, # XXX Needs to be set.
Nick Coghlan761bb112012-07-14 23:59:22 +1000285 })
286 if alter_sys:
287 expected_ns.update({
288 "run_argv0": mod_fname,
289 "run_name_in_sys_modules": True,
290 "module_in_sys_modules": True,
291 })
292 def create_ns(init_globals):
293 return run_module(pkg_name, init_globals, alter_sys=alter_sys)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000294 try:
Nick Coghlan761bb112012-07-14 23:59:22 +1000295 if verbose > 1: print("Running from source:", pkg_name)
296 self.check_code_execution(create_ns, expected_ns)
Brett Cannonfd074152012-04-14 14:10:13 -0400297 importlib.invalidate_caches()
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000298 __import__(mod_name)
299 os.remove(mod_fname)
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200300 if not sys.dont_write_bytecode:
301 make_legacy_pyc(mod_fname)
302 unload(mod_name) # In case loader caches paths
303 if verbose > 1: print("Running from compiled:", pkg_name)
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200304 importlib.invalidate_caches()
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200305 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
306 self.check_code_execution(create_ns, expected_ns)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000307 finally:
308 self._del_pkg(pkg_dir, depth, pkg_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000309 if verbose > 1: print("Package executed successfully")
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000310
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000311 def _add_relative_modules(self, base_dir, source, depth):
Guido van Rossum806c2462007-08-06 23:33:07 +0000312 if depth <= 1:
313 raise ValueError("Relative module test needs depth > 1")
314 pkg_name = "__runpy_pkg__"
315 module_dir = base_dir
316 for i in range(depth):
317 parent_dir = module_dir
318 module_dir = os.path.join(module_dir, pkg_name)
319 # Add sibling module
Skip Montanaro7a98be22007-08-16 14:35:24 +0000320 sibling_fname = os.path.join(module_dir, "sibling.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200321 create_empty_file(sibling_fname)
Nick Coghlan761bb112012-07-14 23:59:22 +1000322 if verbose > 1: print(" Added sibling module:", sibling_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000323 # Add nephew module
324 uncle_dir = os.path.join(parent_dir, "uncle")
325 self._add_pkg_dir(uncle_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000326 if verbose > 1: print(" Added uncle package:", uncle_dir)
Guido van Rossum806c2462007-08-06 23:33:07 +0000327 cousin_dir = os.path.join(uncle_dir, "cousin")
328 self._add_pkg_dir(cousin_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000329 if verbose > 1: print(" Added cousin package:", cousin_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000330 nephew_fname = os.path.join(cousin_dir, "nephew.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200331 create_empty_file(nephew_fname)
Nick Coghlan761bb112012-07-14 23:59:22 +1000332 if verbose > 1: print(" Added nephew module:", nephew_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000333
334 def _check_relative_imports(self, depth, run_name=None):
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000335 contents = r"""\
Guido van Rossum806c2462007-08-06 23:33:07 +0000336from __future__ import absolute_import
337from . import sibling
338from ..uncle.cousin import nephew
339"""
340 pkg_dir, mod_fname, mod_name = (
341 self._make_pkg(contents, depth))
Nick Coghlan761bb112012-07-14 23:59:22 +1000342 if run_name is None:
343 expected_name = mod_name
344 else:
345 expected_name = run_name
Guido van Rossum806c2462007-08-06 23:33:07 +0000346 try:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000347 self._add_relative_modules(pkg_dir, contents, depth)
348 pkg_name = mod_name.rpartition('.')[0]
Nick Coghlan761bb112012-07-14 23:59:22 +1000349 if verbose > 1: print("Running from source:", mod_name)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000350 d1 = run_module(mod_name, run_name=run_name) # Read from source
Nick Coghlan761bb112012-07-14 23:59:22 +1000351 self.assertEqual(d1["__name__"], expected_name)
352 self.assertEqual(d1["__package__"], pkg_name)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000353 self.assertIn("sibling", d1)
354 self.assertIn("nephew", d1)
Guido van Rossum806c2462007-08-06 23:33:07 +0000355 del d1 # Ensure __loader__ entry doesn't keep file open
Brett Cannonfd074152012-04-14 14:10:13 -0400356 importlib.invalidate_caches()
Guido van Rossum806c2462007-08-06 23:33:07 +0000357 __import__(mod_name)
358 os.remove(mod_fname)
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200359 if not sys.dont_write_bytecode:
360 make_legacy_pyc(mod_fname)
361 unload(mod_name) # In case the loader caches paths
362 if verbose > 1: print("Running from compiled:", mod_name)
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200363 importlib.invalidate_caches()
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200364 d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
365 self.assertEqual(d2["__name__"], expected_name)
366 self.assertEqual(d2["__package__"], pkg_name)
367 self.assertIn("sibling", d2)
368 self.assertIn("nephew", d2)
369 del d2 # Ensure __loader__ entry doesn't keep file open
Guido van Rossum806c2462007-08-06 23:33:07 +0000370 finally:
371 self._del_pkg(pkg_dir, depth, mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000372 if verbose > 1: print("Module executed successfully")
Guido van Rossum806c2462007-08-06 23:33:07 +0000373
Thomas Woutersa9773292006-04-21 09:43:23 +0000374 def test_run_module(self):
375 for depth in range(4):
Nick Coghlan761bb112012-07-14 23:59:22 +1000376 if verbose > 1: print("Testing package depth:", depth)
Thomas Woutersa9773292006-04-21 09:43:23 +0000377 self._check_module(depth)
378
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000379 def test_run_package(self):
380 for depth in range(1, 4):
Nick Coghlan761bb112012-07-14 23:59:22 +1000381 if verbose > 1: print("Testing package depth:", depth)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000382 self._check_package(depth)
383
Nick Coghlan761bb112012-07-14 23:59:22 +1000384 def test_run_module_alter_sys(self):
385 for depth in range(4):
386 if verbose > 1: print("Testing package depth:", depth)
387 self._check_module(depth, alter_sys=True)
388
389 def test_run_package_alter_sys(self):
390 for depth in range(1, 4):
391 if verbose > 1: print("Testing package depth:", depth)
392 self._check_package(depth, alter_sys=True)
393
Guido van Rossum806c2462007-08-06 23:33:07 +0000394 def test_explicit_relative_import(self):
395 for depth in range(2, 5):
Nick Coghlan761bb112012-07-14 23:59:22 +1000396 if verbose > 1: print("Testing relative imports at depth:", depth)
Guido van Rossum806c2462007-08-06 23:33:07 +0000397 self._check_relative_imports(depth)
398
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000399 def test_main_relative_import(self):
400 for depth in range(2, 5):
Nick Coghlan761bb112012-07-14 23:59:22 +1000401 if verbose > 1: print("Testing main relative imports at depth:", depth)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000402 self._check_relative_imports(depth, "__main__")
403
Nick Coghlan761bb112012-07-14 23:59:22 +1000404 def test_run_name(self):
405 depth = 1
406 run_name = "And now for something completely different"
407 pkg_dir, mod_fname, mod_name = (
408 self._make_pkg(example_source, depth))
409 forget(mod_name)
410 expected_ns = example_namespace.copy()
411 expected_ns.update({
412 "__name__": run_name,
413 "__file__": mod_fname,
414 "__package__": mod_name.rpartition(".")[0],
415 })
416 def create_ns(init_globals):
417 return run_module(mod_name, init_globals, run_name)
418 try:
419 self.check_code_execution(create_ns, expected_ns)
420 finally:
421 self._del_pkg(pkg_dir, depth, mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000422
Nick Coghlan8ecf5042012-07-15 21:19:18 +1000423 def test_pkgutil_walk_packages(self):
424 # This is a dodgy hack to use the test_runpy infrastructure to test
425 # issue #15343. Issue #15348 declares this is indeed a dodgy hack ;)
426 import pkgutil
427 max_depth = 4
428 base_name = "__runpy_pkg__"
429 package_suffixes = ["uncle", "uncle.cousin"]
430 module_suffixes = ["uncle.cousin.nephew", base_name + ".sibling"]
431 expected_packages = set()
432 expected_modules = set()
433 for depth in range(1, max_depth):
434 pkg_name = ".".join([base_name] * depth)
435 expected_packages.add(pkg_name)
436 for name in package_suffixes:
437 expected_packages.add(pkg_name + "." + name)
438 for name in module_suffixes:
439 expected_modules.add(pkg_name + "." + name)
440 pkg_name = ".".join([base_name] * max_depth)
441 expected_packages.add(pkg_name)
442 expected_modules.add(pkg_name + ".runpy_test")
443 pkg_dir, mod_fname, mod_name = (
444 self._make_pkg("", max_depth))
445 self.addCleanup(self._del_pkg, pkg_dir, max_depth, mod_name)
446 for depth in range(2, max_depth+1):
447 self._add_relative_modules(pkg_dir, "", depth)
448 for finder, mod_name, ispkg in pkgutil.walk_packages([pkg_dir]):
449 self.assertIsInstance(finder,
450 importlib.machinery.FileFinder)
451 if ispkg:
452 expected_packages.remove(mod_name)
453 else:
454 expected_modules.remove(mod_name)
455 self.assertEqual(len(expected_packages), 0, expected_packages)
456 self.assertEqual(len(expected_modules), 0, expected_modules)
Nick Coghlan761bb112012-07-14 23:59:22 +1000457
458class RunPathTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000459 """Unit tests for runpy.run_path"""
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000460
461 def _make_test_script(self, script_dir, script_basename, source=None):
462 if source is None:
Nick Coghlan761bb112012-07-14 23:59:22 +1000463 source = example_source
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000464 return make_script(script_dir, script_basename, source)
465
466 def _check_script(self, script_name, expected_name, expected_file,
Nick Coghlan761bb112012-07-14 23:59:22 +1000467 expected_argv0):
468 # First check is without run_name
469 def create_ns(init_globals):
470 return run_path(script_name, init_globals)
471 expected_ns = example_namespace.copy()
472 expected_ns.update({
473 "__name__": expected_name,
474 "__file__": expected_file,
475 "__package__": "",
476 "run_argv0": expected_argv0,
477 "run_name_in_sys_modules": True,
478 "module_in_sys_modules": True,
479 })
480 self.check_code_execution(create_ns, expected_ns)
481 # Second check makes sure run_name works in all cases
482 run_name = "prove.issue15230.is.fixed"
483 def create_ns(init_globals):
484 return run_path(script_name, init_globals, run_name)
485 expected_ns["__name__"] = run_name
486 expected_ns["__package__"] = run_name.rpartition(".")[0]
487 self.check_code_execution(create_ns, expected_ns)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000488
489 def _check_import_error(self, script_name, msg):
Nick Coghlan16eb0fb2009-11-18 11:35:25 +0000490 msg = re.escape(msg)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000491 self.assertRaisesRegex(ImportError, msg, run_path, script_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000492
493 def test_basic_script(self):
494 with temp_dir() as script_dir:
495 mod_name = 'script'
496 script_name = self._make_test_script(script_dir, mod_name)
497 self._check_script(script_name, "<run_path>", script_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000498 script_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000499
500 def test_script_compiled(self):
501 with temp_dir() as script_dir:
502 mod_name = 'script'
503 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000504 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000505 os.remove(script_name)
506 self._check_script(compiled_name, "<run_path>", compiled_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000507 compiled_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000508
509 def test_directory(self):
510 with temp_dir() as script_dir:
511 mod_name = '__main__'
512 script_name = self._make_test_script(script_dir, mod_name)
513 self._check_script(script_dir, "<run_path>", script_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000514 script_dir)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000515
516 def test_directory_compiled(self):
517 with temp_dir() as script_dir:
518 mod_name = '__main__'
519 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000520 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000521 os.remove(script_name)
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200522 if not sys.dont_write_bytecode:
523 legacy_pyc = make_legacy_pyc(script_name)
524 self._check_script(script_dir, "<run_path>", legacy_pyc,
525 script_dir)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000526
527 def test_directory_error(self):
528 with temp_dir() as script_dir:
529 mod_name = 'not_main'
530 script_name = self._make_test_script(script_dir, mod_name)
531 msg = "can't find '__main__' module in %r" % script_dir
532 self._check_import_error(script_dir, msg)
533
534 def test_zipfile(self):
535 with temp_dir() as script_dir:
536 mod_name = '__main__'
537 script_name = self._make_test_script(script_dir, mod_name)
538 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000539 self._check_script(zip_name, "<run_path>", fname, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000540
541 def test_zipfile_compiled(self):
542 with temp_dir() as script_dir:
543 mod_name = '__main__'
544 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000545 compiled_name = py_compile.compile(script_name, doraise=True)
546 zip_name, fname = make_zip_script(script_dir, 'test_zip',
547 compiled_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000548 self._check_script(zip_name, "<run_path>", fname, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000549
550 def test_zipfile_error(self):
551 with temp_dir() as script_dir:
552 mod_name = 'not_main'
553 script_name = self._make_test_script(script_dir, mod_name)
554 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
555 msg = "can't find '__main__' module in %r" % zip_name
556 self._check_import_error(zip_name, msg)
557
Brett Cannon31f59292011-02-21 19:29:56 +0000558 @no_tracing
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000559 def test_main_recursion_error(self):
560 with temp_dir() as script_dir, temp_dir() as dummy_dir:
561 mod_name = '__main__'
562 source = ("import runpy\n"
563 "runpy.run_path(%r)\n") % dummy_dir
564 script_name = self._make_test_script(script_dir, mod_name, source)
565 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
566 msg = "recursion depth exceeded"
Ezio Melottied3a7d22010-12-01 02:32:32 +0000567 self.assertRaisesRegex(RuntimeError, msg, run_path, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000568
Victor Stinner6c471022011-07-04 01:45:39 +0200569 def test_encoding(self):
570 with temp_dir() as script_dir:
571 filename = os.path.join(script_dir, 'script.py')
572 with open(filename, 'w', encoding='latin1') as f:
573 f.write("""
574#coding:latin1
Benjamin Peterson951a9e32012-10-12 11:44:10 -0400575s = "non-ASCII: h\xe9"
Victor Stinner6c471022011-07-04 01:45:39 +0200576""")
577 result = run_path(filename)
Benjamin Peterson951a9e32012-10-12 11:44:10 -0400578 self.assertEqual(result['s'], "non-ASCII: h\xe9")
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000579
580
Thomas Woutersa9773292006-04-21 09:43:23 +0000581if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400582 unittest.main()