blob: df08e6a86f6708ee53066859b74478181552e223 [file] [log] [blame]
Nick Coghlanbe7e49f2012-07-20 23:40:09 +10001# We import importlib *ASAP* in order to test #15386
2import importlib
Brett Cannona53cca32013-07-06 17:56:43 -04003from importlib._bootstrap import _get_sourcefile
Collin Winter6498cff2010-03-17 03:14:31 +00004import builtins
Christian Heimes13a7a212008-01-07 17:13:09 +00005import imp
Brett Cannon86ae9812012-07-20 15:40:57 -04006from test.test_importlib.import_ import util as importlib_util
Antoine Pitroud35cbf62009-01-06 19:02:24 +00007import marshal
Collin Winter88e333d2010-03-17 03:09:21 +00008import os
Charles-François Natalia13b1fa2011-10-04 19:17:26 +02009import platform
Collin Winter88e333d2010-03-17 03:09:21 +000010import py_compile
11import random
Collin Winter88e333d2010-03-17 03:09:21 +000012import stat
13import sys
14import unittest
Brett Cannona53cca32013-07-06 17:56:43 -040015import unittest.mock as mock
R. David Murrayce4b1702010-12-14 23:06:25 +000016import textwrap
Antoine Pitroudd21f682012-01-25 03:00:57 +010017import errno
Jason R. Coombs71fde312012-06-17 03:53:47 -040018import shutil
Nick Coghlaneb8d6272012-10-19 23:32:00 +100019import contextlib
Barry Warsaw28a691b2010-04-17 00:19:56 +000020
Jason R. Coombs71fde312012-06-17 03:53:47 -040021import test.support
Barry Warsaw28a691b2010-04-17 00:19:56 +000022from test.support import (
23 EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
24 make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
Antoine Pitrou48114b92012-06-17 22:33:38 +020025 unlink, unload, create_empty_file, cpython_only)
R. David Murrayce4b1702010-12-14 23:06:25 +000026from test import script_helper
Guido van Rossumbd6f4fb2000-10-24 17:16:32 +000027
Tim Peters72f98e92001-05-08 15:19:57 +000028
Ezio Melottic28f6fa2013-03-16 19:48:51 +020029skip_if_dont_write_bytecode = unittest.skipIf(
30 sys.dont_write_bytecode,
31 "test meaningful only when writing bytecode")
32
Tim Peters08138fd2004-08-02 03:58:27 +000033def remove_files(name):
Skip Montanaro7a98be22007-08-16 14:35:24 +000034 for f in (name + ".py",
35 name + ".pyc",
36 name + ".pyo",
37 name + ".pyw",
Tim Peters08138fd2004-08-02 03:58:27 +000038 name + "$py.class"):
Florent Xicluna8fbddf12010-03-17 20:29:51 +000039 unlink(f)
Florent Xicluna27354cc2010-08-16 18:41:19 +000040 rmtree('__pycache__')
Tim Peters08138fd2004-08-02 03:58:27 +000041
Tim Petersc1731372001-08-04 08:12:36 +000042
Nick Coghlaneb8d6272012-10-19 23:32:00 +100043@contextlib.contextmanager
44def _ready_to_import(name=None, source=""):
45 # sets up a temporary directory and removes it
46 # creates the module file
47 # temporarily clears the module from sys.modules (if any)
Nick Coghlanf1465f02013-04-15 22:56:51 +100048 # reverts or removes the module when cleaning up
Nick Coghlaneb8d6272012-10-19 23:32:00 +100049 name = name or "spam"
50 with script_helper.temp_dir() as tempdir:
51 path = script_helper.make_script(tempdir, name, source)
52 old_module = sys.modules.pop(name, None)
53 try:
54 sys.path.insert(0, tempdir)
55 yield name, path
56 sys.path.remove(tempdir)
57 finally:
58 if old_module is not None:
59 sys.modules[name] = old_module
Nick Coghlanf1465f02013-04-15 22:56:51 +100060 elif name in sys.modules:
61 del sys.modules[name]
Nick Coghlaneb8d6272012-10-19 23:32:00 +100062
63
Collin Winter88e333d2010-03-17 03:09:21 +000064class ImportTests(unittest.TestCase):
Tim Petersc1731372001-08-04 08:12:36 +000065
Antoine Pitrou46719af2011-03-21 19:05:02 +010066 def setUp(self):
67 remove_files(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +010068 importlib.invalidate_caches()
Antoine Pitrou46719af2011-03-21 19:05:02 +010069
Florent Xicluna8fbddf12010-03-17 20:29:51 +000070 def tearDown(self):
71 unload(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +000072
Florent Xicluna8fbddf12010-03-17 20:29:51 +000073 setUp = tearDown
74
Collin Winter88e333d2010-03-17 03:09:21 +000075 def test_case_sensitivity(self):
76 # Brief digression to test that import is case-sensitive: if we got
77 # this far, we know for sure that "random" exists.
Benjamin Peterson1c87e292010-10-30 23:04:49 +000078 with self.assertRaises(ImportError):
Thomas Wouters89f507f2006-12-13 04:49:30 +000079 import RAnDoM
Tim Peters08138fd2004-08-02 03:58:27 +000080
Collin Winter88e333d2010-03-17 03:09:21 +000081 def test_double_const(self):
82 # Another brief digression to test the accuracy of manifest float
83 # constants.
Thomas Wouters89f507f2006-12-13 04:49:30 +000084 from test import double_const # don't blink -- that *was* the test
Tim Peters08138fd2004-08-02 03:58:27 +000085
Collin Winter88e333d2010-03-17 03:09:21 +000086 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000087 def test_with_extension(ext):
Collin Winter88e333d2010-03-17 03:09:21 +000088 # The extension is normally ".py", perhaps ".pyw".
Thomas Wouters89f507f2006-12-13 04:49:30 +000089 source = TESTFN + ext
Skip Montanaro7a98be22007-08-16 14:35:24 +000090 pyo = TESTFN + ".pyo"
Florent Xicluna8fbddf12010-03-17 20:29:51 +000091 if is_jython:
Thomas Wouters89f507f2006-12-13 04:49:30 +000092 pyc = TESTFN + "$py.class"
93 else:
Skip Montanaro7a98be22007-08-16 14:35:24 +000094 pyc = TESTFN + ".pyc"
Tim Peters08138fd2004-08-02 03:58:27 +000095
Benjamin Peterson16a1f632009-06-13 13:01:19 +000096 with open(source, "w") as f:
Barry Warsaw28a691b2010-04-17 00:19:56 +000097 print("# This tests Python's ability to import a",
98 ext, "file.", file=f)
Benjamin Peterson16a1f632009-06-13 13:01:19 +000099 a = random.randrange(1000)
100 b = random.randrange(1000)
101 print("a =", a, file=f)
102 print("b =", b, file=f)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103
Amaury Forgeot d'Arcdd9e3b82007-11-16 00:56:23 +0000104 if TESTFN in sys.modules:
105 del sys.modules[TESTFN]
Brett Cannonfd074152012-04-14 14:10:13 -0400106 importlib.invalidate_caches()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000107 try:
108 try:
109 mod = __import__(TESTFN)
Guido van Rossumb940e112007-01-10 16:19:56 +0000110 except ImportError as err:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000111 self.fail("import from %s failed: %s" % (ext, err))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000112
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000113 self.assertEqual(mod.a, a,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000114 "module loaded (%s) but contents invalid" % mod)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000115 self.assertEqual(mod.b, b,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000116 "module loaded (%s) but contents invalid" % mod)
117 finally:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000118 forget(TESTFN)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000119 unlink(source)
120 unlink(pyc)
121 unlink(pyo)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000122
Thomas Wouters89f507f2006-12-13 04:49:30 +0000123 sys.path.insert(0, os.curdir)
124 try:
Skip Montanaro7a98be22007-08-16 14:35:24 +0000125 test_with_extension(".py")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000126 if sys.platform.startswith("win"):
Collin Winter88e333d2010-03-17 03:09:21 +0000127 for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000128 test_with_extension(ext)
129 finally:
130 del sys.path[0]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000131
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200132 @skip_if_dont_write_bytecode
Victor Stinner53ffdc52011-09-23 18:54:40 +0200133 def test_bug7732(self):
134 source = TESTFN + '.py'
135 os.mkdir(source)
136 try:
137 self.assertRaisesRegex(ImportError, '^No module',
138 imp.find_module, TESTFN, ["."])
139 finally:
140 os.rmdir(source)
141
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142 def test_module_with_large_stack(self, module='longlist'):
Collin Winter88e333d2010-03-17 03:09:21 +0000143 # Regression test for http://bugs.python.org/issue561858.
Skip Montanaro7a98be22007-08-16 14:35:24 +0000144 filename = module + '.py'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000145
Collin Winter88e333d2010-03-17 03:09:21 +0000146 # Create a file with a list of 65000 elements.
Brett Cannon2cab50b2010-07-03 01:32:48 +0000147 with open(filename, 'w') as f:
Collin Winter88e333d2010-03-17 03:09:21 +0000148 f.write('d = [\n')
149 for i in range(65000):
150 f.write('"",\n')
151 f.write(']')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000152
Brett Cannon2cab50b2010-07-03 01:32:48 +0000153 try:
154 # Compile & remove .py file; we only need .pyc (or .pyo).
155 # Bytecode must be relocated from the PEP 3147 bytecode-only location.
156 py_compile.compile(filename)
157 finally:
158 unlink(filename)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000159
Collin Winter88e333d2010-03-17 03:09:21 +0000160 # Need to be able to load from current dir.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000161 sys.path.append('')
Brett Cannon73def612012-04-14 14:38:19 -0400162 importlib.invalidate_caches()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000163
Brett Cannon93220d02010-05-15 22:20:16 +0000164 try:
Brett Cannon2cab50b2010-07-03 01:32:48 +0000165 make_legacy_pyc(filename)
Brett Cannon93220d02010-05-15 22:20:16 +0000166 # This used to crash.
167 exec('import ' + module)
168 finally:
169 # Cleanup.
170 del sys.path[-1]
171 unlink(filename + 'c')
172 unlink(filename + 'o')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000173
174 def test_failing_import_sticks(self):
Skip Montanaro7a98be22007-08-16 14:35:24 +0000175 source = TESTFN + ".py"
Collin Winter88e333d2010-03-17 03:09:21 +0000176 with open(source, "w") as f:
177 print("a = 1/0", file=f)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000178
179 # New in 2.4, we shouldn't be able to import that no matter how often
180 # we try.
181 sys.path.insert(0, os.curdir)
Antoine Pitrou021548c2012-07-12 19:21:43 +0200182 importlib.invalidate_caches()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000183 if TESTFN in sys.modules:
184 del sys.modules[TESTFN]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000185 try:
Collin Winter88e333d2010-03-17 03:09:21 +0000186 for i in [1, 2, 3]:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000187 self.assertRaises(ZeroDivisionError, __import__, TESTFN)
188 self.assertNotIn(TESTFN, sys.modules,
189 "damaged module in sys.modules on %i try" % i)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000191 del sys.path[0]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000192 remove_files(TESTFN)
193
Thomas Wouters89f507f2006-12-13 04:49:30 +0000194 def test_import_name_binding(self):
195 # import x.y.z binds x in the current namespace
196 import test as x
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000197 import test.support
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000198 self.assertTrue(x is test, x.__name__)
199 self.assertTrue(hasattr(test.support, "__file__"))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000200
201 # import x.y.z as w binds z as w
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000202 import test.support as y
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000203 self.assertTrue(y is test.support, y.__name__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000204
Christian Heimes13a7a212008-01-07 17:13:09 +0000205 def test_failing_reload(self):
206 # A failing reload should leave the module object in sys.modules.
Collin Winter88e333d2010-03-17 03:09:21 +0000207 source = TESTFN + os.extsep + "py"
Christian Heimes13a7a212008-01-07 17:13:09 +0000208 with open(source, "w") as f:
209 f.write("a = 1\nb=2\n")
210
211 sys.path.insert(0, os.curdir)
212 try:
213 mod = __import__(TESTFN)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000214 self.assertIn(TESTFN, sys.modules)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000215 self.assertEqual(mod.a, 1, "module has wrong attribute values")
216 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000217
218 # On WinXP, just replacing the .py file wasn't enough to
219 # convince reload() to reparse it. Maybe the timestamp didn't
220 # move enough. We force it to get reparsed by removing the
221 # compiled file too.
222 remove_files(TESTFN)
223
224 # Now damage the module.
225 with open(source, "w") as f:
226 f.write("a = 10\nb=20//0\n")
227
228 self.assertRaises(ZeroDivisionError, imp.reload, mod)
229 # But we still expect the module to be in sys.modules.
230 mod = sys.modules.get(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000231 self.assertIsNot(mod, None, "expected module to be in sys.modules")
Christian Heimes13a7a212008-01-07 17:13:09 +0000232
233 # We should have replaced a w/ 10, but the old b value should
234 # stick.
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000235 self.assertEqual(mod.a, 10, "module has wrong attribute values")
236 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000237
238 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000239 del sys.path[0]
Christian Heimes13a7a212008-01-07 17:13:09 +0000240 remove_files(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000241 unload(TESTFN)
Christian Heimes13a7a212008-01-07 17:13:09 +0000242
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200243 @skip_if_dont_write_bytecode
Christian Heimes3b06e532008-01-07 20:12:44 +0000244 def test_file_to_source(self):
245 # check if __file__ points to the source file where available
246 source = TESTFN + ".py"
247 with open(source, "w") as f:
248 f.write("test = None\n")
249
250 sys.path.insert(0, os.curdir)
251 try:
252 mod = __import__(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000253 self.assertTrue(mod.__file__.endswith('.py'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000254 os.remove(source)
255 del sys.modules[TESTFN]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000256 make_legacy_pyc(source)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100257 importlib.invalidate_caches()
Christian Heimes3b06e532008-01-07 20:12:44 +0000258 mod = __import__(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000259 base, ext = os.path.splitext(mod.__file__)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000260 self.assertIn(ext, ('.pyc', '.pyo'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000261 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000262 del sys.path[0]
Christian Heimes3b06e532008-01-07 20:12:44 +0000263 remove_files(TESTFN)
264 if TESTFN in sys.modules:
265 del sys.modules[TESTFN]
266
Collin Winter88e333d2010-03-17 03:09:21 +0000267 def test_import_by_filename(self):
Christian Heimes454f37b2008-01-10 00:10:02 +0000268 path = os.path.abspath(TESTFN)
Victor Stinner6c6f8512010-08-07 10:09:35 +0000269 encoding = sys.getfilesystemencoding()
270 try:
271 path.encode(encoding)
272 except UnicodeEncodeError:
273 self.skipTest('path is not encodable to {}'.format(encoding))
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000274 with self.assertRaises(ImportError) as c:
Christian Heimes454f37b2008-01-10 00:10:02 +0000275 __import__(path)
Christian Heimes454f37b2008-01-10 00:10:02 +0000276
R. David Murrayce4b1702010-12-14 23:06:25 +0000277 def test_import_in_del_does_not_crash(self):
278 # Issue 4236
279 testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\
280 import sys
281 class C:
282 def __del__(self):
283 import imp
284 sys.argv.insert(0, C())
285 """))
286 script_helper.assert_python_ok(testfn)
287
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100288 def test_timestamp_overflow(self):
289 # A modification timestamp larger than 2**32 should not be a problem
290 # when importing a module (issue #11235).
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100291 sys.path.insert(0, os.curdir)
292 try:
293 source = TESTFN + ".py"
294 compiled = imp.cache_from_source(source)
295 with open(source, 'w') as f:
296 pass
297 try:
Antoine Pitrou33d15f72012-01-25 18:01:45 +0100298 os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5))
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100299 except OverflowError:
300 self.skipTest("cannot set modification time to large integer")
Antoine Pitroudd21f682012-01-25 03:00:57 +0100301 except OSError as e:
302 if e.errno != getattr(errno, 'EOVERFLOW', None):
303 raise
304 self.skipTest("cannot set modification time to large integer ({})".format(e))
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100305 __import__(TESTFN)
306 # The pyc file was created.
307 os.stat(compiled)
308 finally:
309 del sys.path[0]
310 remove_files(TESTFN)
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100311
Brett Cannon7385adc2012-08-17 13:21:16 -0400312 def test_bogus_fromlist(self):
313 try:
314 __import__('http', fromlist=['blah'])
315 except ImportError:
316 self.fail("fromlist must allow bogus names")
317
Benjamin Peterson7d110042013-04-29 09:08:14 -0400318 @cpython_only
319 def test_delete_builtins_import(self):
320 args = ["-c", "del __builtins__.__import__; import os"]
321 popen = script_helper.spawn_python(*args)
322 stdout, stderr = popen.communicate()
323 self.assertIn(b"ImportError", stdout)
324
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000325
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200326@skip_if_dont_write_bytecode
Nick Coghlaneb8d6272012-10-19 23:32:00 +1000327class FilePermissionTests(unittest.TestCase):
328 # tests for file mode on cached .pyc/.pyo files
329
330 @unittest.skipUnless(os.name == 'posix',
331 "test meaningful only on posix systems")
332 def test_creation_mode(self):
333 mask = 0o022
334 with temp_umask(mask), _ready_to_import() as (name, path):
335 cached_path = imp.cache_from_source(path)
336 module = __import__(name)
337 if not os.path.exists(cached_path):
338 self.fail("__import__ did not result in creation of "
339 "either a .pyc or .pyo file")
340 stat_info = os.stat(cached_path)
341
342 # Check that the umask is respected, and the executable bits
343 # aren't set.
344 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)),
345 oct(0o666 & ~mask))
346
347 @unittest.skipUnless(os.name == 'posix',
348 "test meaningful only on posix systems")
349 def test_cached_mode_issue_2051(self):
350 # permissions of .pyc should match those of .py, regardless of mask
351 mode = 0o600
352 with temp_umask(0o022), _ready_to_import() as (name, path):
353 cached_path = imp.cache_from_source(path)
354 os.chmod(path, mode)
355 __import__(name)
356 if not os.path.exists(cached_path):
357 self.fail("__import__ did not result in creation of "
358 "either a .pyc or .pyo file")
359 stat_info = os.stat(cached_path)
360
361 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(mode))
362
363 @unittest.skipUnless(os.name == 'posix',
364 "test meaningful only on posix systems")
365 def test_cached_readonly(self):
366 mode = 0o400
367 with temp_umask(0o022), _ready_to_import() as (name, path):
368 cached_path = imp.cache_from_source(path)
369 os.chmod(path, mode)
370 __import__(name)
371 if not os.path.exists(cached_path):
372 self.fail("__import__ did not result in creation of "
373 "either a .pyc or .pyo file")
374 stat_info = os.stat(cached_path)
375
376 expected = mode | 0o200 # Account for fix for issue #6074
377 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(expected))
378
379 def test_pyc_always_writable(self):
380 # Initially read-only .pyc files on Windows used to cause problems
381 # with later updates, see issue #6074 for details
382 with _ready_to_import() as (name, path):
383 # Write a Python file, make it read-only and import it
384 with open(path, 'w') as f:
385 f.write("x = 'original'\n")
386 # Tweak the mtime of the source to ensure pyc gets updated later
387 s = os.stat(path)
388 os.utime(path, (s.st_atime, s.st_mtime-100000000))
389 os.chmod(path, 0o400)
390 m = __import__(name)
391 self.assertEqual(m.x, 'original')
392 # Change the file and then reimport it
393 os.chmod(path, 0o600)
394 with open(path, 'w') as f:
395 f.write("x = 'rewritten'\n")
396 unload(name)
397 importlib.invalidate_caches()
398 m = __import__(name)
399 self.assertEqual(m.x, 'rewritten')
400 # Now delete the source file and check the pyc was rewritten
401 unlink(path)
402 unload(name)
403 importlib.invalidate_caches()
404 if __debug__:
405 bytecode_only = path + "c"
406 else:
407 bytecode_only = path + "o"
408 os.rename(imp.cache_from_source(path), bytecode_only)
409 m = __import__(name)
410 self.assertEqual(m.x, 'rewritten')
411
412
Collin Winter88e333d2010-03-17 03:09:21 +0000413class PycRewritingTests(unittest.TestCase):
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000414 # Test that the `co_filename` attribute on code objects always points
415 # to the right file, even when various things happen (e.g. both the .py
416 # and the .pyc file are renamed).
417
418 module_name = "unlikely_module_name"
419 module_source = """
420import sys
421code_filename = sys._getframe().f_code.co_filename
422module_filename = __file__
423constant = 1
424def func():
425 pass
426func_filename = func.__code__.co_filename
427"""
428 dir_name = os.path.abspath(TESTFN)
429 file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
Barry Warsaw28a691b2010-04-17 00:19:56 +0000430 compiled_name = imp.cache_from_source(file_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000431
432 def setUp(self):
433 self.sys_path = sys.path[:]
434 self.orig_module = sys.modules.pop(self.module_name, None)
435 os.mkdir(self.dir_name)
436 with open(self.file_name, "w") as f:
437 f.write(self.module_source)
438 sys.path.insert(0, self.dir_name)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100439 importlib.invalidate_caches()
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000440
441 def tearDown(self):
442 sys.path[:] = self.sys_path
443 if self.orig_module is not None:
444 sys.modules[self.module_name] = self.orig_module
445 else:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000446 unload(self.module_name)
447 unlink(self.file_name)
448 unlink(self.compiled_name)
Florent Xicluna27354cc2010-08-16 18:41:19 +0000449 rmtree(self.dir_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000450
451 def import_module(self):
452 ns = globals()
453 __import__(self.module_name, ns, ns)
454 return sys.modules[self.module_name]
455
456 def test_basics(self):
457 mod = self.import_module()
458 self.assertEqual(mod.module_filename, self.file_name)
459 self.assertEqual(mod.code_filename, self.file_name)
460 self.assertEqual(mod.func_filename, self.file_name)
461 del sys.modules[self.module_name]
462 mod = self.import_module()
463 self.assertEqual(mod.module_filename, self.file_name)
464 self.assertEqual(mod.code_filename, self.file_name)
465 self.assertEqual(mod.func_filename, self.file_name)
466
467 def test_incorrect_code_name(self):
468 py_compile.compile(self.file_name, dfile="another_module.py")
469 mod = self.import_module()
470 self.assertEqual(mod.module_filename, self.file_name)
471 self.assertEqual(mod.code_filename, self.file_name)
472 self.assertEqual(mod.func_filename, self.file_name)
473
474 def test_module_without_source(self):
475 target = "another_module.py"
476 py_compile.compile(self.file_name, dfile=target)
477 os.remove(self.file_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000478 pyc_file = make_legacy_pyc(self.file_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400479 importlib.invalidate_caches()
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000480 mod = self.import_module()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000481 self.assertEqual(mod.module_filename, pyc_file)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000482 self.assertEqual(mod.code_filename, target)
483 self.assertEqual(mod.func_filename, target)
484
485 def test_foreign_code(self):
486 py_compile.compile(self.file_name)
487 with open(self.compiled_name, "rb") as f:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100488 header = f.read(12)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000489 code = marshal.load(f)
490 constants = list(code.co_consts)
491 foreign_code = test_main.__code__
492 pos = constants.index(1)
493 constants[pos] = foreign_code
494 code = type(code)(code.co_argcount, code.co_kwonlyargcount,
495 code.co_nlocals, code.co_stacksize,
496 code.co_flags, code.co_code, tuple(constants),
497 code.co_names, code.co_varnames, code.co_filename,
498 code.co_name, code.co_firstlineno, code.co_lnotab,
499 code.co_freevars, code.co_cellvars)
500 with open(self.compiled_name, "wb") as f:
501 f.write(header)
502 marshal.dump(code, f)
503 mod = self.import_module()
504 self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
505
Collin Winter88e333d2010-03-17 03:09:21 +0000506
Christian Heimes204093a2007-11-01 22:37:07 +0000507class PathsTests(unittest.TestCase):
508 SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
509 'test\u00b0\u00b3\u00b2')
Christian Heimes90333392007-11-01 19:08:42 +0000510 path = TESTFN
511
512 def setUp(self):
513 os.mkdir(self.path)
514 self.syspath = sys.path[:]
515
516 def tearDown(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000517 rmtree(self.path)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000518 sys.path[:] = self.syspath
Christian Heimes90333392007-11-01 19:08:42 +0000519
Collin Winter88e333d2010-03-17 03:09:21 +0000520 # Regression test for http://bugs.python.org/issue1293.
Christian Heimes1d1a4002007-11-01 19:41:07 +0000521 def test_trailing_slash(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000522 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
523 f.write("testdata = 'test_trailing_slash'")
Christian Heimes1d1a4002007-11-01 19:41:07 +0000524 sys.path.append(self.path+'/')
525 mod = __import__("test_trailing_slash")
526 self.assertEqual(mod.testdata, 'test_trailing_slash')
527 unload("test_trailing_slash")
528
Collin Winter88e333d2010-03-17 03:09:21 +0000529 # Regression test for http://bugs.python.org/issue3677.
Brett Cannonbbdc9cd2012-04-20 16:29:39 -0400530 @unittest.skipUnless(sys.platform == 'win32', 'Windows-specific')
Brett Cannon9e924ed2012-04-20 17:34:59 -0400531 def test_UNC_path(self):
Antoine Pitrouf189e802012-07-12 19:48:49 +0200532 with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f:
533 f.write("testdata = 'test_unc_path'")
Brett Cannonb8c02062012-04-21 19:11:58 -0400534 importlib.invalidate_caches()
Collin Winter88e333d2010-03-17 03:09:21 +0000535 # Create the UNC path, like \\myhost\c$\foo\bar.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000536 path = os.path.abspath(self.path)
537 import socket
538 hn = socket.gethostname()
539 drive = path[0]
540 unc = "\\\\%s\\%s$"%(hn, drive)
541 unc += path[2:]
Brett Cannonb8c02062012-04-21 19:11:58 -0400542 try:
Antoine Pitrou5df02042012-07-12 19:50:03 +0200543 os.listdir(unc)
Antoine Pitrou68f42472012-07-13 20:54:42 +0200544 except OSError as e:
545 if e.errno in (errno.EPERM, errno.EACCES):
546 # See issue #15338
547 self.skipTest("cannot access administrative share %r" % (unc,))
548 raise
Antoine Pitrouc27ace62012-07-13 20:59:19 +0200549 sys.path.insert(0, unc)
550 try:
551 mod = __import__("test_unc_path")
552 except ImportError as e:
553 self.fail("could not import 'test_unc_path' from %r: %r"
554 % (unc, e))
555 self.assertEqual(mod.testdata, 'test_unc_path')
556 self.assertTrue(mod.__file__.startswith(unc), mod.__file__)
557 unload("test_unc_path")
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000558
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000559
Collin Winter88e333d2010-03-17 03:09:21 +0000560class RelativeImportTests(unittest.TestCase):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000561
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000562 def tearDown(self):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000563 unload("test.relimport")
564 setUp = tearDown
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000565
566 def test_relimport_star(self):
567 # This will import * from .test_import.
568 from . import relimport
Collin Winter88e333d2010-03-17 03:09:21 +0000569 self.assertTrue(hasattr(relimport, "RelativeImportTests"))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000570
Georg Brandl2ee470f2008-07-16 12:55:28 +0000571 def test_issue3221(self):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000572 # Note for mergers: the 'absolute' tests from the 2.x branch
573 # are missing in Py3k because implicit relative imports are
574 # a thing of the past
Collin Winter88e333d2010-03-17 03:09:21 +0000575 #
576 # Regression test for http://bugs.python.org/issue3221.
Georg Brandl2ee470f2008-07-16 12:55:28 +0000577 def check_relative():
578 exec("from . import relimport", ns)
Collin Winter88e333d2010-03-17 03:09:21 +0000579
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000580 # Check relative import OK with __package__ and __name__ correct
Georg Brandl2ee470f2008-07-16 12:55:28 +0000581 ns = dict(__package__='test', __name__='test.notarealmodule')
582 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000583
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000584 # Check relative import OK with only __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000585 ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
586 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000587
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000588 # Check relative import fails with only __package__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000589 ns = dict(__package__='foo', __name__='test.notarealmodule')
590 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000591
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000592 # Check relative import fails with __package__ and __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000593 ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
594 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000595
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000596 # Check relative import fails with package set to a non-string
Georg Brandl2ee470f2008-07-16 12:55:28 +0000597 ns = dict(__package__=object())
Brett Cannonfd074152012-04-14 14:10:13 -0400598 self.assertRaises(TypeError, check_relative)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000599
Benjamin Peterson556d8002010-06-27 22:37:28 +0000600 def test_absolute_import_without_future(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000601 # If explicit relative import syntax is used, then do not try
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000602 # to perform an absolute import in the face of failure.
Benjamin Peterson556d8002010-06-27 22:37:28 +0000603 # Issue #7902.
Florent Xicluna27354cc2010-08-16 18:41:19 +0000604 with self.assertRaises(ImportError):
Benjamin Peterson556d8002010-06-27 22:37:28 +0000605 from .os import sep
Benjamin Peterson556d8002010-06-27 22:37:28 +0000606 self.fail("explicit relative import triggered an "
Florent Xicluna27354cc2010-08-16 18:41:19 +0000607 "implicit absolute import")
Collin Winter88e333d2010-03-17 03:09:21 +0000608
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000609
Collin Winter6498cff2010-03-17 03:14:31 +0000610class OverridingImportBuiltinTests(unittest.TestCase):
611 def test_override_builtin(self):
612 # Test that overriding builtins.__import__ can bypass sys.modules.
613 import os
614
615 def foo():
616 import os
617 return os
618 self.assertEqual(foo(), os) # Quick sanity check.
619
620 with swap_attr(builtins, "__import__", lambda *x: 5):
621 self.assertEqual(foo(), 5)
622
623 # Test what happens when we shadow __import__ in globals(); this
624 # currently does not impact the import process, but if this changes,
625 # other code will need to change, so keep this test as a tripwire.
626 with swap_item(globals(), "__import__", lambda *x: 5):
627 self.assertEqual(foo(), os)
628
629
Barry Warsaw28a691b2010-04-17 00:19:56 +0000630class PycacheTests(unittest.TestCase):
631 # Test the various PEP 3147 related behaviors.
632
633 tag = imp.get_tag()
634
635 def _clean(self):
636 forget(TESTFN)
637 rmtree('__pycache__')
638 unlink(self.source)
639
640 def setUp(self):
641 self.source = TESTFN + '.py'
642 self._clean()
643 with open(self.source, 'w') as fp:
644 print('# This is a test file written by test_import.py', file=fp)
645 sys.path.insert(0, os.curdir)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100646 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000647
648 def tearDown(self):
649 assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]'
650 del sys.path[0]
651 self._clean()
652
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200653 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000654 def test_import_pyc_path(self):
655 self.assertFalse(os.path.exists('__pycache__'))
656 __import__(TESTFN)
657 self.assertTrue(os.path.exists('__pycache__'))
658 self.assertTrue(os.path.exists(os.path.join(
Georg Brandlfb3c84a2010-10-14 07:24:28 +0000659 '__pycache__', '{}.{}.py{}'.format(
Benjamin Petersond388c4e2012-09-25 11:01:41 -0400660 TESTFN, self.tag, 'c' if __debug__ else 'o'))))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000661
662 @unittest.skipUnless(os.name == 'posix',
663 "test meaningful only on posix systems")
Charles-François Natali035018d2011-10-04 23:35:47 +0200664 @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
Charles-François Natali79164c82011-10-04 20:40:58 +0200665 "due to varying filesystem permission semantics (issue #11956)")
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200666 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000667 def test_unwritable_directory(self):
668 # When the umask causes the new __pycache__ directory to be
669 # unwritable, the import still succeeds but no .pyc file is written.
670 with temp_umask(0o222):
671 __import__(TESTFN)
672 self.assertTrue(os.path.exists('__pycache__'))
673 self.assertFalse(os.path.exists(os.path.join(
674 '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag))))
675
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200676 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000677 def test_missing_source(self):
678 # With PEP 3147 cache layout, removing the source but leaving the pyc
679 # file does not satisfy the import.
680 __import__(TESTFN)
681 pyc_file = imp.cache_from_source(self.source)
682 self.assertTrue(os.path.exists(pyc_file))
683 os.remove(self.source)
684 forget(TESTFN)
685 self.assertRaises(ImportError, __import__, TESTFN)
686
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200687 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000688 def test_missing_source_legacy(self):
689 # Like test_missing_source() except that for backward compatibility,
690 # when the pyc file lives where the py file would have been (and named
691 # without the tag), it is importable. The __file__ of the imported
692 # module is the pyc location.
693 __import__(TESTFN)
694 # pyc_file gets removed in _clean() via tearDown().
695 pyc_file = make_legacy_pyc(self.source)
696 os.remove(self.source)
697 unload(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100698 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000699 m = __import__(TESTFN)
700 self.assertEqual(m.__file__,
701 os.path.join(os.curdir, os.path.relpath(pyc_file)))
702
703 def test___cached__(self):
704 # Modules now also have an __cached__ that points to the pyc file.
705 m = __import__(TESTFN)
706 pyc_file = imp.cache_from_source(TESTFN + '.py')
707 self.assertEqual(m.__cached__, os.path.join(os.curdir, pyc_file))
708
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200709 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000710 def test___cached___legacy_pyc(self):
711 # Like test___cached__() except that for backward compatibility,
712 # when the pyc file lives where the py file would have been (and named
713 # without the tag), it is importable. The __cached__ of the imported
714 # module is the pyc location.
715 __import__(TESTFN)
716 # pyc_file gets removed in _clean() via tearDown().
717 pyc_file = make_legacy_pyc(self.source)
718 os.remove(self.source)
719 unload(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100720 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000721 m = __import__(TESTFN)
722 self.assertEqual(m.__cached__,
723 os.path.join(os.curdir, os.path.relpath(pyc_file)))
724
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200725 @skip_if_dont_write_bytecode
Barry Warsaw28a691b2010-04-17 00:19:56 +0000726 def test_package___cached__(self):
727 # Like test___cached__ but for packages.
728 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000729 rmtree('pep3147')
Antoine Pitroud4daa872012-06-23 18:09:55 +0200730 unload('pep3147.foo')
731 unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000732 os.mkdir('pep3147')
733 self.addCleanup(cleanup)
734 # Touch the __init__.py
735 with open(os.path.join('pep3147', '__init__.py'), 'w'):
736 pass
737 with open(os.path.join('pep3147', 'foo.py'), 'w'):
738 pass
Brett Cannonfd074152012-04-14 14:10:13 -0400739 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000740 m = __import__('pep3147.foo')
741 init_pyc = imp.cache_from_source(
742 os.path.join('pep3147', '__init__.py'))
743 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
744 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
745 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
746 os.path.join(os.curdir, foo_pyc))
747
748 def test_package___cached___from_pyc(self):
749 # Like test___cached__ but ensuring __cached__ when imported from a
750 # PEP 3147 pyc file.
751 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000752 rmtree('pep3147')
Antoine Pitroud4daa872012-06-23 18:09:55 +0200753 unload('pep3147.foo')
754 unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000755 os.mkdir('pep3147')
756 self.addCleanup(cleanup)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000757 # Touch the __init__.py
758 with open(os.path.join('pep3147', '__init__.py'), 'w'):
759 pass
760 with open(os.path.join('pep3147', 'foo.py'), 'w'):
761 pass
Brett Cannonfd074152012-04-14 14:10:13 -0400762 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000763 m = __import__('pep3147.foo')
764 unload('pep3147.foo')
765 unload('pep3147')
Brett Cannonfd074152012-04-14 14:10:13 -0400766 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000767 m = __import__('pep3147.foo')
768 init_pyc = imp.cache_from_source(
769 os.path.join('pep3147', '__init__.py'))
770 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
771 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
772 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
773 os.path.join(os.curdir, foo_pyc))
774
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100775 def test_recompute_pyc_same_second(self):
776 # Even when the source file doesn't change timestamp, a change in
777 # source size is enough to trigger recomputation of the pyc file.
778 __import__(TESTFN)
779 unload(TESTFN)
780 with open(self.source, 'a') as fp:
781 print("x = 5", file=fp)
782 m = __import__(TESTFN)
783 self.assertEqual(m.x, 5)
784
Barry Warsaw28a691b2010-04-17 00:19:56 +0000785
Jason R. Coombs71fde312012-06-17 03:53:47 -0400786class TestSymbolicallyLinkedPackage(unittest.TestCase):
787 package_name = 'sample'
Brett Cannon6ee96952012-07-20 14:22:04 -0400788 tagged = package_name + '-tagged'
Jason R. Coombs71fde312012-06-17 03:53:47 -0400789
790 def setUp(self):
Brett Cannon6ee96952012-07-20 14:22:04 -0400791 test.support.rmtree(self.tagged)
792 test.support.rmtree(self.package_name)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400793 self.orig_sys_path = sys.path[:]
794
795 # create a sample package; imagine you have a package with a tag and
796 # you want to symbolically link it from its untagged name.
797 os.mkdir(self.tagged)
Brett Cannon6ee96952012-07-20 14:22:04 -0400798 self.addCleanup(test.support.rmtree, self.tagged)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400799 init_file = os.path.join(self.tagged, '__init__.py')
Brett Cannon6ee96952012-07-20 14:22:04 -0400800 test.support.create_empty_file(init_file)
801 assert os.path.exists(init_file)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400802
803 # now create a symlink to the tagged package
804 # sample -> sample-tagged
Jason R. Coombsd0118e12012-07-26 15:21:17 -0400805 os.symlink(self.tagged, self.package_name, target_is_directory=True)
Brett Cannon6ee96952012-07-20 14:22:04 -0400806 self.addCleanup(test.support.unlink, self.package_name)
807 importlib.invalidate_caches()
Jason R. Coombs71fde312012-06-17 03:53:47 -0400808
Jason R. Coombsd0118e12012-07-26 15:21:17 -0400809 self.assertEqual(os.path.isdir(self.package_name), True)
Jason R. Coombs42c9b042012-06-20 10:24:24 -0400810
Brett Cannon6ee96952012-07-20 14:22:04 -0400811 assert os.path.isfile(os.path.join(self.package_name, '__init__.py'))
Jason R. Coombs71fde312012-06-17 03:53:47 -0400812
Brett Cannon6ee96952012-07-20 14:22:04 -0400813 def tearDown(self):
814 sys.path[:] = self.orig_sys_path
Jason R. Coombs71fde312012-06-17 03:53:47 -0400815
816 # regression test for issue6727
817 @unittest.skipUnless(
818 not hasattr(sys, 'getwindowsversion')
819 or sys.getwindowsversion() >= (6, 0),
820 "Windows Vista or later required")
821 @test.support.skip_unless_symlink
822 def test_symlinked_dir_importable(self):
823 # make sure sample can only be imported from the current directory.
824 sys.path[:] = ['.']
Brett Cannon6ee96952012-07-20 14:22:04 -0400825 assert os.path.exists(self.package_name)
826 assert os.path.exists(os.path.join(self.package_name, '__init__.py'))
Jason R. Coombs71fde312012-06-17 03:53:47 -0400827
Brett Cannon6ee96952012-07-20 14:22:04 -0400828 # Try to import the package
829 importlib.import_module(self.package_name)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400830
831
Antoine Pitrou48114b92012-06-17 22:33:38 +0200832@cpython_only
833class ImportlibBootstrapTests(unittest.TestCase):
834 # These tests check that importlib is bootstrapped.
835
836 def test_frozen_importlib(self):
837 mod = sys.modules['_frozen_importlib']
838 self.assertTrue(mod)
839
840 def test_frozen_importlib_is_bootstrap(self):
841 from importlib import _bootstrap
842 mod = sys.modules['_frozen_importlib']
843 self.assertIs(mod, _bootstrap)
844 self.assertEqual(mod.__name__, 'importlib._bootstrap')
845 self.assertEqual(mod.__package__, 'importlib')
846 self.assertTrue(mod.__file__.endswith('_bootstrap.py'), mod.__file__)
847
Nick Coghlanbe7e49f2012-07-20 23:40:09 +1000848 def test_there_can_be_only_one(self):
849 # Issue #15386 revealed a tricky loophole in the bootstrapping
850 # This test is technically redundant, since the bug caused importing
851 # this test module to crash completely, but it helps prove the point
852 from importlib import machinery
853 mod = sys.modules['_frozen_importlib']
854 self.assertIs(machinery.FileFinder, mod.FileFinder)
855 self.assertIs(imp.new_module, mod.new_module)
856
Antoine Pitrou48114b92012-06-17 22:33:38 +0200857
Brett Cannona53cca32013-07-06 17:56:43 -0400858@cpython_only
859class GetSourcefileTests(unittest.TestCase):
860
861 """Test importlib._bootstrap._get_sourcefile() as used by the C API.
862
863 Because of the peculiarities of the need of this function, the tests are
864 knowingly whitebox tests.
865
866 """
867
868 def test_get_sourcefile(self):
869 # Given a valid bytecode path, return the path to the corresponding
870 # source file if it exists.
871 with mock.patch('importlib._bootstrap._path_isfile') as _path_isfile:
872 _path_isfile.return_value = True;
873 path = TESTFN + '.pyc'
874 expect = TESTFN + '.py'
875 self.assertEqual(_get_sourcefile(path), expect)
876
877 def test_get_sourcefile_no_source(self):
878 # Given a valid bytecode path without a corresponding source path,
879 # return the original bytecode path.
880 with mock.patch('importlib._bootstrap._path_isfile') as _path_isfile:
881 _path_isfile.return_value = False;
882 path = TESTFN + '.pyc'
883 self.assertEqual(_get_sourcefile(path), path)
884
885 def test_get_sourcefile_bad_ext(self):
886 # Given a path with an invalid bytecode extension, return the
887 # bytecode path passed as the argument.
888 path = TESTFN + '.bad_ext'
889 self.assertEqual(_get_sourcefile(path), path)
890
891
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200892class ImportTracebackTests(unittest.TestCase):
893
894 def setUp(self):
895 os.mkdir(TESTFN)
896 self.old_path = sys.path[:]
897 sys.path.insert(0, TESTFN)
898
899 def tearDown(self):
900 sys.path[:] = self.old_path
901 rmtree(TESTFN)
902
Nick Coghlan42c07662012-07-31 21:14:18 +1000903 def create_module(self, mod, contents, ext=".py"):
904 fname = os.path.join(TESTFN, mod + ext)
905 with open(fname, "w") as f:
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200906 f.write(contents)
907 self.addCleanup(unload, mod)
908 importlib.invalidate_caches()
Nick Coghlan42c07662012-07-31 21:14:18 +1000909 return fname
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200910
911 def assert_traceback(self, tb, files):
912 deduped_files = []
913 while tb:
914 code = tb.tb_frame.f_code
915 fn = code.co_filename
916 if not deduped_files or fn != deduped_files[-1]:
917 deduped_files.append(fn)
918 tb = tb.tb_next
919 self.assertEqual(len(deduped_files), len(files), deduped_files)
920 for fn, pat in zip(deduped_files, files):
Antoine Pitrou68038552012-07-08 13:16:15 +0200921 self.assertIn(pat, fn)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200922
923 def test_nonexistent_module(self):
924 try:
925 # assertRaises() clears __traceback__
926 import nonexistent_xyzzy
927 except ImportError as e:
928 tb = e.__traceback__
929 else:
930 self.fail("ImportError should have been raised")
931 self.assert_traceback(tb, [__file__])
932
933 def test_nonexistent_module_nested(self):
934 self.create_module("foo", "import nonexistent_xyzzy")
935 try:
936 import foo
937 except ImportError as e:
938 tb = e.__traceback__
939 else:
940 self.fail("ImportError should have been raised")
941 self.assert_traceback(tb, [__file__, 'foo.py'])
942
943 def test_exec_failure(self):
944 self.create_module("foo", "1/0")
945 try:
946 import foo
947 except ZeroDivisionError as e:
948 tb = e.__traceback__
949 else:
950 self.fail("ZeroDivisionError should have been raised")
951 self.assert_traceback(tb, [__file__, 'foo.py'])
952
953 def test_exec_failure_nested(self):
954 self.create_module("foo", "import bar")
955 self.create_module("bar", "1/0")
956 try:
957 import foo
958 except ZeroDivisionError as e:
959 tb = e.__traceback__
960 else:
961 self.fail("ZeroDivisionError should have been raised")
962 self.assert_traceback(tb, [__file__, 'foo.py', 'bar.py'])
963
Nick Coghlan5ee98922012-07-29 20:30:36 +1000964 # A few more examples from issue #15425
965 def test_syntax_error(self):
966 self.create_module("foo", "invalid syntax is invalid")
967 try:
968 import foo
969 except SyntaxError as e:
970 tb = e.__traceback__
971 else:
972 self.fail("SyntaxError should have been raised")
973 self.assert_traceback(tb, [__file__])
974
975 def _setup_broken_package(self, parent, child):
976 pkg_name = "_parent_foo"
Nick Coghlan336d9ac2012-07-31 21:39:42 +1000977 self.addCleanup(unload, pkg_name)
978 pkg_path = os.path.join(TESTFN, pkg_name)
979 os.mkdir(pkg_path)
Nick Coghlan5ee98922012-07-29 20:30:36 +1000980 # Touch the __init__.py
Nick Coghlan336d9ac2012-07-31 21:39:42 +1000981 init_path = os.path.join(pkg_path, '__init__.py')
Nick Coghlan5ee98922012-07-29 20:30:36 +1000982 with open(init_path, 'w') as f:
983 f.write(parent)
Nick Coghlan336d9ac2012-07-31 21:39:42 +1000984 bar_path = os.path.join(pkg_path, 'bar.py')
Nick Coghlan5ee98922012-07-29 20:30:36 +1000985 with open(bar_path, 'w') as f:
986 f.write(child)
987 importlib.invalidate_caches()
988 return init_path, bar_path
989
990 def test_broken_submodule(self):
991 init_path, bar_path = self._setup_broken_package("", "1/0")
992 try:
993 import _parent_foo.bar
994 except ZeroDivisionError as e:
995 tb = e.__traceback__
996 else:
997 self.fail("ZeroDivisionError should have been raised")
998 self.assert_traceback(tb, [__file__, bar_path])
999
1000 def test_broken_from(self):
1001 init_path, bar_path = self._setup_broken_package("", "1/0")
1002 try:
1003 from _parent_foo import bar
1004 except ZeroDivisionError as e:
1005 tb = e.__traceback__
1006 else:
1007 self.fail("ImportError should have been raised")
1008 self.assert_traceback(tb, [__file__, bar_path])
1009
1010 def test_broken_parent(self):
1011 init_path, bar_path = self._setup_broken_package("1/0", "")
1012 try:
1013 import _parent_foo.bar
1014 except ZeroDivisionError as e:
1015 tb = e.__traceback__
1016 else:
1017 self.fail("ZeroDivisionError should have been raised")
1018 self.assert_traceback(tb, [__file__, init_path])
1019
1020 def test_broken_parent_from(self):
1021 init_path, bar_path = self._setup_broken_package("1/0", "")
1022 try:
1023 from _parent_foo import bar
1024 except ZeroDivisionError as e:
1025 tb = e.__traceback__
1026 else:
1027 self.fail("ZeroDivisionError should have been raised")
1028 self.assert_traceback(tb, [__file__, init_path])
1029
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001030 @cpython_only
1031 def test_import_bug(self):
1032 # We simulate a bug in importlib and check that it's not stripped
1033 # away from the traceback.
1034 self.create_module("foo", "")
1035 importlib = sys.modules['_frozen_importlib']
1036 old_load_module = importlib.SourceLoader.load_module
1037 try:
1038 def load_module(*args):
1039 1/0
1040 importlib.SourceLoader.load_module = load_module
1041 try:
1042 import foo
1043 except ZeroDivisionError as e:
1044 tb = e.__traceback__
1045 else:
1046 self.fail("ZeroDivisionError should have been raised")
1047 self.assert_traceback(tb, [__file__, '<frozen importlib', __file__])
1048 finally:
1049 importlib.SourceLoader.load_module = old_load_module
1050
1051
Thomas Wouters89f507f2006-12-13 04:49:30 +00001052def test_main(verbose=None):
Nick Coghlaneb8d6272012-10-19 23:32:00 +10001053 run_unittest(ImportTests, PycacheTests, FilePermissionTests,
Brett Cannonba525862012-07-20 14:01:34 -04001054 PycRewritingTests, PathsTests, RelativeImportTests,
1055 OverridingImportBuiltinTests,
Brett Cannona53cca32013-07-06 17:56:43 -04001056 ImportlibBootstrapTests, GetSourcefileTests,
Brett Cannonba525862012-07-20 14:01:34 -04001057 TestSymbolicallyLinkedPackage,
1058 ImportTracebackTests)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001059
Barry Warsaw28a691b2010-04-17 00:19:56 +00001060
Thomas Wouters89f507f2006-12-13 04:49:30 +00001061if __name__ == '__main__':
Collin Winter88e333d2010-03-17 03:09:21 +00001062 # Test needs to be a package, so we can do relative imports.
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001063 from test.test_import import test_main
Thomas Wouters89f507f2006-12-13 04:49:30 +00001064 test_main()