blob: de44df07baf9bdee888ddddd01b7f818a677417b [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 Coghlan260bd3e2009-11-16 06:49:25 +000016
17from 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
23# Set up the test code and expected results
24
25class RunModuleCodeTest(unittest.TestCase):
Nick Coghlan260bd3e2009-11-16 06:49:25 +000026 """Unit tests for runpy._run_code and runpy._run_module_code"""
Thomas Woutersa9773292006-04-21 09:43:23 +000027
28 expected_result = ["Top level assignment", "Lower level reference"]
29 test_source = (
30 "# Check basic code execution\n"
31 "result = ['Top level assignment']\n"
32 "def f():\n"
33 " result.append('Lower level reference')\n"
34 "f()\n"
35 "# Check the sys module\n"
36 "import sys\n"
37 "run_argv0 = sys.argv[0]\n"
Guido van Rossum806c2462007-08-06 23:33:07 +000038 "run_name_in_sys_modules = __name__ in sys.modules\n"
39 "if run_name_in_sys_modules:\n"
40 " module_in_sys_modules = globals() is sys.modules[__name__].__dict__\n"
Thomas Woutersa9773292006-04-21 09:43:23 +000041 "# Check nested operation\n"
42 "import runpy\n"
Guido van Rossum806c2462007-08-06 23:33:07 +000043 "nested = runpy._run_module_code('x=1\\n', mod_name='<run>')\n"
Thomas Woutersa9773292006-04-21 09:43:23 +000044 )
45
Thomas Woutersed03b412007-08-28 21:37:11 +000046 def test_run_code(self):
47 saved_argv0 = sys.argv[0]
48 d = _run_code(self.test_source, {})
Nick Coghlan260bd3e2009-11-16 06:49:25 +000049 self.assertEqual(d["result"], self.expected_result)
50 self.assertIs(d["__name__"], None)
51 self.assertIs(d["__file__"], None)
Barry Warsaw28a691b2010-04-17 00:19:56 +000052 self.assertIs(d["__cached__"], None)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000053 self.assertIs(d["__loader__"], None)
54 self.assertIs(d["__package__"], None)
55 self.assertIs(d["run_argv0"], saved_argv0)
56 self.assertNotIn("run_name", d)
57 self.assertIs(sys.argv[0], saved_argv0)
Thomas Woutersa9773292006-04-21 09:43:23 +000058
59 def test_run_module_code(self):
60 initial = object()
61 name = "<Nonsense>"
62 file = "Some other nonsense"
63 loader = "Now you're just being silly"
Christian Heimescbf3b5c2007-12-03 21:02:03 +000064 package = '' # Treat as a top level module
Thomas Woutersa9773292006-04-21 09:43:23 +000065 d1 = dict(initial=initial)
66 saved_argv0 = sys.argv[0]
Thomas Woutersed03b412007-08-28 21:37:11 +000067 d2 = _run_module_code(self.test_source,
68 d1,
69 name,
70 file,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000071 loader,
72 package)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000073 self.assertNotIn("result", d1)
74 self.assertIs(d2["initial"], initial)
Thomas Woutersed03b412007-08-28 21:37:11 +000075 self.assertEqual(d2["result"], self.expected_result)
76 self.assertEqual(d2["nested"]["x"], 1)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000077 self.assertIs(d2["__name__"], name)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000078 self.assertTrue(d2["run_name_in_sys_modules"])
79 self.assertTrue(d2["module_in_sys_modules"])
Nick Coghlan260bd3e2009-11-16 06:49:25 +000080 self.assertIs(d2["__file__"], file)
Barry Warsaw28a691b2010-04-17 00:19:56 +000081 self.assertIs(d2["__cached__"], None)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000082 self.assertIs(d2["run_argv0"], file)
83 self.assertIs(d2["__loader__"], loader)
84 self.assertIs(d2["__package__"], package)
85 self.assertIs(sys.argv[0], saved_argv0)
86 self.assertNotIn(name, sys.modules)
Thomas Woutersed03b412007-08-28 21:37:11 +000087
Thomas Woutersa9773292006-04-21 09:43:23 +000088
89class RunModuleTest(unittest.TestCase):
Nick Coghlan260bd3e2009-11-16 06:49:25 +000090 """Unit tests for runpy.run_module"""
Thomas Woutersa9773292006-04-21 09:43:23 +000091
92 def expect_import_error(self, mod_name):
93 try:
94 run_module(mod_name)
95 except ImportError:
96 pass
97 else:
98 self.fail("Expected import error for " + mod_name)
99
100 def test_invalid_names(self):
Guido van Rossum806c2462007-08-06 23:33:07 +0000101 # Builtin module
Thomas Woutersa9773292006-04-21 09:43:23 +0000102 self.expect_import_error("sys")
Guido van Rossum806c2462007-08-06 23:33:07 +0000103 # Non-existent modules
Thomas Woutersa9773292006-04-21 09:43:23 +0000104 self.expect_import_error("sys.imp.eric")
105 self.expect_import_error("os.path.half")
106 self.expect_import_error("a.bee")
107 self.expect_import_error(".howard")
108 self.expect_import_error("..eaten")
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000109 # Package without __main__.py
110 self.expect_import_error("multiprocessing")
Thomas Woutersa9773292006-04-21 09:43:23 +0000111
112 def test_library_module(self):
113 run_module("runpy")
114
Guido van Rossum806c2462007-08-06 23:33:07 +0000115 def _add_pkg_dir(self, pkg_dir):
116 os.mkdir(pkg_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000117 pkg_fname = os.path.join(pkg_dir, "__init__.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200118 create_empty_file(pkg_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000119 return pkg_fname
120
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000121 def _make_pkg(self, source, depth, mod_base="runpy_test"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000122 pkg_name = "__runpy_pkg__"
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000123 test_fname = mod_base+os.extsep+"py"
Thomas Woutersa9773292006-04-21 09:43:23 +0000124 pkg_dir = sub_dir = tempfile.mkdtemp()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000125 if verbose: print(" Package tree in:", sub_dir)
Thomas Woutersa9773292006-04-21 09:43:23 +0000126 sys.path.insert(0, pkg_dir)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000127 if verbose: print(" Updated sys.path:", sys.path[0])
Thomas Woutersa9773292006-04-21 09:43:23 +0000128 for i in range(depth):
129 sub_dir = os.path.join(sub_dir, pkg_name)
Guido van Rossum806c2462007-08-06 23:33:07 +0000130 pkg_fname = self._add_pkg_dir(sub_dir)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000131 if verbose: print(" Next level in:", sub_dir)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000132 if verbose: print(" Created:", pkg_fname)
Thomas Woutersa9773292006-04-21 09:43:23 +0000133 mod_fname = os.path.join(sub_dir, test_fname)
134 mod_file = open(mod_fname, "w")
135 mod_file.write(source)
136 mod_file.close()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000137 if verbose: print(" Created:", mod_fname)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000138 mod_name = (pkg_name+".")*depth + mod_base
Thomas Woutersa9773292006-04-21 09:43:23 +0000139 return pkg_dir, mod_fname, mod_name
140
141 def _del_pkg(self, top, depth, mod_name):
Guido van Rossum806c2462007-08-06 23:33:07 +0000142 for entry in list(sys.modules):
143 if entry.startswith("__runpy_pkg__"):
Thomas Woutersa9773292006-04-21 09:43:23 +0000144 del sys.modules[entry]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000145 if verbose: print(" Removed sys.modules entries")
Thomas Woutersa9773292006-04-21 09:43:23 +0000146 del sys.path[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000147 if verbose: print(" Removed sys.path entry")
Thomas Woutersa9773292006-04-21 09:43:23 +0000148 for root, dirs, files in os.walk(top, topdown=False):
149 for name in files:
150 try:
151 os.remove(os.path.join(root, name))
Guido van Rossumb940e112007-01-10 16:19:56 +0000152 except OSError as ex:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000153 if verbose: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000154 for name in dirs:
155 fullname = os.path.join(root, name)
156 try:
157 os.rmdir(fullname)
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 try:
161 os.rmdir(top)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000162 if verbose: print(" Removed package tree")
Guido van Rossumb940e112007-01-10 16:19:56 +0000163 except OSError as ex:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000164 if verbose: print(ex) # Persist with cleaning up
Thomas Woutersa9773292006-04-21 09:43:23 +0000165
166 def _check_module(self, depth):
167 pkg_dir, mod_fname, mod_name = (
168 self._make_pkg("x=1\n", depth))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000169 forget(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000170 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000171 if verbose: print("Running from source:", mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000172 d1 = run_module(mod_name) # Read from source
Benjamin Peterson577473f2010-01-19 00:09:57 +0000173 self.assertIn("x", d1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000174 self.assertEqual(d1["x"], 1)
Thomas Woutersa9773292006-04-21 09:43:23 +0000175 del d1 # Ensure __loader__ entry doesn't keep file open
Brett Cannonfd074152012-04-14 14:10:13 -0400176 importlib.invalidate_caches()
Thomas Woutersa9773292006-04-21 09:43:23 +0000177 __import__(mod_name)
178 os.remove(mod_fname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000179 make_legacy_pyc(mod_fname)
Brett Cannon61b14252010-07-03 21:48:25 +0000180 unload(mod_name) # In case loader caches paths
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000181 if verbose: print("Running from compiled:", mod_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400182 importlib.invalidate_caches()
Thomas Woutersa9773292006-04-21 09:43:23 +0000183 d2 = run_module(mod_name) # Read from bytecode
Benjamin Peterson577473f2010-01-19 00:09:57 +0000184 self.assertIn("x", d2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000185 self.assertEqual(d2["x"], 1)
Thomas Woutersa9773292006-04-21 09:43:23 +0000186 del d2 # Ensure __loader__ entry doesn't keep file open
187 finally:
188 self._del_pkg(pkg_dir, depth, mod_name)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000189 if verbose: print("Module executed successfully")
Thomas Woutersa9773292006-04-21 09:43:23 +0000190
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000191 def _check_package(self, depth):
192 pkg_dir, mod_fname, mod_name = (
193 self._make_pkg("x=1\n", depth, "__main__"))
194 pkg_name, _, _ = mod_name.rpartition(".")
195 forget(mod_name)
196 try:
197 if verbose: print("Running from source:", pkg_name)
198 d1 = run_module(pkg_name) # Read from source
Benjamin Peterson577473f2010-01-19 00:09:57 +0000199 self.assertIn("x", d1)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000200 self.assertTrue(d1["x"] == 1)
201 del d1 # Ensure __loader__ entry doesn't keep file open
Brett Cannonfd074152012-04-14 14:10:13 -0400202 importlib.invalidate_caches()
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000203 __import__(mod_name)
204 os.remove(mod_fname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000205 make_legacy_pyc(mod_fname)
Brett Cannon61b14252010-07-03 21:48:25 +0000206 unload(mod_name) # In case loader caches paths
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000207 if verbose: print("Running from compiled:", pkg_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400208 importlib.invalidate_caches()
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000209 d2 = run_module(pkg_name) # Read from bytecode
Benjamin Peterson577473f2010-01-19 00:09:57 +0000210 self.assertIn("x", d2)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000211 self.assertTrue(d2["x"] == 1)
212 del d2 # Ensure __loader__ entry doesn't keep file open
213 finally:
214 self._del_pkg(pkg_dir, depth, pkg_name)
215 if verbose: print("Package executed successfully")
216
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000217 def _add_relative_modules(self, base_dir, source, depth):
Guido van Rossum806c2462007-08-06 23:33:07 +0000218 if depth <= 1:
219 raise ValueError("Relative module test needs depth > 1")
220 pkg_name = "__runpy_pkg__"
221 module_dir = base_dir
222 for i in range(depth):
223 parent_dir = module_dir
224 module_dir = os.path.join(module_dir, pkg_name)
225 # Add sibling module
Skip Montanaro7a98be22007-08-16 14:35:24 +0000226 sibling_fname = os.path.join(module_dir, "sibling.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200227 create_empty_file(sibling_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000228 if verbose: print(" Added sibling module:", sibling_fname)
229 # Add nephew module
230 uncle_dir = os.path.join(parent_dir, "uncle")
231 self._add_pkg_dir(uncle_dir)
232 if verbose: print(" Added uncle package:", uncle_dir)
233 cousin_dir = os.path.join(uncle_dir, "cousin")
234 self._add_pkg_dir(cousin_dir)
235 if verbose: print(" Added cousin package:", cousin_dir)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000236 nephew_fname = os.path.join(cousin_dir, "nephew.py")
Victor Stinnerbf816222011-06-30 23:25:47 +0200237 create_empty_file(nephew_fname)
Guido van Rossum806c2462007-08-06 23:33:07 +0000238 if verbose: print(" Added nephew module:", nephew_fname)
239
240 def _check_relative_imports(self, depth, run_name=None):
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000241 contents = r"""\
Guido van Rossum806c2462007-08-06 23:33:07 +0000242from __future__ import absolute_import
243from . import sibling
244from ..uncle.cousin import nephew
245"""
246 pkg_dir, mod_fname, mod_name = (
247 self._make_pkg(contents, depth))
248 try:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000249 self._add_relative_modules(pkg_dir, contents, depth)
250 pkg_name = mod_name.rpartition('.')[0]
Guido van Rossum806c2462007-08-06 23:33:07 +0000251 if verbose: print("Running from source:", mod_name)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000252 d1 = run_module(mod_name, run_name=run_name) # Read from source
Benjamin Peterson577473f2010-01-19 00:09:57 +0000253 self.assertIn("__package__", d1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000254 self.assertTrue(d1["__package__"] == pkg_name)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000255 self.assertIn("sibling", d1)
256 self.assertIn("nephew", d1)
Guido van Rossum806c2462007-08-06 23:33:07 +0000257 del d1 # Ensure __loader__ entry doesn't keep file open
Brett Cannonfd074152012-04-14 14:10:13 -0400258 importlib.invalidate_caches()
Guido van Rossum806c2462007-08-06 23:33:07 +0000259 __import__(mod_name)
260 os.remove(mod_fname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000261 make_legacy_pyc(mod_fname)
Brett Cannon61b14252010-07-03 21:48:25 +0000262 unload(mod_name) # In case the loader caches paths
Guido van Rossum806c2462007-08-06 23:33:07 +0000263 if verbose: print("Running from compiled:", mod_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400264 importlib.invalidate_caches()
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000265 d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
Benjamin Peterson577473f2010-01-19 00:09:57 +0000266 self.assertIn("__package__", d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000267 self.assertTrue(d2["__package__"] == pkg_name)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000268 self.assertIn("sibling", d2)
269 self.assertIn("nephew", d2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000270 del d2 # Ensure __loader__ entry doesn't keep file open
271 finally:
272 self._del_pkg(pkg_dir, depth, mod_name)
273 if verbose: print("Module executed successfully")
274
Thomas Woutersa9773292006-04-21 09:43:23 +0000275 def test_run_module(self):
276 for depth in range(4):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000277 if verbose: print("Testing package depth:", depth)
Thomas Woutersa9773292006-04-21 09:43:23 +0000278 self._check_module(depth)
279
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000280 def test_run_package(self):
281 for depth in range(1, 4):
282 if verbose: print("Testing package depth:", depth)
283 self._check_package(depth)
284
Guido van Rossum806c2462007-08-06 23:33:07 +0000285 def test_explicit_relative_import(self):
286 for depth in range(2, 5):
287 if verbose: print("Testing relative imports at depth:", depth)
288 self._check_relative_imports(depth)
289
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000290 def test_main_relative_import(self):
291 for depth in range(2, 5):
292 if verbose: print("Testing main relative imports at depth:", depth)
293 self._check_relative_imports(depth, "__main__")
294
Thomas Woutersa9773292006-04-21 09:43:23 +0000295
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000296class RunPathTest(unittest.TestCase):
297 """Unit tests for runpy.run_path"""
298 # Based on corresponding tests in test_cmd_line_script
299
300 test_source = """\
301# Script may be run with optimisation enabled, so don't rely on assert
302# statements being executed
303def assertEqual(lhs, rhs):
304 if lhs != rhs:
305 raise AssertionError('%r != %r' % (lhs, rhs))
306def assertIs(lhs, rhs):
307 if lhs is not rhs:
308 raise AssertionError('%r is not %r' % (lhs, rhs))
309# Check basic code execution
310result = ['Top level assignment']
311def f():
312 result.append('Lower level reference')
313f()
314assertEqual(result, ['Top level assignment', 'Lower level reference'])
315# Check the sys module
316import sys
317assertIs(globals(), sys.modules[__name__].__dict__)
318argv0 = sys.argv[0]
319"""
320
321 def _make_test_script(self, script_dir, script_basename, source=None):
322 if source is None:
323 source = self.test_source
324 return make_script(script_dir, script_basename, source)
325
326 def _check_script(self, script_name, expected_name, expected_file,
327 expected_argv0, expected_package):
328 result = run_path(script_name)
329 self.assertEqual(result["__name__"], expected_name)
330 self.assertEqual(result["__file__"], expected_file)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000331 self.assertEqual(result["__cached__"], None)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000332 self.assertIn("argv0", result)
333 self.assertEqual(result["argv0"], expected_argv0)
334 self.assertEqual(result["__package__"], expected_package)
335
336 def _check_import_error(self, script_name, msg):
Nick Coghlan16eb0fb2009-11-18 11:35:25 +0000337 msg = re.escape(msg)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000338 self.assertRaisesRegex(ImportError, msg, run_path, script_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000339
340 def test_basic_script(self):
341 with temp_dir() as script_dir:
342 mod_name = 'script'
343 script_name = self._make_test_script(script_dir, mod_name)
344 self._check_script(script_name, "<run_path>", script_name,
345 script_name, None)
346
347 def test_script_compiled(self):
348 with temp_dir() as script_dir:
349 mod_name = 'script'
350 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000351 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000352 os.remove(script_name)
353 self._check_script(compiled_name, "<run_path>", compiled_name,
354 compiled_name, None)
355
356 def test_directory(self):
357 with temp_dir() as script_dir:
358 mod_name = '__main__'
359 script_name = self._make_test_script(script_dir, mod_name)
360 self._check_script(script_dir, "<run_path>", script_name,
361 script_dir, '')
362
363 def test_directory_compiled(self):
364 with temp_dir() as script_dir:
365 mod_name = '__main__'
366 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000367 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000368 os.remove(script_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000369 legacy_pyc = make_legacy_pyc(script_name)
370 self._check_script(script_dir, "<run_path>", legacy_pyc,
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000371 script_dir, '')
372
373 def test_directory_error(self):
374 with temp_dir() as script_dir:
375 mod_name = 'not_main'
376 script_name = self._make_test_script(script_dir, mod_name)
377 msg = "can't find '__main__' module in %r" % script_dir
378 self._check_import_error(script_dir, msg)
379
380 def test_zipfile(self):
381 with temp_dir() as script_dir:
382 mod_name = '__main__'
383 script_name = self._make_test_script(script_dir, mod_name)
384 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
385 self._check_script(zip_name, "<run_path>", fname, zip_name, '')
386
387 def test_zipfile_compiled(self):
388 with temp_dir() as script_dir:
389 mod_name = '__main__'
390 script_name = self._make_test_script(script_dir, mod_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000391 compiled_name = py_compile.compile(script_name, doraise=True)
392 zip_name, fname = make_zip_script(script_dir, 'test_zip',
393 compiled_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000394 self._check_script(zip_name, "<run_path>", fname, zip_name, '')
395
396 def test_zipfile_error(self):
397 with temp_dir() as script_dir:
398 mod_name = 'not_main'
399 script_name = self._make_test_script(script_dir, mod_name)
400 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
401 msg = "can't find '__main__' module in %r" % zip_name
402 self._check_import_error(zip_name, msg)
403
Brett Cannon31f59292011-02-21 19:29:56 +0000404 @no_tracing
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000405 def test_main_recursion_error(self):
406 with temp_dir() as script_dir, temp_dir() as dummy_dir:
407 mod_name = '__main__'
408 source = ("import runpy\n"
409 "runpy.run_path(%r)\n") % dummy_dir
410 script_name = self._make_test_script(script_dir, mod_name, source)
411 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
412 msg = "recursion depth exceeded"
Ezio Melottied3a7d22010-12-01 02:32:32 +0000413 self.assertRaisesRegex(RuntimeError, msg, run_path, zip_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000414
Victor Stinner6c471022011-07-04 01:45:39 +0200415 def test_encoding(self):
416 with temp_dir() as script_dir:
417 filename = os.path.join(script_dir, 'script.py')
418 with open(filename, 'w', encoding='latin1') as f:
419 f.write("""
420#coding:latin1
421"non-ASCII: h\xe9"
422""")
423 result = run_path(filename)
424 self.assertEqual(result['__doc__'], "non-ASCII: h\xe9")
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000425
426
Thomas Woutersa9773292006-04-21 09:43:23 +0000427def test_main():
Brett Cannon61b14252010-07-03 21:48:25 +0000428 run_unittest(
429 RunModuleCodeTest,
430 RunModuleTest,
431 RunPathTest
432 )
Thomas Woutersa9773292006-04-21 09:43:23 +0000433
434if __name__ == "__main__":
435 test_main()