blob: 81ddf45330781b8c59c891b32ecfb092c806ab82 [file] [log] [blame]
Nick Coghlanbe7e49f2012-07-20 23:40:09 +10001# We import importlib *ASAP* in order to test #15386
2import importlib
Collin Winter6498cff2010-03-17 03:14:31 +00003import builtins
Christian Heimes13a7a212008-01-07 17:13:09 +00004import imp
Brett Cannon86ae9812012-07-20 15:40:57 -04005from test.test_importlib.import_ import util as importlib_util
Antoine Pitroud35cbf62009-01-06 19:02:24 +00006import marshal
Collin Winter88e333d2010-03-17 03:09:21 +00007import os
Charles-François Natalia13b1fa2011-10-04 19:17:26 +02008import platform
Collin Winter88e333d2010-03-17 03:09:21 +00009import py_compile
10import random
Collin Winter88e333d2010-03-17 03:09:21 +000011import stat
12import sys
13import unittest
R. David Murrayce4b1702010-12-14 23:06:25 +000014import textwrap
Antoine Pitroudd21f682012-01-25 03:00:57 +010015import errno
Jason R. Coombs71fde312012-06-17 03:53:47 -040016import shutil
Nick Coghlaneb8d6272012-10-19 23:32:00 +100017import contextlib
Barry Warsaw28a691b2010-04-17 00:19:56 +000018
Jason R. Coombs71fde312012-06-17 03:53:47 -040019import test.support
Barry Warsaw28a691b2010-04-17 00:19:56 +000020from test.support import (
21 EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
22 make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
Antoine Pitrou48114b92012-06-17 22:33:38 +020023 unlink, unload, create_empty_file, cpython_only)
R. David Murrayce4b1702010-12-14 23:06:25 +000024from test import script_helper
Guido van Rossumbd6f4fb2000-10-24 17:16:32 +000025
Tim Peters72f98e92001-05-08 15:19:57 +000026
Ezio Melottic28f6fa2013-03-16 19:48:51 +020027skip_if_dont_write_bytecode = unittest.skipIf(
28 sys.dont_write_bytecode,
29 "test meaningful only when writing bytecode")
30
Tim Peters08138fd2004-08-02 03:58:27 +000031def remove_files(name):
Skip Montanaro7a98be22007-08-16 14:35:24 +000032 for f in (name + ".py",
33 name + ".pyc",
34 name + ".pyo",
35 name + ".pyw",
Tim Peters08138fd2004-08-02 03:58:27 +000036 name + "$py.class"):
Florent Xicluna8fbddf12010-03-17 20:29:51 +000037 unlink(f)
Florent Xicluna27354cc2010-08-16 18:41:19 +000038 rmtree('__pycache__')
Tim Peters08138fd2004-08-02 03:58:27 +000039
Tim Petersc1731372001-08-04 08:12:36 +000040
Nick Coghlaneb8d6272012-10-19 23:32:00 +100041@contextlib.contextmanager
42def _ready_to_import(name=None, source=""):
43 # sets up a temporary directory and removes it
44 # creates the module file
45 # temporarily clears the module from sys.modules (if any)
46 name = name or "spam"
47 with script_helper.temp_dir() as tempdir:
48 path = script_helper.make_script(tempdir, name, source)
49 old_module = sys.modules.pop(name, None)
50 try:
51 sys.path.insert(0, tempdir)
52 yield name, path
53 sys.path.remove(tempdir)
54 finally:
55 if old_module is not None:
56 sys.modules[name] = old_module
57
58
Collin Winter88e333d2010-03-17 03:09:21 +000059class ImportTests(unittest.TestCase):
Tim Petersc1731372001-08-04 08:12:36 +000060
Antoine Pitrou46719af2011-03-21 19:05:02 +010061 def setUp(self):
62 remove_files(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +010063 importlib.invalidate_caches()
Antoine Pitrou46719af2011-03-21 19:05:02 +010064
Florent Xicluna8fbddf12010-03-17 20:29:51 +000065 def tearDown(self):
66 unload(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +000067
Florent Xicluna8fbddf12010-03-17 20:29:51 +000068 setUp = tearDown
69
Collin Winter88e333d2010-03-17 03:09:21 +000070 def test_case_sensitivity(self):
71 # Brief digression to test that import is case-sensitive: if we got
72 # this far, we know for sure that "random" exists.
Benjamin Peterson1c87e292010-10-30 23:04:49 +000073 with self.assertRaises(ImportError):
Thomas Wouters89f507f2006-12-13 04:49:30 +000074 import RAnDoM
Tim Peters08138fd2004-08-02 03:58:27 +000075
Collin Winter88e333d2010-03-17 03:09:21 +000076 def test_double_const(self):
77 # Another brief digression to test the accuracy of manifest float
78 # constants.
Thomas Wouters89f507f2006-12-13 04:49:30 +000079 from test import double_const # don't blink -- that *was* the test
Tim Peters08138fd2004-08-02 03:58:27 +000080
Collin Winter88e333d2010-03-17 03:09:21 +000081 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000082 def test_with_extension(ext):
Collin Winter88e333d2010-03-17 03:09:21 +000083 # The extension is normally ".py", perhaps ".pyw".
Thomas Wouters89f507f2006-12-13 04:49:30 +000084 source = TESTFN + ext
Skip Montanaro7a98be22007-08-16 14:35:24 +000085 pyo = TESTFN + ".pyo"
Florent Xicluna8fbddf12010-03-17 20:29:51 +000086 if is_jython:
Thomas Wouters89f507f2006-12-13 04:49:30 +000087 pyc = TESTFN + "$py.class"
88 else:
Skip Montanaro7a98be22007-08-16 14:35:24 +000089 pyc = TESTFN + ".pyc"
Tim Peters08138fd2004-08-02 03:58:27 +000090
Benjamin Peterson16a1f632009-06-13 13:01:19 +000091 with open(source, "w") as f:
Barry Warsaw28a691b2010-04-17 00:19:56 +000092 print("# This tests Python's ability to import a",
93 ext, "file.", file=f)
Benjamin Peterson16a1f632009-06-13 13:01:19 +000094 a = random.randrange(1000)
95 b = random.randrange(1000)
96 print("a =", a, file=f)
97 print("b =", b, file=f)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000098
Amaury Forgeot d'Arcdd9e3b82007-11-16 00:56:23 +000099 if TESTFN in sys.modules:
100 del sys.modules[TESTFN]
Brett Cannonfd074152012-04-14 14:10:13 -0400101 importlib.invalidate_caches()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000102 try:
103 try:
104 mod = __import__(TESTFN)
Guido van Rossumb940e112007-01-10 16:19:56 +0000105 except ImportError as err:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000106 self.fail("import from %s failed: %s" % (ext, err))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000108 self.assertEqual(mod.a, a,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000109 "module loaded (%s) but contents invalid" % mod)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000110 self.assertEqual(mod.b, b,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000111 "module loaded (%s) but contents invalid" % mod)
112 finally:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000113 forget(TESTFN)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000114 unlink(source)
115 unlink(pyc)
116 unlink(pyo)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000117
Thomas Wouters89f507f2006-12-13 04:49:30 +0000118 sys.path.insert(0, os.curdir)
119 try:
Skip Montanaro7a98be22007-08-16 14:35:24 +0000120 test_with_extension(".py")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000121 if sys.platform.startswith("win"):
Collin Winter88e333d2010-03-17 03:09:21 +0000122 for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000123 test_with_extension(ext)
124 finally:
125 del sys.path[0]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200127 @skip_if_dont_write_bytecode
Victor Stinner53ffdc52011-09-23 18:54:40 +0200128 def test_bug7732(self):
129 source = TESTFN + '.py'
130 os.mkdir(source)
131 try:
132 self.assertRaisesRegex(ImportError, '^No module',
133 imp.find_module, TESTFN, ["."])
134 finally:
135 os.rmdir(source)
136
Thomas Wouters89f507f2006-12-13 04:49:30 +0000137 def test_module_with_large_stack(self, module='longlist'):
Collin Winter88e333d2010-03-17 03:09:21 +0000138 # Regression test for http://bugs.python.org/issue561858.
Skip Montanaro7a98be22007-08-16 14:35:24 +0000139 filename = module + '.py'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000140
Collin Winter88e333d2010-03-17 03:09:21 +0000141 # Create a file with a list of 65000 elements.
Brett Cannon2cab50b2010-07-03 01:32:48 +0000142 with open(filename, 'w') as f:
Collin Winter88e333d2010-03-17 03:09:21 +0000143 f.write('d = [\n')
144 for i in range(65000):
145 f.write('"",\n')
146 f.write(']')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000147
Brett Cannon2cab50b2010-07-03 01:32:48 +0000148 try:
149 # Compile & remove .py file; we only need .pyc (or .pyo).
150 # Bytecode must be relocated from the PEP 3147 bytecode-only location.
151 py_compile.compile(filename)
152 finally:
153 unlink(filename)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000154
Collin Winter88e333d2010-03-17 03:09:21 +0000155 # Need to be able to load from current dir.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000156 sys.path.append('')
Brett Cannon73def612012-04-14 14:38:19 -0400157 importlib.invalidate_caches()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000158
Brett Cannon93220d02010-05-15 22:20:16 +0000159 try:
Brett Cannon2cab50b2010-07-03 01:32:48 +0000160 make_legacy_pyc(filename)
Brett Cannon93220d02010-05-15 22:20:16 +0000161 # This used to crash.
162 exec('import ' + module)
163 finally:
164 # Cleanup.
165 del sys.path[-1]
166 unlink(filename + 'c')
167 unlink(filename + 'o')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000168
169 def test_failing_import_sticks(self):
Skip Montanaro7a98be22007-08-16 14:35:24 +0000170 source = TESTFN + ".py"
Collin Winter88e333d2010-03-17 03:09:21 +0000171 with open(source, "w") as f:
172 print("a = 1/0", file=f)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000173
174 # New in 2.4, we shouldn't be able to import that no matter how often
175 # we try.
176 sys.path.insert(0, os.curdir)
Antoine Pitrou021548c2012-07-12 19:21:43 +0200177 importlib.invalidate_caches()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000178 if TESTFN in sys.modules:
179 del sys.modules[TESTFN]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000180 try:
Collin Winter88e333d2010-03-17 03:09:21 +0000181 for i in [1, 2, 3]:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000182 self.assertRaises(ZeroDivisionError, __import__, TESTFN)
183 self.assertNotIn(TESTFN, sys.modules,
184 "damaged module in sys.modules on %i try" % i)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000185 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000186 del sys.path[0]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000187 remove_files(TESTFN)
188
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189 def test_import_name_binding(self):
190 # import x.y.z binds x in the current namespace
191 import test as x
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000192 import test.support
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000193 self.assertTrue(x is test, x.__name__)
194 self.assertTrue(hasattr(test.support, "__file__"))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000195
196 # import x.y.z as w binds z as w
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000197 import test.support as y
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000198 self.assertTrue(y is test.support, y.__name__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000199
Christian Heimes13a7a212008-01-07 17:13:09 +0000200 def test_failing_reload(self):
201 # A failing reload should leave the module object in sys.modules.
Collin Winter88e333d2010-03-17 03:09:21 +0000202 source = TESTFN + os.extsep + "py"
Christian Heimes13a7a212008-01-07 17:13:09 +0000203 with open(source, "w") as f:
204 f.write("a = 1\nb=2\n")
205
206 sys.path.insert(0, os.curdir)
207 try:
208 mod = __import__(TESTFN)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000209 self.assertIn(TESTFN, sys.modules)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000210 self.assertEqual(mod.a, 1, "module has wrong attribute values")
211 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000212
213 # On WinXP, just replacing the .py file wasn't enough to
214 # convince reload() to reparse it. Maybe the timestamp didn't
215 # move enough. We force it to get reparsed by removing the
216 # compiled file too.
217 remove_files(TESTFN)
218
219 # Now damage the module.
220 with open(source, "w") as f:
221 f.write("a = 10\nb=20//0\n")
222
223 self.assertRaises(ZeroDivisionError, imp.reload, mod)
224 # But we still expect the module to be in sys.modules.
225 mod = sys.modules.get(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000226 self.assertIsNot(mod, None, "expected module to be in sys.modules")
Christian Heimes13a7a212008-01-07 17:13:09 +0000227
228 # We should have replaced a w/ 10, but the old b value should
229 # stick.
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000230 self.assertEqual(mod.a, 10, "module has wrong attribute values")
231 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000232
233 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000234 del sys.path[0]
Christian Heimes13a7a212008-01-07 17:13:09 +0000235 remove_files(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000236 unload(TESTFN)
Christian Heimes13a7a212008-01-07 17:13:09 +0000237
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200238 @skip_if_dont_write_bytecode
Christian Heimes3b06e532008-01-07 20:12:44 +0000239 def test_file_to_source(self):
240 # check if __file__ points to the source file where available
241 source = TESTFN + ".py"
242 with open(source, "w") as f:
243 f.write("test = None\n")
244
245 sys.path.insert(0, os.curdir)
246 try:
247 mod = __import__(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000248 self.assertTrue(mod.__file__.endswith('.py'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000249 os.remove(source)
250 del sys.modules[TESTFN]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000251 make_legacy_pyc(source)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100252 importlib.invalidate_caches()
Christian Heimes3b06e532008-01-07 20:12:44 +0000253 mod = __import__(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000254 base, ext = os.path.splitext(mod.__file__)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000255 self.assertIn(ext, ('.pyc', '.pyo'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000256 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000257 del sys.path[0]
Christian Heimes3b06e532008-01-07 20:12:44 +0000258 remove_files(TESTFN)
259 if TESTFN in sys.modules:
260 del sys.modules[TESTFN]
261
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000262 def test_import_name_binding(self):
263 # import x.y.z binds x in the current namespace.
264 import test as x
265 import test.support
266 self.assertIs(x, test, x.__name__)
267 self.assertTrue(hasattr(test.support, "__file__"))
268
269 # import x.y.z as w binds z as w.
270 import test.support as y
271 self.assertIs(y, test.support, y.__name__)
272
Collin Winter88e333d2010-03-17 03:09:21 +0000273 def test_import_by_filename(self):
Christian Heimes454f37b2008-01-10 00:10:02 +0000274 path = os.path.abspath(TESTFN)
Victor Stinner6c6f8512010-08-07 10:09:35 +0000275 encoding = sys.getfilesystemencoding()
276 try:
277 path.encode(encoding)
278 except UnicodeEncodeError:
279 self.skipTest('path is not encodable to {}'.format(encoding))
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000280 with self.assertRaises(ImportError) as c:
Christian Heimes454f37b2008-01-10 00:10:02 +0000281 __import__(path)
Christian Heimes454f37b2008-01-10 00:10:02 +0000282
R. David Murrayce4b1702010-12-14 23:06:25 +0000283 def test_import_in_del_does_not_crash(self):
284 # Issue 4236
285 testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\
286 import sys
287 class C:
288 def __del__(self):
289 import imp
290 sys.argv.insert(0, C())
291 """))
292 script_helper.assert_python_ok(testfn)
293
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100294 def test_timestamp_overflow(self):
295 # A modification timestamp larger than 2**32 should not be a problem
296 # when importing a module (issue #11235).
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100297 sys.path.insert(0, os.curdir)
298 try:
299 source = TESTFN + ".py"
300 compiled = imp.cache_from_source(source)
301 with open(source, 'w') as f:
302 pass
303 try:
Antoine Pitrou33d15f72012-01-25 18:01:45 +0100304 os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5))
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100305 except OverflowError:
306 self.skipTest("cannot set modification time to large integer")
Antoine Pitroudd21f682012-01-25 03:00:57 +0100307 except OSError as e:
308 if e.errno != getattr(errno, 'EOVERFLOW', None):
309 raise
310 self.skipTest("cannot set modification time to large integer ({})".format(e))
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100311 __import__(TESTFN)
312 # The pyc file was created.
313 os.stat(compiled)
314 finally:
315 del sys.path[0]
316 remove_files(TESTFN)
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100317
Brett Cannon7385adc2012-08-17 13:21:16 -0400318 def test_bogus_fromlist(self):
319 try:
320 __import__('http', fromlist=['blah'])
321 except ImportError:
322 self.fail("fromlist must allow bogus names")
323
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000324
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200325@skip_if_dont_write_bytecode
Nick Coghlaneb8d6272012-10-19 23:32:00 +1000326class FilePermissionTests(unittest.TestCase):
327 # tests for file mode on cached .pyc/.pyo files
328
329 @unittest.skipUnless(os.name == 'posix',
330 "test meaningful only on posix systems")
331 def test_creation_mode(self):
332 mask = 0o022
333 with temp_umask(mask), _ready_to_import() as (name, path):
334 cached_path = imp.cache_from_source(path)
335 module = __import__(name)
336 if not os.path.exists(cached_path):
337 self.fail("__import__ did not result in creation of "
338 "either a .pyc or .pyo file")
339 stat_info = os.stat(cached_path)
340
341 # Check that the umask is respected, and the executable bits
342 # aren't set.
343 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)),
344 oct(0o666 & ~mask))
345
346 @unittest.skipUnless(os.name == 'posix',
347 "test meaningful only on posix systems")
348 def test_cached_mode_issue_2051(self):
349 # permissions of .pyc should match those of .py, regardless of mask
350 mode = 0o600
351 with temp_umask(0o022), _ready_to_import() as (name, path):
352 cached_path = imp.cache_from_source(path)
353 os.chmod(path, mode)
354 __import__(name)
355 if not os.path.exists(cached_path):
356 self.fail("__import__ did not result in creation of "
357 "either a .pyc or .pyo file")
358 stat_info = os.stat(cached_path)
359
360 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(mode))
361
362 @unittest.skipUnless(os.name == 'posix',
363 "test meaningful only on posix systems")
364 def test_cached_readonly(self):
365 mode = 0o400
366 with temp_umask(0o022), _ready_to_import() as (name, path):
367 cached_path = imp.cache_from_source(path)
368 os.chmod(path, mode)
369 __import__(name)
370 if not os.path.exists(cached_path):
371 self.fail("__import__ did not result in creation of "
372 "either a .pyc or .pyo file")
373 stat_info = os.stat(cached_path)
374
375 expected = mode | 0o200 # Account for fix for issue #6074
376 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(expected))
377
378 def test_pyc_always_writable(self):
379 # Initially read-only .pyc files on Windows used to cause problems
380 # with later updates, see issue #6074 for details
381 with _ready_to_import() as (name, path):
382 # Write a Python file, make it read-only and import it
383 with open(path, 'w') as f:
384 f.write("x = 'original'\n")
385 # Tweak the mtime of the source to ensure pyc gets updated later
386 s = os.stat(path)
387 os.utime(path, (s.st_atime, s.st_mtime-100000000))
388 os.chmod(path, 0o400)
389 m = __import__(name)
390 self.assertEqual(m.x, 'original')
391 # Change the file and then reimport it
392 os.chmod(path, 0o600)
393 with open(path, 'w') as f:
394 f.write("x = 'rewritten'\n")
395 unload(name)
396 importlib.invalidate_caches()
397 m = __import__(name)
398 self.assertEqual(m.x, 'rewritten')
399 # Now delete the source file and check the pyc was rewritten
400 unlink(path)
401 unload(name)
402 importlib.invalidate_caches()
403 if __debug__:
404 bytecode_only = path + "c"
405 else:
406 bytecode_only = path + "o"
407 os.rename(imp.cache_from_source(path), bytecode_only)
408 m = __import__(name)
409 self.assertEqual(m.x, 'rewritten')
410
411
Collin Winter88e333d2010-03-17 03:09:21 +0000412class PycRewritingTests(unittest.TestCase):
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000413 # Test that the `co_filename` attribute on code objects always points
414 # to the right file, even when various things happen (e.g. both the .py
415 # and the .pyc file are renamed).
416
417 module_name = "unlikely_module_name"
418 module_source = """
419import sys
420code_filename = sys._getframe().f_code.co_filename
421module_filename = __file__
422constant = 1
423def func():
424 pass
425func_filename = func.__code__.co_filename
426"""
427 dir_name = os.path.abspath(TESTFN)
428 file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
Barry Warsaw28a691b2010-04-17 00:19:56 +0000429 compiled_name = imp.cache_from_source(file_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000430
431 def setUp(self):
432 self.sys_path = sys.path[:]
433 self.orig_module = sys.modules.pop(self.module_name, None)
434 os.mkdir(self.dir_name)
435 with open(self.file_name, "w") as f:
436 f.write(self.module_source)
437 sys.path.insert(0, self.dir_name)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100438 importlib.invalidate_caches()
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000439
440 def tearDown(self):
441 sys.path[:] = self.sys_path
442 if self.orig_module is not None:
443 sys.modules[self.module_name] = self.orig_module
444 else:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000445 unload(self.module_name)
446 unlink(self.file_name)
447 unlink(self.compiled_name)
Florent Xicluna27354cc2010-08-16 18:41:19 +0000448 rmtree(self.dir_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000449
450 def import_module(self):
451 ns = globals()
452 __import__(self.module_name, ns, ns)
453 return sys.modules[self.module_name]
454
455 def test_basics(self):
456 mod = self.import_module()
457 self.assertEqual(mod.module_filename, self.file_name)
458 self.assertEqual(mod.code_filename, self.file_name)
459 self.assertEqual(mod.func_filename, self.file_name)
460 del sys.modules[self.module_name]
461 mod = self.import_module()
462 self.assertEqual(mod.module_filename, self.file_name)
463 self.assertEqual(mod.code_filename, self.file_name)
464 self.assertEqual(mod.func_filename, self.file_name)
465
466 def test_incorrect_code_name(self):
467 py_compile.compile(self.file_name, dfile="another_module.py")
468 mod = self.import_module()
469 self.assertEqual(mod.module_filename, self.file_name)
470 self.assertEqual(mod.code_filename, self.file_name)
471 self.assertEqual(mod.func_filename, self.file_name)
472
473 def test_module_without_source(self):
474 target = "another_module.py"
475 py_compile.compile(self.file_name, dfile=target)
476 os.remove(self.file_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000477 pyc_file = make_legacy_pyc(self.file_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400478 importlib.invalidate_caches()
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000479 mod = self.import_module()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000480 self.assertEqual(mod.module_filename, pyc_file)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000481 self.assertEqual(mod.code_filename, target)
482 self.assertEqual(mod.func_filename, target)
483
484 def test_foreign_code(self):
485 py_compile.compile(self.file_name)
486 with open(self.compiled_name, "rb") as f:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100487 header = f.read(12)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000488 code = marshal.load(f)
489 constants = list(code.co_consts)
490 foreign_code = test_main.__code__
491 pos = constants.index(1)
492 constants[pos] = foreign_code
493 code = type(code)(code.co_argcount, code.co_kwonlyargcount,
494 code.co_nlocals, code.co_stacksize,
495 code.co_flags, code.co_code, tuple(constants),
496 code.co_names, code.co_varnames, code.co_filename,
497 code.co_name, code.co_firstlineno, code.co_lnotab,
498 code.co_freevars, code.co_cellvars)
499 with open(self.compiled_name, "wb") as f:
500 f.write(header)
501 marshal.dump(code, f)
502 mod = self.import_module()
503 self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
504
Collin Winter88e333d2010-03-17 03:09:21 +0000505
Christian Heimes204093a2007-11-01 22:37:07 +0000506class PathsTests(unittest.TestCase):
507 SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
508 'test\u00b0\u00b3\u00b2')
Christian Heimes90333392007-11-01 19:08:42 +0000509 path = TESTFN
510
511 def setUp(self):
512 os.mkdir(self.path)
513 self.syspath = sys.path[:]
514
515 def tearDown(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000516 rmtree(self.path)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000517 sys.path[:] = self.syspath
Christian Heimes90333392007-11-01 19:08:42 +0000518
Collin Winter88e333d2010-03-17 03:09:21 +0000519 # Regression test for http://bugs.python.org/issue1293.
Christian Heimes1d1a4002007-11-01 19:41:07 +0000520 def test_trailing_slash(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000521 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
522 f.write("testdata = 'test_trailing_slash'")
Christian Heimes1d1a4002007-11-01 19:41:07 +0000523 sys.path.append(self.path+'/')
524 mod = __import__("test_trailing_slash")
525 self.assertEqual(mod.testdata, 'test_trailing_slash')
526 unload("test_trailing_slash")
527
Collin Winter88e333d2010-03-17 03:09:21 +0000528 # Regression test for http://bugs.python.org/issue3677.
Brett Cannonbbdc9cd2012-04-20 16:29:39 -0400529 @unittest.skipUnless(sys.platform == 'win32', 'Windows-specific')
Brett Cannon9e924ed2012-04-20 17:34:59 -0400530 def test_UNC_path(self):
Antoine Pitrouf189e802012-07-12 19:48:49 +0200531 with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f:
532 f.write("testdata = 'test_unc_path'")
Brett Cannonb8c02062012-04-21 19:11:58 -0400533 importlib.invalidate_caches()
Collin Winter88e333d2010-03-17 03:09:21 +0000534 # Create the UNC path, like \\myhost\c$\foo\bar.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000535 path = os.path.abspath(self.path)
536 import socket
537 hn = socket.gethostname()
538 drive = path[0]
539 unc = "\\\\%s\\%s$"%(hn, drive)
540 unc += path[2:]
Brett Cannonb8c02062012-04-21 19:11:58 -0400541 try:
Antoine Pitrou5df02042012-07-12 19:50:03 +0200542 os.listdir(unc)
Antoine Pitrou68f42472012-07-13 20:54:42 +0200543 except OSError as e:
544 if e.errno in (errno.EPERM, errno.EACCES):
545 # See issue #15338
546 self.skipTest("cannot access administrative share %r" % (unc,))
547 raise
Antoine Pitrouc27ace62012-07-13 20:59:19 +0200548 sys.path.insert(0, unc)
549 try:
550 mod = __import__("test_unc_path")
551 except ImportError as e:
552 self.fail("could not import 'test_unc_path' from %r: %r"
553 % (unc, e))
554 self.assertEqual(mod.testdata, 'test_unc_path')
555 self.assertTrue(mod.__file__.startswith(unc), mod.__file__)
556 unload("test_unc_path")
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000557
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000558
Collin Winter88e333d2010-03-17 03:09:21 +0000559class RelativeImportTests(unittest.TestCase):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000560
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000561 def tearDown(self):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000562 unload("test.relimport")
563 setUp = tearDown
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000564
565 def test_relimport_star(self):
566 # This will import * from .test_import.
567 from . import relimport
Collin Winter88e333d2010-03-17 03:09:21 +0000568 self.assertTrue(hasattr(relimport, "RelativeImportTests"))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000569
Georg Brandl2ee470f2008-07-16 12:55:28 +0000570 def test_issue3221(self):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000571 # Note for mergers: the 'absolute' tests from the 2.x branch
572 # are missing in Py3k because implicit relative imports are
573 # a thing of the past
Collin Winter88e333d2010-03-17 03:09:21 +0000574 #
575 # Regression test for http://bugs.python.org/issue3221.
Georg Brandl2ee470f2008-07-16 12:55:28 +0000576 def check_relative():
577 exec("from . import relimport", ns)
Collin Winter88e333d2010-03-17 03:09:21 +0000578
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000579 # Check relative import OK with __package__ and __name__ correct
Georg Brandl2ee470f2008-07-16 12:55:28 +0000580 ns = dict(__package__='test', __name__='test.notarealmodule')
581 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000582
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000583 # Check relative import OK with only __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000584 ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
585 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000586
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000587 # Check relative import fails with only __package__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000588 ns = dict(__package__='foo', __name__='test.notarealmodule')
589 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000590
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000591 # Check relative import fails with __package__ and __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000592 ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
593 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000594
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000595 # Check relative import fails with package set to a non-string
Georg Brandl2ee470f2008-07-16 12:55:28 +0000596 ns = dict(__package__=object())
Brett Cannonfd074152012-04-14 14:10:13 -0400597 self.assertRaises(TypeError, check_relative)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000598
Benjamin Peterson556d8002010-06-27 22:37:28 +0000599 def test_absolute_import_without_future(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000600 # If explicit relative import syntax is used, then do not try
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000601 # to perform an absolute import in the face of failure.
Benjamin Peterson556d8002010-06-27 22:37:28 +0000602 # Issue #7902.
Florent Xicluna27354cc2010-08-16 18:41:19 +0000603 with self.assertRaises(ImportError):
Benjamin Peterson556d8002010-06-27 22:37:28 +0000604 from .os import sep
Benjamin Peterson556d8002010-06-27 22:37:28 +0000605 self.fail("explicit relative import triggered an "
Florent Xicluna27354cc2010-08-16 18:41:19 +0000606 "implicit absolute import")
Collin Winter88e333d2010-03-17 03:09:21 +0000607
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000608
Collin Winter6498cff2010-03-17 03:14:31 +0000609class OverridingImportBuiltinTests(unittest.TestCase):
610 def test_override_builtin(self):
611 # Test that overriding builtins.__import__ can bypass sys.modules.
612 import os
613
614 def foo():
615 import os
616 return os
617 self.assertEqual(foo(), os) # Quick sanity check.
618
619 with swap_attr(builtins, "__import__", lambda *x: 5):
620 self.assertEqual(foo(), 5)
621
622 # Test what happens when we shadow __import__ in globals(); this
623 # currently does not impact the import process, but if this changes,
624 # other code will need to change, so keep this test as a tripwire.
625 with swap_item(globals(), "__import__", lambda *x: 5):
626 self.assertEqual(foo(), os)
627
628
Barry Warsaw28a691b2010-04-17 00:19:56 +0000629class PycacheTests(unittest.TestCase):
630 # Test the various PEP 3147 related behaviors.
631
632 tag = imp.get_tag()
633
634 def _clean(self):
635 forget(TESTFN)
636 rmtree('__pycache__')
637 unlink(self.source)
638
639 def setUp(self):
640 self.source = TESTFN + '.py'
641 self._clean()
642 with open(self.source, 'w') as fp:
643 print('# This is a test file written by test_import.py', file=fp)
644 sys.path.insert(0, os.curdir)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100645 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000646
647 def tearDown(self):
648 assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]'
649 del sys.path[0]
650 self._clean()
651
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200652 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000653 def test_import_pyc_path(self):
654 self.assertFalse(os.path.exists('__pycache__'))
655 __import__(TESTFN)
656 self.assertTrue(os.path.exists('__pycache__'))
657 self.assertTrue(os.path.exists(os.path.join(
Georg Brandlfb3c84a2010-10-14 07:24:28 +0000658 '__pycache__', '{}.{}.py{}'.format(
Benjamin Petersond388c4e2012-09-25 11:01:41 -0400659 TESTFN, self.tag, 'c' if __debug__ else 'o'))))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000660
661 @unittest.skipUnless(os.name == 'posix',
662 "test meaningful only on posix systems")
Charles-François Natali035018d2011-10-04 23:35:47 +0200663 @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
Charles-François Natali79164c82011-10-04 20:40:58 +0200664 "due to varying filesystem permission semantics (issue #11956)")
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200665 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000666 def test_unwritable_directory(self):
667 # When the umask causes the new __pycache__ directory to be
668 # unwritable, the import still succeeds but no .pyc file is written.
669 with temp_umask(0o222):
670 __import__(TESTFN)
671 self.assertTrue(os.path.exists('__pycache__'))
672 self.assertFalse(os.path.exists(os.path.join(
673 '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag))))
674
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200675 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000676 def test_missing_source(self):
677 # With PEP 3147 cache layout, removing the source but leaving the pyc
678 # file does not satisfy the import.
679 __import__(TESTFN)
680 pyc_file = imp.cache_from_source(self.source)
681 self.assertTrue(os.path.exists(pyc_file))
682 os.remove(self.source)
683 forget(TESTFN)
684 self.assertRaises(ImportError, __import__, TESTFN)
685
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200686 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000687 def test_missing_source_legacy(self):
688 # Like test_missing_source() except that for backward compatibility,
689 # when the pyc file lives where the py file would have been (and named
690 # without the tag), it is importable. The __file__ of the imported
691 # module is the pyc location.
692 __import__(TESTFN)
693 # pyc_file gets removed in _clean() via tearDown().
694 pyc_file = make_legacy_pyc(self.source)
695 os.remove(self.source)
696 unload(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100697 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000698 m = __import__(TESTFN)
699 self.assertEqual(m.__file__,
700 os.path.join(os.curdir, os.path.relpath(pyc_file)))
701
702 def test___cached__(self):
703 # Modules now also have an __cached__ that points to the pyc file.
704 m = __import__(TESTFN)
705 pyc_file = imp.cache_from_source(TESTFN + '.py')
706 self.assertEqual(m.__cached__, os.path.join(os.curdir, pyc_file))
707
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200708 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000709 def test___cached___legacy_pyc(self):
710 # Like test___cached__() except that for backward compatibility,
711 # when the pyc file lives where the py file would have been (and named
712 # without the tag), it is importable. The __cached__ of the imported
713 # module is the pyc location.
714 __import__(TESTFN)
715 # pyc_file gets removed in _clean() via tearDown().
716 pyc_file = make_legacy_pyc(self.source)
717 os.remove(self.source)
718 unload(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100719 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000720 m = __import__(TESTFN)
721 self.assertEqual(m.__cached__,
722 os.path.join(os.curdir, os.path.relpath(pyc_file)))
723
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200724 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000725 def test_package___cached__(self):
726 # Like test___cached__ but for packages.
727 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000728 rmtree('pep3147')
Antoine Pitroud4daa872012-06-23 18:09:55 +0200729 unload('pep3147.foo')
730 unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000731 os.mkdir('pep3147')
732 self.addCleanup(cleanup)
733 # Touch the __init__.py
734 with open(os.path.join('pep3147', '__init__.py'), 'w'):
735 pass
736 with open(os.path.join('pep3147', 'foo.py'), 'w'):
737 pass
Brett Cannonfd074152012-04-14 14:10:13 -0400738 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000739 m = __import__('pep3147.foo')
740 init_pyc = imp.cache_from_source(
741 os.path.join('pep3147', '__init__.py'))
742 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
743 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
744 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
745 os.path.join(os.curdir, foo_pyc))
746
747 def test_package___cached___from_pyc(self):
748 # Like test___cached__ but ensuring __cached__ when imported from a
749 # PEP 3147 pyc file.
750 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000751 rmtree('pep3147')
Antoine Pitroud4daa872012-06-23 18:09:55 +0200752 unload('pep3147.foo')
753 unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000754 os.mkdir('pep3147')
755 self.addCleanup(cleanup)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000756 # Touch the __init__.py
757 with open(os.path.join('pep3147', '__init__.py'), 'w'):
758 pass
759 with open(os.path.join('pep3147', 'foo.py'), 'w'):
760 pass
Brett Cannonfd074152012-04-14 14:10:13 -0400761 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000762 m = __import__('pep3147.foo')
763 unload('pep3147.foo')
764 unload('pep3147')
Brett Cannonfd074152012-04-14 14:10:13 -0400765 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000766 m = __import__('pep3147.foo')
767 init_pyc = imp.cache_from_source(
768 os.path.join('pep3147', '__init__.py'))
769 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
770 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
771 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
772 os.path.join(os.curdir, foo_pyc))
773
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100774 def test_recompute_pyc_same_second(self):
775 # Even when the source file doesn't change timestamp, a change in
776 # source size is enough to trigger recomputation of the pyc file.
777 __import__(TESTFN)
778 unload(TESTFN)
779 with open(self.source, 'a') as fp:
780 print("x = 5", file=fp)
781 m = __import__(TESTFN)
782 self.assertEqual(m.x, 5)
783
Barry Warsaw28a691b2010-04-17 00:19:56 +0000784
Jason R. Coombs71fde312012-06-17 03:53:47 -0400785class TestSymbolicallyLinkedPackage(unittest.TestCase):
786 package_name = 'sample'
Brett Cannon6ee96952012-07-20 14:22:04 -0400787 tagged = package_name + '-tagged'
Jason R. Coombs71fde312012-06-17 03:53:47 -0400788
789 def setUp(self):
Brett Cannon6ee96952012-07-20 14:22:04 -0400790 test.support.rmtree(self.tagged)
791 test.support.rmtree(self.package_name)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400792 self.orig_sys_path = sys.path[:]
793
794 # create a sample package; imagine you have a package with a tag and
795 # you want to symbolically link it from its untagged name.
796 os.mkdir(self.tagged)
Brett Cannon6ee96952012-07-20 14:22:04 -0400797 self.addCleanup(test.support.rmtree, self.tagged)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400798 init_file = os.path.join(self.tagged, '__init__.py')
Brett Cannon6ee96952012-07-20 14:22:04 -0400799 test.support.create_empty_file(init_file)
800 assert os.path.exists(init_file)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400801
802 # now create a symlink to the tagged package
803 # sample -> sample-tagged
Jason R. Coombsd0118e12012-07-26 15:21:17 -0400804 os.symlink(self.tagged, self.package_name, target_is_directory=True)
Brett Cannon6ee96952012-07-20 14:22:04 -0400805 self.addCleanup(test.support.unlink, self.package_name)
806 importlib.invalidate_caches()
Jason R. Coombs71fde312012-06-17 03:53:47 -0400807
Jason R. Coombsd0118e12012-07-26 15:21:17 -0400808 self.assertEqual(os.path.isdir(self.package_name), True)
Jason R. Coombs42c9b042012-06-20 10:24:24 -0400809
Brett Cannon6ee96952012-07-20 14:22:04 -0400810 assert os.path.isfile(os.path.join(self.package_name, '__init__.py'))
Jason R. Coombs71fde312012-06-17 03:53:47 -0400811
Brett Cannon6ee96952012-07-20 14:22:04 -0400812 def tearDown(self):
813 sys.path[:] = self.orig_sys_path
Jason R. Coombs71fde312012-06-17 03:53:47 -0400814
815 # regression test for issue6727
816 @unittest.skipUnless(
817 not hasattr(sys, 'getwindowsversion')
818 or sys.getwindowsversion() >= (6, 0),
819 "Windows Vista or later required")
820 @test.support.skip_unless_symlink
821 def test_symlinked_dir_importable(self):
822 # make sure sample can only be imported from the current directory.
823 sys.path[:] = ['.']
Brett Cannon6ee96952012-07-20 14:22:04 -0400824 assert os.path.exists(self.package_name)
825 assert os.path.exists(os.path.join(self.package_name, '__init__.py'))
Jason R. Coombs71fde312012-06-17 03:53:47 -0400826
Brett Cannon6ee96952012-07-20 14:22:04 -0400827 # Try to import the package
828 importlib.import_module(self.package_name)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400829
830
Antoine Pitrou48114b92012-06-17 22:33:38 +0200831@cpython_only
832class ImportlibBootstrapTests(unittest.TestCase):
833 # These tests check that importlib is bootstrapped.
834
835 def test_frozen_importlib(self):
836 mod = sys.modules['_frozen_importlib']
837 self.assertTrue(mod)
838
839 def test_frozen_importlib_is_bootstrap(self):
840 from importlib import _bootstrap
841 mod = sys.modules['_frozen_importlib']
842 self.assertIs(mod, _bootstrap)
843 self.assertEqual(mod.__name__, 'importlib._bootstrap')
844 self.assertEqual(mod.__package__, 'importlib')
845 self.assertTrue(mod.__file__.endswith('_bootstrap.py'), mod.__file__)
846
Nick Coghlanbe7e49f2012-07-20 23:40:09 +1000847 def test_there_can_be_only_one(self):
848 # Issue #15386 revealed a tricky loophole in the bootstrapping
849 # This test is technically redundant, since the bug caused importing
850 # this test module to crash completely, but it helps prove the point
851 from importlib import machinery
852 mod = sys.modules['_frozen_importlib']
853 self.assertIs(machinery.FileFinder, mod.FileFinder)
854 self.assertIs(imp.new_module, mod.new_module)
855
Antoine Pitrou48114b92012-06-17 22:33:38 +0200856
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200857class ImportTracebackTests(unittest.TestCase):
858
859 def setUp(self):
860 os.mkdir(TESTFN)
861 self.old_path = sys.path[:]
862 sys.path.insert(0, TESTFN)
863
864 def tearDown(self):
865 sys.path[:] = self.old_path
866 rmtree(TESTFN)
867
Nick Coghlan42c07662012-07-31 21:14:18 +1000868 def create_module(self, mod, contents, ext=".py"):
869 fname = os.path.join(TESTFN, mod + ext)
870 with open(fname, "w") as f:
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200871 f.write(contents)
872 self.addCleanup(unload, mod)
873 importlib.invalidate_caches()
Nick Coghlan42c07662012-07-31 21:14:18 +1000874 return fname
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200875
876 def assert_traceback(self, tb, files):
877 deduped_files = []
878 while tb:
879 code = tb.tb_frame.f_code
880 fn = code.co_filename
881 if not deduped_files or fn != deduped_files[-1]:
882 deduped_files.append(fn)
883 tb = tb.tb_next
884 self.assertEqual(len(deduped_files), len(files), deduped_files)
885 for fn, pat in zip(deduped_files, files):
Antoine Pitrou68038552012-07-08 13:16:15 +0200886 self.assertIn(pat, fn)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200887
888 def test_nonexistent_module(self):
889 try:
890 # assertRaises() clears __traceback__
891 import nonexistent_xyzzy
892 except ImportError as e:
893 tb = e.__traceback__
894 else:
895 self.fail("ImportError should have been raised")
896 self.assert_traceback(tb, [__file__])
897
898 def test_nonexistent_module_nested(self):
899 self.create_module("foo", "import nonexistent_xyzzy")
900 try:
901 import foo
902 except ImportError as e:
903 tb = e.__traceback__
904 else:
905 self.fail("ImportError should have been raised")
906 self.assert_traceback(tb, [__file__, 'foo.py'])
907
908 def test_exec_failure(self):
909 self.create_module("foo", "1/0")
910 try:
911 import foo
912 except ZeroDivisionError as e:
913 tb = e.__traceback__
914 else:
915 self.fail("ZeroDivisionError should have been raised")
916 self.assert_traceback(tb, [__file__, 'foo.py'])
917
918 def test_exec_failure_nested(self):
919 self.create_module("foo", "import bar")
920 self.create_module("bar", "1/0")
921 try:
922 import foo
923 except ZeroDivisionError as e:
924 tb = e.__traceback__
925 else:
926 self.fail("ZeroDivisionError should have been raised")
927 self.assert_traceback(tb, [__file__, 'foo.py', 'bar.py'])
928
Nick Coghlan5ee98922012-07-29 20:30:36 +1000929 # A few more examples from issue #15425
930 def test_syntax_error(self):
931 self.create_module("foo", "invalid syntax is invalid")
932 try:
933 import foo
934 except SyntaxError as e:
935 tb = e.__traceback__
936 else:
937 self.fail("SyntaxError should have been raised")
938 self.assert_traceback(tb, [__file__])
939
940 def _setup_broken_package(self, parent, child):
941 pkg_name = "_parent_foo"
Nick Coghlan336d9ac2012-07-31 21:39:42 +1000942 self.addCleanup(unload, pkg_name)
943 pkg_path = os.path.join(TESTFN, pkg_name)
944 os.mkdir(pkg_path)
Nick Coghlan5ee98922012-07-29 20:30:36 +1000945 # Touch the __init__.py
Nick Coghlan336d9ac2012-07-31 21:39:42 +1000946 init_path = os.path.join(pkg_path, '__init__.py')
Nick Coghlan5ee98922012-07-29 20:30:36 +1000947 with open(init_path, 'w') as f:
948 f.write(parent)
Nick Coghlan336d9ac2012-07-31 21:39:42 +1000949 bar_path = os.path.join(pkg_path, 'bar.py')
Nick Coghlan5ee98922012-07-29 20:30:36 +1000950 with open(bar_path, 'w') as f:
951 f.write(child)
952 importlib.invalidate_caches()
953 return init_path, bar_path
954
955 def test_broken_submodule(self):
956 init_path, bar_path = self._setup_broken_package("", "1/0")
957 try:
958 import _parent_foo.bar
959 except ZeroDivisionError as e:
960 tb = e.__traceback__
961 else:
962 self.fail("ZeroDivisionError should have been raised")
963 self.assert_traceback(tb, [__file__, bar_path])
964
965 def test_broken_from(self):
966 init_path, bar_path = self._setup_broken_package("", "1/0")
967 try:
968 from _parent_foo import bar
969 except ZeroDivisionError as e:
970 tb = e.__traceback__
971 else:
972 self.fail("ImportError should have been raised")
973 self.assert_traceback(tb, [__file__, bar_path])
974
975 def test_broken_parent(self):
976 init_path, bar_path = self._setup_broken_package("1/0", "")
977 try:
978 import _parent_foo.bar
979 except ZeroDivisionError as e:
980 tb = e.__traceback__
981 else:
982 self.fail("ZeroDivisionError should have been raised")
983 self.assert_traceback(tb, [__file__, init_path])
984
985 def test_broken_parent_from(self):
986 init_path, bar_path = self._setup_broken_package("1/0", "")
987 try:
988 from _parent_foo import bar
989 except ZeroDivisionError as e:
990 tb = e.__traceback__
991 else:
992 self.fail("ZeroDivisionError should have been raised")
993 self.assert_traceback(tb, [__file__, init_path])
994
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200995 @cpython_only
996 def test_import_bug(self):
997 # We simulate a bug in importlib and check that it's not stripped
998 # away from the traceback.
999 self.create_module("foo", "")
1000 importlib = sys.modules['_frozen_importlib']
1001 old_load_module = importlib.SourceLoader.load_module
1002 try:
1003 def load_module(*args):
1004 1/0
1005 importlib.SourceLoader.load_module = load_module
1006 try:
1007 import foo
1008 except ZeroDivisionError as e:
1009 tb = e.__traceback__
1010 else:
1011 self.fail("ZeroDivisionError should have been raised")
1012 self.assert_traceback(tb, [__file__, '<frozen importlib', __file__])
1013 finally:
1014 importlib.SourceLoader.load_module = old_load_module
1015
1016
Thomas Wouters89f507f2006-12-13 04:49:30 +00001017def test_main(verbose=None):
Nick Coghlaneb8d6272012-10-19 23:32:00 +10001018 run_unittest(ImportTests, PycacheTests, FilePermissionTests,
Brett Cannonba525862012-07-20 14:01:34 -04001019 PycRewritingTests, PathsTests, RelativeImportTests,
1020 OverridingImportBuiltinTests,
1021 ImportlibBootstrapTests,
1022 TestSymbolicallyLinkedPackage,
1023 ImportTracebackTests)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001024
Barry Warsaw28a691b2010-04-17 00:19:56 +00001025
Thomas Wouters89f507f2006-12-13 04:49:30 +00001026if __name__ == '__main__':
Collin Winter88e333d2010-03-17 03:09:21 +00001027 # Test needs to be a package, so we can do relative imports.
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001028 from test.test_import import test_main
Thomas Wouters89f507f2006-12-13 04:49:30 +00001029 test_main()