blob: c39e281d93835cef128ad131a0ca9adbc0bf4c84 [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 Coghlan761bb112012-07-14 23:59:22 +100016import runpy
Nick Coghlan260bd3e2009-11-16 06:49:25 +000017from runpy import _run_code, _run_module_code, run_module, run_path
Christian Heimescbf3b5c2007-12-03 21:02:03 +000018# Note: This module can't safely test _run_module_as_main as it
19# runs its tests in the current process, which would mess with the
20# real __main__ module (usually test.regrtest)
21# See test_cmd_line_script for a test that executes that code path
Thomas Woutersa9773292006-04-21 09:43:23 +000022
Thomas Woutersa9773292006-04-21 09:43:23 +000023
Nick Coghlan761bb112012-07-14 23:59:22 +100024# Set up the test code and expected results
25example_source = """\
26# Check basic code execution
27result = ['Top level assignment']
28def f():
29 result.append('Lower level reference')
30f()
31del f
32# Check the sys module
33import sys
34run_argv0 = sys.argv[0]
35run_name_in_sys_modules = __name__ in sys.modules
36module_in_sys_modules = (run_name_in_sys_modules and
37 globals() is sys.modules[__name__].__dict__)
38# Check nested operation
39import runpy
40nested = runpy._run_module_code('x=1\\n', mod_name='<run>')
41"""
42
43implicit_namespace = {
44 "__name__": None,
45 "__file__": None,
46 "__cached__": None,
47 "__package__": None,
48 "__doc__": None,
49}
50example_namespace = {
51 "sys": sys,
52 "runpy": runpy,
53 "result": ["Top level assignment", "Lower level reference"],
54 "run_argv0": sys.argv[0],
55 "run_name_in_sys_modules": False,
56 "module_in_sys_modules": False,
57 "nested": dict(implicit_namespace,
58 x=1, __name__="<run>", __loader__=None),
59}
60example_namespace.update(implicit_namespace)
61
62class CodeExecutionMixin:
63 # Issue #15230 (run_path not handling run_name correctly) highlighted a
64 # problem with the way arguments were being passed from higher level APIs
65 # down to lower level code. This mixin makes it easier to ensure full
66 # testing occurs at those upper layers as well, not just at the utility
67 # layer
68
69 def assertNamespaceMatches(self, result_ns, expected_ns):
70 """Check two namespaces match.
71
72 Ignores any unspecified interpreter created names
73 """
74 # Impls are permitted to add extra names, so filter them out
75 for k in list(result_ns):
76 if k.startswith("__") and k.endswith("__"):
77 if k not in expected_ns:
78 result_ns.pop(k)
79 if k not in expected_ns["nested"]:
80 result_ns["nested"].pop(k)
81 # Don't use direct dict comparison - the diffs are too hard to debug
82 self.assertEqual(set(result_ns), set(expected_ns))
83 for k in result_ns:
84 actual = (k, result_ns[k])
85 expected = (k, expected_ns[k])
86 self.assertEqual(actual, expected)
87
88 def check_code_execution(self, create_namespace, expected_namespace):
89 """Check that an interface runs the example code correctly
90
91 First argument is a callable accepting the initial globals and
92 using them to create the actual namespace
93 Second argument is the expected result
94 """
95 sentinel = object()
96 expected_ns = expected_namespace.copy()
97 run_name = expected_ns["__name__"]
98 saved_argv0 = sys.argv[0]
99 saved_mod = sys.modules.get(run_name, sentinel)
100 # Check without initial globals
101 result_ns = create_namespace(None)
102 self.assertNamespaceMatches(result_ns, expected_ns)
103 self.assertIs(sys.argv[0], saved_argv0)
104 self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
105 # And then with initial globals
106 initial_ns = {"sentinel": sentinel}
107 expected_ns["sentinel"] = sentinel
108 result_ns = create_namespace(initial_ns)
109 self.assertIsNot(result_ns, initial_ns)
110 self.assertNamespaceMatches(result_ns, expected_ns)
111 self.assertIs(sys.argv[0], saved_argv0)
112 self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
113
114
115class ExecutionLayerTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000116 """Unit tests for runpy._run_code and runpy._run_module_code"""
Thomas Woutersa9773292006-04-21 09:43:23 +0000117
Thomas Woutersed03b412007-08-28 21:37:11 +0000118 def test_run_code(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000119 expected_ns = example_namespace.copy()
120 expected_ns.update({
121 "__loader__": None,
122 })
123 def create_ns(init_globals):
124 return _run_code(example_source, {}, init_globals)
125 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersa9773292006-04-21 09:43:23 +0000126
127 def test_run_module_code(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000128 mod_name = "<Nonsense>"
129 mod_fname = "Some other nonsense"
130 mod_loader = "Now you're just being silly"
131 mod_package = '' # Treat as a top level module
132 expected_ns = example_namespace.copy()
133 expected_ns.update({
134 "__name__": mod_name,
135 "__file__": mod_fname,
136 "__loader__": mod_loader,
137 "__package__": mod_package,
138 "run_argv0": mod_fname,
139 "run_name_in_sys_modules": True,
140 "module_in_sys_modules": True,
141 })
142 def create_ns(init_globals):
143 return _run_module_code(example_source,
144 init_globals,
145 mod_name,
146 mod_fname,
147 mod_loader,
148 mod_package)
149 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersed03b412007-08-28 21:37:11 +0000150
Thomas Woutersa9773292006-04-21 09:43:23 +0000151
Nick Coghlan761bb112012-07-14 23:59:22 +1000152class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000153 """Unit tests for runpy.run_module"""
Thomas Woutersa9773292006-04-21 09:43:23 +0000154
155 def expect_import_error(self, mod_name):
156 try:
157 run_module(mod_name)
158 except ImportError:
159 pass
160 else:
161 self.fail("Expected import error for " + mod_name)
162
163 def test_invalid_names(self):
Guido van Rossum806c2462007-08-06 23:33:07 +0000164 # Builtin module
Thomas Woutersa9773292006-04-21 09:43:23 +0000165 self.expect_import_error("sys")
Guido van Rossum806c2462007-08-06 23:33:07 +0000166 # Non-existent modules
Thomas Woutersa9773292006-04-21 09:43:23 +0000167 self.expect_import_error("sys.imp.eric")
168 self.expect_import_error("os.path.half")
169 self.expect_import_error("a.bee")
170 self.expect_import_error(".howard")
171 self.expect_import_error("..eaten")
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000172 # Package without __main__.py
173 self.expect_import_error("multiprocessing")
Thomas Woutersa9773292006-04-21 09:43:23 +0000174
175 def test_library_module(self):
Nick Coghlan761bb112012-07-14 23:59:22 +1000176 self.assertEqual(run_module("runpy")["__name__"], "runpy")
Thomas Woutersa9773292006-04-21 09:43:23 +0000177
Guido van Rossum806c2462007-08-06 23:33:07 +0000178 def _add_pkg_dir(self, pkg_dir):
179 os.mkdir(pkg_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000180 pkg_fname = os.path.join(pkg_dir, "__init__.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200181 create_empty_file(pkg_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000182 return pkg_fname
183
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000184 def _make_pkg(self, source, depth, mod_base="runpy_test"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000185 pkg_name = "__runpy_pkg__"
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000186 test_fname = mod_base+os.extsep+"py"
Thomas Woutersa9773292006-04-21 09:43:23 +0000187 pkg_dir = sub_dir = tempfile.mkdtemp()
Nick Coghlan761bb112012-07-14 23:59:22 +1000188 if verbose > 1: print(" Package tree in:", sub_dir)
Thomas Woutersa9773292006-04-21 09:43:23 +0000189 sys.path.insert(0, pkg_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000190 if verbose > 1: print(" Updated sys.path:", sys.path[0])
Thomas Woutersa9773292006-04-21 09:43:23 +0000191 for i in range(depth):
192 sub_dir = os.path.join(sub_dir, pkg_name)
Guido van Rossum806c2462007-08-06 23:33:07 +0000193 pkg_fname = self._add_pkg_dir(sub_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000194 if verbose > 1: print(" Next level in:", sub_dir)
195 if verbose > 1: print(" Created:", pkg_fname)
Thomas Woutersa9773292006-04-21 09:43:23 +0000196 mod_fname = os.path.join(sub_dir, test_fname)
197 mod_file = open(mod_fname, "w")
198 mod_file.write(source)
199 mod_file.close()
Nick Coghlan761bb112012-07-14 23:59:22 +1000200 if verbose > 1: print(" Created:", mod_fname)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000201 mod_name = (pkg_name+".")*depth + mod_base
Thomas Woutersa9773292006-04-21 09:43:23 +0000202 return pkg_dir, mod_fname, mod_name
203
204 def _del_pkg(self, top, depth, mod_name):
Guido van Rossum806c2462007-08-06 23:33:07 +0000205 for entry in list(sys.modules):
206 if entry.startswith("__runpy_pkg__"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000207 del sys.modules[entry]
Nick Coghlan761bb112012-07-14 23:59:22 +1000208 if verbose > 1: print(" Removed sys.modules entries")
Thomas Woutersa9773292006-04-21 09:43:23 +0000209 del sys.path[0]
Nick Coghlan761bb112012-07-14 23:59:22 +1000210 if verbose > 1: print(" Removed sys.path entry")
Thomas Woutersa9773292006-04-21 09:43:23 +0000211 for root, dirs, files in os.walk(top, topdown=False):
212 for name in files:
213 try:
214 os.remove(os.path.join(root, name))
Guido van Rossumb940e112007-01-10 16:19:56 +0000215 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000216 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000217 for name in dirs:
218 fullname = os.path.join(root, name)
219 try:
220 os.rmdir(fullname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000221 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000222 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000223 try:
224 os.rmdir(top)
Nick Coghlan761bb112012-07-14 23:59:22 +1000225 if verbose > 1: print(" Removed package tree")
Guido van Rossumb940e112007-01-10 16:19:56 +0000226 except OSError as ex:
Nick Coghlan761bb112012-07-14 23:59:22 +1000227 if verbose > 1: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000228
Nick Coghlan761bb112012-07-14 23:59:22 +1000229 def _fix_ns_for_legacy_pyc(self, ns, alter_sys):
230 char_to_add = "c" if __debug__ else "o"
231 ns["__file__"] += char_to_add
232 if alter_sys:
233 ns["run_argv0"] += char_to_add
234
235
236 def _check_module(self, depth, alter_sys=False):
Thomas Woutersa9773292006-04-21 09:43:23 +0000237 pkg_dir, mod_fname, mod_name = (
Nick Coghlan761bb112012-07-14 23:59:22 +1000238 self._make_pkg(example_source, depth))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000239 forget(mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000240 expected_ns = example_namespace.copy()
241 expected_ns.update({
242 "__name__": mod_name,
243 "__file__": mod_fname,
244 "__package__": mod_name.rpartition(".")[0],
245 })
246 if alter_sys:
247 expected_ns.update({
248 "run_argv0": mod_fname,
249 "run_name_in_sys_modules": True,
250 "module_in_sys_modules": True,
251 })
252 def create_ns(init_globals):
253 return run_module(mod_name, init_globals, alter_sys=alter_sys)
Thomas Woutersa9773292006-04-21 09:43:23 +0000254 try:
Nick Coghlan761bb112012-07-14 23:59:22 +1000255 if verbose > 1: print("Running from source:", mod_name)
256 self.check_code_execution(create_ns, expected_ns)
Brett Cannonfd074152012-04-14 14:10:13 -0400257 importlib.invalidate_caches()
Thomas Woutersa9773292006-04-21 09:43:23 +0000258 __import__(mod_name)
259 os.remove(mod_fname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000260 make_legacy_pyc(mod_fname)
Brett Cannon61b14252010-07-03 21:48:25 +0000261 unload(mod_name) # In case loader caches paths
Brett Cannonfd074152012-04-14 14:10:13 -0400262 importlib.invalidate_caches()
Nick Coghlan761bb112012-07-14 23:59:22 +1000263 if verbose > 1: print("Running from compiled:", mod_name)
264 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
265 self.check_code_execution(create_ns, expected_ns)
Thomas Woutersa9773292006-04-21 09:43:23 +0000266 finally:
267 self._del_pkg(pkg_dir, depth, mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000268 if verbose > 1: print("Module executed successfully")
Thomas Woutersa9773292006-04-21 09:43:23 +0000269
Nick Coghlan761bb112012-07-14 23:59:22 +1000270 def _check_package(self, depth, alter_sys=False):
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000271 pkg_dir, mod_fname, mod_name = (
Nick Coghlan761bb112012-07-14 23:59:22 +1000272 self._make_pkg(example_source, depth, "__main__"))
273 pkg_name = mod_name.rpartition(".")[0]
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000274 forget(mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000275 expected_ns = example_namespace.copy()
276 expected_ns.update({
277 "__name__": mod_name,
278 "__file__": mod_fname,
279 "__package__": pkg_name,
280 })
281 if alter_sys:
282 expected_ns.update({
283 "run_argv0": mod_fname,
284 "run_name_in_sys_modules": True,
285 "module_in_sys_modules": True,
286 })
287 def create_ns(init_globals):
288 return run_module(pkg_name, init_globals, alter_sys=alter_sys)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000289 try:
Nick Coghlan761bb112012-07-14 23:59:22 +1000290 if verbose > 1: print("Running from source:", pkg_name)
291 self.check_code_execution(create_ns, expected_ns)
Brett Cannonfd074152012-04-14 14:10:13 -0400292 importlib.invalidate_caches()
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000293 __import__(mod_name)
294 os.remove(mod_fname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000295 make_legacy_pyc(mod_fname)
Brett Cannon61b14252010-07-03 21:48:25 +0000296 unload(mod_name) # In case loader caches paths
Nick Coghlan761bb112012-07-14 23:59:22 +1000297 if verbose > 1: print("Running from compiled:", pkg_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400298 importlib.invalidate_caches()
Nick Coghlan761bb112012-07-14 23:59:22 +1000299 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
300 self.check_code_execution(create_ns, expected_ns)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000301 finally:
302 self._del_pkg(pkg_dir, depth, pkg_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000303 if verbose > 1: print("Package executed successfully")
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000304
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000305 def _add_relative_modules(self, base_dir, source, depth):
Guido van Rossum806c2462007-08-06 23:33:07 +0000306 if depth <= 1:
307 raise ValueError("Relative module test needs depth > 1")
308 pkg_name = "__runpy_pkg__"
309 module_dir = base_dir
310 for i in range(depth):
311 parent_dir = module_dir
312 module_dir = os.path.join(module_dir, pkg_name)
313 # Add sibling module
Skip Montanaro7a98be22007-08-16 14:35:24 +0000314 sibling_fname = os.path.join(module_dir, "sibling.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200315 create_empty_file(sibling_fname)
Nick Coghlan761bb112012-07-14 23:59:22 +1000316 if verbose > 1: print(" Added sibling module:", sibling_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000317 # Add nephew module
318 uncle_dir = os.path.join(parent_dir, "uncle")
319 self._add_pkg_dir(uncle_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000320 if verbose > 1: print(" Added uncle package:", uncle_dir)
Guido van Rossum806c2462007-08-06 23:33:07 +0000321 cousin_dir = os.path.join(uncle_dir, "cousin")
322 self._add_pkg_dir(cousin_dir)
Nick Coghlan761bb112012-07-14 23:59:22 +1000323 if verbose > 1: print(" Added cousin package:", cousin_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000324 nephew_fname = os.path.join(cousin_dir, "nephew.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200325 create_empty_file(nephew_fname)
Nick Coghlan761bb112012-07-14 23:59:22 +1000326 if verbose > 1: print(" Added nephew module:", nephew_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000327
328 def _check_relative_imports(self, depth, run_name=None):
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000329 contents = r"""\
Guido van Rossum806c2462007-08-06 23:33:07 +0000330from __future__ import absolute_import
331from . import sibling
332from ..uncle.cousin import nephew
333"""
334 pkg_dir, mod_fname, mod_name = (
335 self._make_pkg(contents, depth))
Nick Coghlan761bb112012-07-14 23:59:22 +1000336 if run_name is None:
337 expected_name = mod_name
338 else:
339 expected_name = run_name
Guido van Rossum806c2462007-08-06 23:33:07 +0000340 try:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000341 self._add_relative_modules(pkg_dir, contents, depth)
342 pkg_name = mod_name.rpartition('.')[0]
Nick Coghlan761bb112012-07-14 23:59:22 +1000343 if verbose > 1: print("Running from source:", mod_name)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000344 d1 = run_module(mod_name, run_name=run_name) # Read from source
Nick Coghlan761bb112012-07-14 23:59:22 +1000345 self.assertEqual(d1["__name__"], expected_name)
346 self.assertEqual(d1["__package__"], pkg_name)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000347 self.assertIn("sibling", d1)
348 self.assertIn("nephew", d1)
Guido van Rossum806c2462007-08-06 23:33:07 +0000349 del d1 # Ensure __loader__ entry doesn't keep file open
Brett Cannonfd074152012-04-14 14:10:13 -0400350 importlib.invalidate_caches()
Guido van Rossum806c2462007-08-06 23:33:07 +0000351 __import__(mod_name)
352 os.remove(mod_fname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000353 make_legacy_pyc(mod_fname)
Brett Cannon61b14252010-07-03 21:48:25 +0000354 unload(mod_name) # In case the loader caches paths
Nick Coghlan761bb112012-07-14 23:59:22 +1000355 if verbose > 1: print("Running from compiled:", mod_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400356 importlib.invalidate_caches()
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000357 d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
Nick Coghlan761bb112012-07-14 23:59:22 +1000358 self.assertEqual(d2["__name__"], expected_name)
359 self.assertEqual(d2["__package__"], pkg_name)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000360 self.assertIn("sibling", d2)
361 self.assertIn("nephew", d2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000362 del d2 # Ensure __loader__ entry doesn't keep file open
363 finally:
364 self._del_pkg(pkg_dir, depth, mod_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000365 if verbose > 1: print("Module executed successfully")
Guido van Rossum806c2462007-08-06 23:33:07 +0000366
Thomas Woutersa9773292006-04-21 09:43:23 +0000367 def test_run_module(self):
368 for depth in range(4):
Nick Coghlan761bb112012-07-14 23:59:22 +1000369 if verbose > 1: print("Testing package depth:", depth)
Thomas Woutersa9773292006-04-21 09:43:23 +0000370 self._check_module(depth)
371
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000372 def test_run_package(self):
373 for depth in range(1, 4):
Nick Coghlan761bb112012-07-14 23:59:22 +1000374 if verbose > 1: print("Testing package depth:", depth)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000375 self._check_package(depth)
376
Nick Coghlan761bb112012-07-14 23:59:22 +1000377 def test_run_module_alter_sys(self):
378 for depth in range(4):
379 if verbose > 1: print("Testing package depth:", depth)
380 self._check_module(depth, alter_sys=True)
381
382 def test_run_package_alter_sys(self):
383 for depth in range(1, 4):
384 if verbose > 1: print("Testing package depth:", depth)
385 self._check_package(depth, alter_sys=True)
386
Guido van Rossum806c2462007-08-06 23:33:07 +0000387 def test_explicit_relative_import(self):
388 for depth in range(2, 5):
Nick Coghlan761bb112012-07-14 23:59:22 +1000389 if verbose > 1: print("Testing relative imports at depth:", depth)
Guido van Rossum806c2462007-08-06 23:33:07 +0000390 self._check_relative_imports(depth)
391
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000392 def test_main_relative_import(self):
393 for depth in range(2, 5):
Nick Coghlan761bb112012-07-14 23:59:22 +1000394 if verbose > 1: print("Testing main relative imports at depth:", depth)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000395 self._check_relative_imports(depth, "__main__")
396
Nick Coghlan761bb112012-07-14 23:59:22 +1000397 def test_run_name(self):
398 depth = 1
399 run_name = "And now for something completely different"
400 pkg_dir, mod_fname, mod_name = (
401 self._make_pkg(example_source, depth))
402 forget(mod_name)
403 expected_ns = example_namespace.copy()
404 expected_ns.update({
405 "__name__": run_name,
406 "__file__": mod_fname,
407 "__package__": mod_name.rpartition(".")[0],
408 })
409 def create_ns(init_globals):
410 return run_module(mod_name, init_globals, run_name)
411 try:
412 self.check_code_execution(create_ns, expected_ns)
413 finally:
414 self._del_pkg(pkg_dir, depth, mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000415
Nick Coghlan761bb112012-07-14 23:59:22 +1000416
417class RunPathTestCase(unittest.TestCase, CodeExecutionMixin):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000418 """Unit tests for runpy.run_path"""
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000419
420 def _make_test_script(self, script_dir, script_basename, source=None):
421 if source is None:
Nick Coghlan761bb112012-07-14 23:59:22 +1000422 source = example_source
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000423 return make_script(script_dir, script_basename, source)
424
425 def _check_script(self, script_name, expected_name, expected_file,
Nick Coghlan761bb112012-07-14 23:59:22 +1000426 expected_argv0):
427 # First check is without run_name
428 def create_ns(init_globals):
429 return run_path(script_name, init_globals)
430 expected_ns = example_namespace.copy()
431 expected_ns.update({
432 "__name__": expected_name,
433 "__file__": expected_file,
434 "__package__": "",
435 "run_argv0": expected_argv0,
436 "run_name_in_sys_modules": True,
437 "module_in_sys_modules": True,
438 })
439 self.check_code_execution(create_ns, expected_ns)
440 # Second check makes sure run_name works in all cases
441 run_name = "prove.issue15230.is.fixed"
442 def create_ns(init_globals):
443 return run_path(script_name, init_globals, run_name)
444 expected_ns["__name__"] = run_name
445 expected_ns["__package__"] = run_name.rpartition(".")[0]
446 self.check_code_execution(create_ns, expected_ns)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000447
448 def _check_import_error(self, script_name, msg):
Nick Coghlan16eb0fb2009-11-18 11:35:25 +0000449 msg = re.escape(msg)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000450 self.assertRaisesRegex(ImportError, msg, run_path, script_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000451
452 def test_basic_script(self):
453 with temp_dir() as script_dir:
454 mod_name = 'script'
455 script_name = self._make_test_script(script_dir, mod_name)
456 self._check_script(script_name, "<run_path>", script_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000457 script_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000458
459 def test_script_compiled(self):
460 with temp_dir() as script_dir:
461 mod_name = 'script'
462 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000463 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000464 os.remove(script_name)
465 self._check_script(compiled_name, "<run_path>", compiled_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000466 compiled_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000467
468 def test_directory(self):
469 with temp_dir() as script_dir:
470 mod_name = '__main__'
471 script_name = self._make_test_script(script_dir, mod_name)
472 self._check_script(script_dir, "<run_path>", script_name,
Nick Coghlan761bb112012-07-14 23:59:22 +1000473 script_dir)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000474
475 def test_directory_compiled(self):
476 with temp_dir() as script_dir:
477 mod_name = '__main__'
478 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000479 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000480 os.remove(script_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000481 legacy_pyc = make_legacy_pyc(script_name)
482 self._check_script(script_dir, "<run_path>", legacy_pyc,
Nick Coghlan761bb112012-07-14 23:59:22 +1000483 script_dir)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000484
485 def test_directory_error(self):
486 with temp_dir() as script_dir:
487 mod_name = 'not_main'
488 script_name = self._make_test_script(script_dir, mod_name)
489 msg = "can't find '__main__' module in %r" % script_dir
490 self._check_import_error(script_dir, msg)
491
492 def test_zipfile(self):
493 with temp_dir() as script_dir:
494 mod_name = '__main__'
495 script_name = self._make_test_script(script_dir, mod_name)
496 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000497 self._check_script(zip_name, "<run_path>", fname, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000498
499 def test_zipfile_compiled(self):
500 with temp_dir() as script_dir:
501 mod_name = '__main__'
502 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000503 compiled_name = py_compile.compile(script_name, doraise=True)
504 zip_name, fname = make_zip_script(script_dir, 'test_zip',
505 compiled_name)
Nick Coghlan761bb112012-07-14 23:59:22 +1000506 self._check_script(zip_name, "<run_path>", fname, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000507
508 def test_zipfile_error(self):
509 with temp_dir() as script_dir:
510 mod_name = 'not_main'
511 script_name = self._make_test_script(script_dir, mod_name)
512 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
513 msg = "can't find '__main__' module in %r" % zip_name
514 self._check_import_error(zip_name, msg)
515
Brett Cannon31f59292011-02-21 19:29:56 +0000516 @no_tracing
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000517 def test_main_recursion_error(self):
518 with temp_dir() as script_dir, temp_dir() as dummy_dir:
519 mod_name = '__main__'
520 source = ("import runpy\n"
521 "runpy.run_path(%r)\n") % dummy_dir
522 script_name = self._make_test_script(script_dir, mod_name, source)
523 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
524 msg = "recursion depth exceeded"
Ezio Melottied3a7d22010-12-01 02:32:32 +0000525 self.assertRaisesRegex(RuntimeError, msg, run_path, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000526
Victor Stinner6c471022011-07-04 01:45:39 +0200527 def test_encoding(self):
528 with temp_dir() as script_dir:
529 filename = os.path.join(script_dir, 'script.py')
530 with open(filename, 'w', encoding='latin1') as f:
531 f.write("""
532#coding:latin1
533"non-ASCII: h\xe9"
534""")
535 result = run_path(filename)
536 self.assertEqual(result['__doc__'], "non-ASCII: h\xe9")
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000537
538
Thomas Woutersa9773292006-04-21 09:43:23 +0000539def test_main():
Brett Cannon61b14252010-07-03 21:48:25 +0000540 run_unittest(
Nick Coghlan761bb112012-07-14 23:59:22 +1000541 ExecutionLayerTestCase,
542 RunModuleTestCase,
543 RunPathTestCase
Brett Cannon61b14252010-07-03 21:48:25 +0000544 )
Thomas Woutersa9773292006-04-21 09:43:23 +0000545
546if __name__ == "__main__":
547 test_main()