blob: 5053d49f4639982ede5468592ba6d2114b80f8ba [file] [log] [blame]
Collin Winter6498cff2010-03-17 03:14:31 +00001import builtins
Christian Heimes13a7a212008-01-07 17:13:09 +00002import imp
Brett Cannon1f274792010-07-23 14:03:16 +00003from importlib.test.import_ import test_relative_imports
4from importlib.test.import_ import util as importlib_util
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01005import importlib
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
Barry Warsaw28a691b2010-04-17 00:19:56 +000016
17from test.support import (
18 EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
19 make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
Victor Stinnerbf816222011-06-30 23:25:47 +020020 unlink, unload, create_empty_file)
R. David Murrayce4b1702010-12-14 23:06:25 +000021from test import script_helper
Guido van Rossumbd6f4fb2000-10-24 17:16:32 +000022
Tim Peters72f98e92001-05-08 15:19:57 +000023
Tim Peters08138fd2004-08-02 03:58:27 +000024def remove_files(name):
Skip Montanaro7a98be22007-08-16 14:35:24 +000025 for f in (name + ".py",
26 name + ".pyc",
27 name + ".pyo",
28 name + ".pyw",
Tim Peters08138fd2004-08-02 03:58:27 +000029 name + "$py.class"):
Florent Xicluna8fbddf12010-03-17 20:29:51 +000030 unlink(f)
Florent Xicluna27354cc2010-08-16 18:41:19 +000031 rmtree('__pycache__')
Tim Peters08138fd2004-08-02 03:58:27 +000032
Tim Petersc1731372001-08-04 08:12:36 +000033
Collin Winter88e333d2010-03-17 03:09:21 +000034class ImportTests(unittest.TestCase):
Tim Petersc1731372001-08-04 08:12:36 +000035
Antoine Pitrou46719af2011-03-21 19:05:02 +010036 def setUp(self):
37 remove_files(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +010038 importlib.invalidate_caches()
Antoine Pitrou46719af2011-03-21 19:05:02 +010039
Florent Xicluna8fbddf12010-03-17 20:29:51 +000040 def tearDown(self):
41 unload(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +000042
Florent Xicluna8fbddf12010-03-17 20:29:51 +000043 setUp = tearDown
44
Collin Winter88e333d2010-03-17 03:09:21 +000045 def test_case_sensitivity(self):
46 # Brief digression to test that import is case-sensitive: if we got
47 # this far, we know for sure that "random" exists.
Benjamin Peterson1c87e292010-10-30 23:04:49 +000048 with self.assertRaises(ImportError):
Thomas Wouters89f507f2006-12-13 04:49:30 +000049 import RAnDoM
Tim Peters08138fd2004-08-02 03:58:27 +000050
Collin Winter88e333d2010-03-17 03:09:21 +000051 def test_double_const(self):
52 # Another brief digression to test the accuracy of manifest float
53 # constants.
Thomas Wouters89f507f2006-12-13 04:49:30 +000054 from test import double_const # don't blink -- that *was* the test
Tim Peters08138fd2004-08-02 03:58:27 +000055
Collin Winter88e333d2010-03-17 03:09:21 +000056 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000057 def test_with_extension(ext):
Collin Winter88e333d2010-03-17 03:09:21 +000058 # The extension is normally ".py", perhaps ".pyw".
Thomas Wouters89f507f2006-12-13 04:49:30 +000059 source = TESTFN + ext
Skip Montanaro7a98be22007-08-16 14:35:24 +000060 pyo = TESTFN + ".pyo"
Florent Xicluna8fbddf12010-03-17 20:29:51 +000061 if is_jython:
Thomas Wouters89f507f2006-12-13 04:49:30 +000062 pyc = TESTFN + "$py.class"
63 else:
Skip Montanaro7a98be22007-08-16 14:35:24 +000064 pyc = TESTFN + ".pyc"
Tim Peters08138fd2004-08-02 03:58:27 +000065
Benjamin Peterson16a1f632009-06-13 13:01:19 +000066 with open(source, "w") as f:
Barry Warsaw28a691b2010-04-17 00:19:56 +000067 print("# This tests Python's ability to import a",
68 ext, "file.", file=f)
Benjamin Peterson16a1f632009-06-13 13:01:19 +000069 a = random.randrange(1000)
70 b = random.randrange(1000)
71 print("a =", a, file=f)
72 print("b =", b, file=f)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000073
Amaury Forgeot d'Arcdd9e3b82007-11-16 00:56:23 +000074 if TESTFN in sys.modules:
75 del sys.modules[TESTFN]
Brett Cannonfd074152012-04-14 14:10:13 -040076 importlib.invalidate_caches()
Thomas Wouters89f507f2006-12-13 04:49:30 +000077 try:
78 try:
79 mod = __import__(TESTFN)
Guido van Rossumb940e112007-01-10 16:19:56 +000080 except ImportError as err:
Thomas Wouters89f507f2006-12-13 04:49:30 +000081 self.fail("import from %s failed: %s" % (ext, err))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082
Florent Xicluna8fbddf12010-03-17 20:29:51 +000083 self.assertEqual(mod.a, a,
Thomas Wouters89f507f2006-12-13 04:49:30 +000084 "module loaded (%s) but contents invalid" % mod)
Florent Xicluna8fbddf12010-03-17 20:29:51 +000085 self.assertEqual(mod.b, b,
Thomas Wouters89f507f2006-12-13 04:49:30 +000086 "module loaded (%s) but contents invalid" % mod)
87 finally:
Barry Warsaw28a691b2010-04-17 00:19:56 +000088 forget(TESTFN)
Guido van Rossume7ba4952007-06-06 23:52:48 +000089 unlink(source)
90 unlink(pyc)
91 unlink(pyo)
Thomas Wouters477c8d52006-05-27 19:21:47 +000092
Thomas Wouters89f507f2006-12-13 04:49:30 +000093 sys.path.insert(0, os.curdir)
94 try:
Skip Montanaro7a98be22007-08-16 14:35:24 +000095 test_with_extension(".py")
Thomas Wouters89f507f2006-12-13 04:49:30 +000096 if sys.platform.startswith("win"):
Collin Winter88e333d2010-03-17 03:09:21 +000097 for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
Thomas Wouters89f507f2006-12-13 04:49:30 +000098 test_with_extension(ext)
99 finally:
100 del sys.path[0]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000101
Barry Warsaw28a691b2010-04-17 00:19:56 +0000102 @unittest.skipUnless(os.name == 'posix',
103 "test meaningful only on posix systems")
Charles-François Natali0c929d92011-11-10 19:12:29 +0100104 def test_creation_mode(self):
105 mask = 0o022
106 with temp_umask(mask):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000107 sys.path.insert(0, os.curdir)
108 try:
109 fname = TESTFN + os.extsep + "py"
Victor Stinnerbf816222011-06-30 23:25:47 +0200110 create_empty_file(fname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000111 fn = imp.cache_from_source(fname)
Antoine Pitrou28f8bee2011-12-21 15:50:42 +0100112 unlink(fn)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100113 importlib.invalidate_caches()
Antoine Pitrou28f8bee2011-12-21 15:50:42 +0100114 __import__(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000115 if not os.path.exists(fn):
116 self.fail("__import__ did not result in creation of "
117 "either a .pyc or .pyo file")
Charles-François Natali0c929d92011-11-10 19:12:29 +0100118 s = os.stat(fn)
119 # Check that the umask is respected, and the executable bits
120 # aren't set.
121 self.assertEqual(stat.S_IMODE(s.st_mode), 0o666 & ~mask)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000122 finally:
123 del sys.path[0]
124 remove_files(TESTFN)
125 unload(TESTFN)
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000126
Collin Winter88e333d2010-03-17 03:09:21 +0000127 def test_imp_module(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000128 # Verify that the imp module can correctly load and find .py files
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000129 # XXX (ncoghlan): It would be nice to use support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000130 # here, but that breaks because the os module registers some
131 # handlers in copy_reg on import. Since CleanImport doesn't
132 # revert that registration, the module is left in a broken
133 # state after reversion. Reinitialising the module contents
134 # and just reverting os.environ to its previous state is an OK
135 # workaround
136 orig_path = os.path
137 orig_getenv = os.getenv
138 with EnvironmentVarGuard():
139 x = imp.find_module("os")
Benjamin Petersone0487972010-10-30 23:06:57 +0000140 self.addCleanup(x[0].close)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000141 new_os = imp.load_module("os", *x)
142 self.assertIs(os, new_os)
143 self.assertIs(orig_path, new_os.path)
144 self.assertIsNot(orig_getenv, new_os.getenv)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000145
Victor Stinner53ffdc52011-09-23 18:54:40 +0200146 def test_bug7732(self):
147 source = TESTFN + '.py'
148 os.mkdir(source)
149 try:
150 self.assertRaisesRegex(ImportError, '^No module',
151 imp.find_module, TESTFN, ["."])
152 finally:
153 os.rmdir(source)
154
Thomas Wouters89f507f2006-12-13 04:49:30 +0000155 def test_module_with_large_stack(self, module='longlist'):
Collin Winter88e333d2010-03-17 03:09:21 +0000156 # Regression test for http://bugs.python.org/issue561858.
Skip Montanaro7a98be22007-08-16 14:35:24 +0000157 filename = module + '.py'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000158
Collin Winter88e333d2010-03-17 03:09:21 +0000159 # Create a file with a list of 65000 elements.
Brett Cannon2cab50b2010-07-03 01:32:48 +0000160 with open(filename, 'w') as f:
Collin Winter88e333d2010-03-17 03:09:21 +0000161 f.write('d = [\n')
162 for i in range(65000):
163 f.write('"",\n')
164 f.write(']')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000165
Brett Cannon2cab50b2010-07-03 01:32:48 +0000166 try:
167 # Compile & remove .py file; we only need .pyc (or .pyo).
168 # Bytecode must be relocated from the PEP 3147 bytecode-only location.
169 py_compile.compile(filename)
170 finally:
171 unlink(filename)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000172
Collin Winter88e333d2010-03-17 03:09:21 +0000173 # Need to be able to load from current dir.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000174 sys.path.append('')
Brett Cannon73def612012-04-14 14:38:19 -0400175 importlib.invalidate_caches()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000176
Brett Cannon93220d02010-05-15 22:20:16 +0000177 try:
Brett Cannon2cab50b2010-07-03 01:32:48 +0000178 make_legacy_pyc(filename)
Brett Cannon93220d02010-05-15 22:20:16 +0000179 # This used to crash.
180 exec('import ' + module)
181 finally:
182 # Cleanup.
183 del sys.path[-1]
184 unlink(filename + 'c')
185 unlink(filename + 'o')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000186
187 def test_failing_import_sticks(self):
Skip Montanaro7a98be22007-08-16 14:35:24 +0000188 source = TESTFN + ".py"
Collin Winter88e333d2010-03-17 03:09:21 +0000189 with open(source, "w") as f:
190 print("a = 1/0", file=f)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191
192 # New in 2.4, we shouldn't be able to import that no matter how often
193 # we try.
194 sys.path.insert(0, os.curdir)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000195 if TESTFN in sys.modules:
196 del sys.modules[TESTFN]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000197 try:
Collin Winter88e333d2010-03-17 03:09:21 +0000198 for i in [1, 2, 3]:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000199 self.assertRaises(ZeroDivisionError, __import__, TESTFN)
200 self.assertNotIn(TESTFN, sys.modules,
201 "damaged module in sys.modules on %i try" % i)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000202 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000203 del sys.path[0]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000204 remove_files(TESTFN)
205
Thomas Wouters89f507f2006-12-13 04:49:30 +0000206 def test_import_name_binding(self):
207 # import x.y.z binds x in the current namespace
208 import test as x
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000209 import test.support
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000210 self.assertTrue(x is test, x.__name__)
211 self.assertTrue(hasattr(test.support, "__file__"))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000212
213 # import x.y.z as w binds z as w
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000214 import test.support as y
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000215 self.assertTrue(y is test.support, y.__name__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000216
Christian Heimes13a7a212008-01-07 17:13:09 +0000217 def test_failing_reload(self):
218 # A failing reload should leave the module object in sys.modules.
Collin Winter88e333d2010-03-17 03:09:21 +0000219 source = TESTFN + os.extsep + "py"
Christian Heimes13a7a212008-01-07 17:13:09 +0000220 with open(source, "w") as f:
221 f.write("a = 1\nb=2\n")
222
223 sys.path.insert(0, os.curdir)
224 try:
225 mod = __import__(TESTFN)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000226 self.assertIn(TESTFN, sys.modules)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000227 self.assertEqual(mod.a, 1, "module has wrong attribute values")
228 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000229
230 # On WinXP, just replacing the .py file wasn't enough to
231 # convince reload() to reparse it. Maybe the timestamp didn't
232 # move enough. We force it to get reparsed by removing the
233 # compiled file too.
234 remove_files(TESTFN)
235
236 # Now damage the module.
237 with open(source, "w") as f:
238 f.write("a = 10\nb=20//0\n")
239
240 self.assertRaises(ZeroDivisionError, imp.reload, mod)
241 # But we still expect the module to be in sys.modules.
242 mod = sys.modules.get(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000243 self.assertIsNot(mod, None, "expected module to be in sys.modules")
Christian Heimes13a7a212008-01-07 17:13:09 +0000244
245 # We should have replaced a w/ 10, but the old b value should
246 # stick.
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000247 self.assertEqual(mod.a, 10, "module has wrong attribute values")
248 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000249
250 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000251 del sys.path[0]
Christian Heimes13a7a212008-01-07 17:13:09 +0000252 remove_files(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000253 unload(TESTFN)
Christian Heimes13a7a212008-01-07 17:13:09 +0000254
Christian Heimes3b06e532008-01-07 20:12:44 +0000255 def test_file_to_source(self):
256 # check if __file__ points to the source file where available
257 source = TESTFN + ".py"
258 with open(source, "w") as f:
259 f.write("test = None\n")
260
261 sys.path.insert(0, os.curdir)
262 try:
263 mod = __import__(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000264 self.assertTrue(mod.__file__.endswith('.py'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000265 os.remove(source)
266 del sys.modules[TESTFN]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000267 make_legacy_pyc(source)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100268 importlib.invalidate_caches()
Christian Heimes3b06e532008-01-07 20:12:44 +0000269 mod = __import__(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000270 base, ext = os.path.splitext(mod.__file__)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000271 self.assertIn(ext, ('.pyc', '.pyo'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000272 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000273 del sys.path[0]
Christian Heimes3b06e532008-01-07 20:12:44 +0000274 remove_files(TESTFN)
275 if TESTFN in sys.modules:
276 del sys.modules[TESTFN]
277
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000278 def test_import_name_binding(self):
279 # import x.y.z binds x in the current namespace.
280 import test as x
281 import test.support
282 self.assertIs(x, test, x.__name__)
283 self.assertTrue(hasattr(test.support, "__file__"))
284
285 # import x.y.z as w binds z as w.
286 import test.support as y
287 self.assertIs(y, test.support, y.__name__)
288
289 def test_import_initless_directory_warning(self):
290 with check_warnings(('', ImportWarning)):
291 # Just a random non-package directory we always expect to be
292 # somewhere in sys.path...
293 self.assertRaises(ImportError, __import__, "site-packages")
294
Collin Winter88e333d2010-03-17 03:09:21 +0000295 def test_import_by_filename(self):
Christian Heimes454f37b2008-01-10 00:10:02 +0000296 path = os.path.abspath(TESTFN)
Victor Stinner6c6f8512010-08-07 10:09:35 +0000297 encoding = sys.getfilesystemencoding()
298 try:
299 path.encode(encoding)
300 except UnicodeEncodeError:
301 self.skipTest('path is not encodable to {}'.format(encoding))
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000302 with self.assertRaises(ImportError) as c:
Christian Heimes454f37b2008-01-10 00:10:02 +0000303 __import__(path)
Christian Heimes454f37b2008-01-10 00:10:02 +0000304
R. David Murrayce4b1702010-12-14 23:06:25 +0000305 def test_import_in_del_does_not_crash(self):
306 # Issue 4236
307 testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\
308 import sys
309 class C:
310 def __del__(self):
311 import imp
312 sys.argv.insert(0, C())
313 """))
314 script_helper.assert_python_ok(testfn)
315
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100316 def test_timestamp_overflow(self):
317 # A modification timestamp larger than 2**32 should not be a problem
318 # when importing a module (issue #11235).
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100319 sys.path.insert(0, os.curdir)
320 try:
321 source = TESTFN + ".py"
322 compiled = imp.cache_from_source(source)
323 with open(source, 'w') as f:
324 pass
325 try:
Antoine Pitrou33d15f72012-01-25 18:01:45 +0100326 os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5))
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100327 except OverflowError:
328 self.skipTest("cannot set modification time to large integer")
Antoine Pitroudd21f682012-01-25 03:00:57 +0100329 except OSError as e:
330 if e.errno != getattr(errno, 'EOVERFLOW', None):
331 raise
332 self.skipTest("cannot set modification time to large integer ({})".format(e))
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100333 __import__(TESTFN)
334 # The pyc file was created.
335 os.stat(compiled)
336 finally:
337 del sys.path[0]
338 remove_files(TESTFN)
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100339
Brian Curtinb206a802012-04-16 00:10:17 -0500340 @unittest.skipUnless(sys.platform == "win32", "Windows specific")
341 def test_extension_import_fail(self):
342 # Issue 1559549 added `name` and `path` attributes to ImportError
343 # in order to provide better detail. Issue 10854 implemented those
344 # attributes on import failures of extensions on Windows.
345 debug = True if sys.executable[-6:] == "_d.exe" else False
346 pkg_name = "extension"
347 pkg_file = pkg_name + "{}".format("_d.pyd" if debug else ".pyd")
348 with open(pkg_file, "w"): pass
349 try:
350 with self.assertRaises(ImportError) as err:
351 import extension
352 self.assertEqual(err.exception.name, pkg_name)
353 # The path we get back has the dot-slash, e.g., ".\\extension.pyd"
354 self.assertEqual(os.path.relpath(err.exception.path), pkg_file)
355 finally:
356 unlink(pkg_file)
357
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000358
Collin Winter88e333d2010-03-17 03:09:21 +0000359class PycRewritingTests(unittest.TestCase):
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000360 # Test that the `co_filename` attribute on code objects always points
361 # to the right file, even when various things happen (e.g. both the .py
362 # and the .pyc file are renamed).
363
364 module_name = "unlikely_module_name"
365 module_source = """
366import sys
367code_filename = sys._getframe().f_code.co_filename
368module_filename = __file__
369constant = 1
370def func():
371 pass
372func_filename = func.__code__.co_filename
373"""
374 dir_name = os.path.abspath(TESTFN)
375 file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
Barry Warsaw28a691b2010-04-17 00:19:56 +0000376 compiled_name = imp.cache_from_source(file_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000377
378 def setUp(self):
379 self.sys_path = sys.path[:]
380 self.orig_module = sys.modules.pop(self.module_name, None)
381 os.mkdir(self.dir_name)
382 with open(self.file_name, "w") as f:
383 f.write(self.module_source)
384 sys.path.insert(0, self.dir_name)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100385 importlib.invalidate_caches()
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000386
387 def tearDown(self):
388 sys.path[:] = self.sys_path
389 if self.orig_module is not None:
390 sys.modules[self.module_name] = self.orig_module
391 else:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000392 unload(self.module_name)
393 unlink(self.file_name)
394 unlink(self.compiled_name)
Florent Xicluna27354cc2010-08-16 18:41:19 +0000395 rmtree(self.dir_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000396
397 def import_module(self):
398 ns = globals()
399 __import__(self.module_name, ns, ns)
400 return sys.modules[self.module_name]
401
402 def test_basics(self):
403 mod = self.import_module()
404 self.assertEqual(mod.module_filename, self.file_name)
405 self.assertEqual(mod.code_filename, self.file_name)
406 self.assertEqual(mod.func_filename, self.file_name)
407 del sys.modules[self.module_name]
408 mod = self.import_module()
409 self.assertEqual(mod.module_filename, self.file_name)
410 self.assertEqual(mod.code_filename, self.file_name)
411 self.assertEqual(mod.func_filename, self.file_name)
412
413 def test_incorrect_code_name(self):
414 py_compile.compile(self.file_name, dfile="another_module.py")
415 mod = self.import_module()
416 self.assertEqual(mod.module_filename, self.file_name)
417 self.assertEqual(mod.code_filename, self.file_name)
418 self.assertEqual(mod.func_filename, self.file_name)
419
420 def test_module_without_source(self):
421 target = "another_module.py"
422 py_compile.compile(self.file_name, dfile=target)
423 os.remove(self.file_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000424 pyc_file = make_legacy_pyc(self.file_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400425 importlib.invalidate_caches()
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000426 mod = self.import_module()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000427 self.assertEqual(mod.module_filename, pyc_file)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000428 self.assertEqual(mod.code_filename, target)
429 self.assertEqual(mod.func_filename, target)
430
431 def test_foreign_code(self):
432 py_compile.compile(self.file_name)
433 with open(self.compiled_name, "rb") as f:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100434 header = f.read(12)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000435 code = marshal.load(f)
436 constants = list(code.co_consts)
437 foreign_code = test_main.__code__
438 pos = constants.index(1)
439 constants[pos] = foreign_code
440 code = type(code)(code.co_argcount, code.co_kwonlyargcount,
441 code.co_nlocals, code.co_stacksize,
442 code.co_flags, code.co_code, tuple(constants),
443 code.co_names, code.co_varnames, code.co_filename,
444 code.co_name, code.co_firstlineno, code.co_lnotab,
445 code.co_freevars, code.co_cellvars)
446 with open(self.compiled_name, "wb") as f:
447 f.write(header)
448 marshal.dump(code, f)
449 mod = self.import_module()
450 self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
451
Collin Winter88e333d2010-03-17 03:09:21 +0000452
Christian Heimes204093a2007-11-01 22:37:07 +0000453class PathsTests(unittest.TestCase):
454 SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
455 'test\u00b0\u00b3\u00b2')
Christian Heimes90333392007-11-01 19:08:42 +0000456 path = TESTFN
457
458 def setUp(self):
459 os.mkdir(self.path)
460 self.syspath = sys.path[:]
461
462 def tearDown(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000463 rmtree(self.path)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000464 sys.path[:] = self.syspath
Christian Heimes90333392007-11-01 19:08:42 +0000465
Collin Winter88e333d2010-03-17 03:09:21 +0000466 # Regression test for http://bugs.python.org/issue1293.
Christian Heimes1d1a4002007-11-01 19:41:07 +0000467 def test_trailing_slash(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000468 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
469 f.write("testdata = 'test_trailing_slash'")
Christian Heimes1d1a4002007-11-01 19:41:07 +0000470 sys.path.append(self.path+'/')
471 mod = __import__("test_trailing_slash")
472 self.assertEqual(mod.testdata, 'test_trailing_slash')
473 unload("test_trailing_slash")
474
Collin Winter88e333d2010-03-17 03:09:21 +0000475 # Regression test for http://bugs.python.org/issue3677.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000476 def _test_UNC_path(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000477 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
478 f.write("testdata = 'test_trailing_slash'")
479 # Create the UNC path, like \\myhost\c$\foo\bar.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000480 path = os.path.abspath(self.path)
481 import socket
482 hn = socket.gethostname()
483 drive = path[0]
484 unc = "\\\\%s\\%s$"%(hn, drive)
485 unc += path[2:]
486 sys.path.append(path)
487 mod = __import__("test_trailing_slash")
488 self.assertEqual(mod.testdata, 'test_trailing_slash')
489 unload("test_trailing_slash")
490
491 if sys.platform == "win32":
492 test_UNC_path = _test_UNC_path
493
494
Collin Winter88e333d2010-03-17 03:09:21 +0000495class RelativeImportTests(unittest.TestCase):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000496
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000497 def tearDown(self):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000498 unload("test.relimport")
499 setUp = tearDown
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000500
501 def test_relimport_star(self):
502 # This will import * from .test_import.
503 from . import relimport
Collin Winter88e333d2010-03-17 03:09:21 +0000504 self.assertTrue(hasattr(relimport, "RelativeImportTests"))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000505
Georg Brandl2ee470f2008-07-16 12:55:28 +0000506 def test_issue3221(self):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000507 # Note for mergers: the 'absolute' tests from the 2.x branch
508 # are missing in Py3k because implicit relative imports are
509 # a thing of the past
Collin Winter88e333d2010-03-17 03:09:21 +0000510 #
511 # Regression test for http://bugs.python.org/issue3221.
Georg Brandl2ee470f2008-07-16 12:55:28 +0000512 def check_relative():
513 exec("from . import relimport", ns)
Collin Winter88e333d2010-03-17 03:09:21 +0000514
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000515 # Check relative import OK with __package__ and __name__ correct
Georg Brandl2ee470f2008-07-16 12:55:28 +0000516 ns = dict(__package__='test', __name__='test.notarealmodule')
517 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000518
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000519 # Check relative import OK with only __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000520 ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
521 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000522
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000523 # Check relative import fails with only __package__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000524 ns = dict(__package__='foo', __name__='test.notarealmodule')
525 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000526
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000527 # Check relative import fails with __package__ and __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000528 ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
529 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000530
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000531 # Check relative import fails with package set to a non-string
Georg Brandl2ee470f2008-07-16 12:55:28 +0000532 ns = dict(__package__=object())
Brett Cannonfd074152012-04-14 14:10:13 -0400533 self.assertRaises(TypeError, check_relative)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000534
Benjamin Peterson556d8002010-06-27 22:37:28 +0000535 def test_absolute_import_without_future(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000536 # If explicit relative import syntax is used, then do not try
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000537 # to perform an absolute import in the face of failure.
Benjamin Peterson556d8002010-06-27 22:37:28 +0000538 # Issue #7902.
Florent Xicluna27354cc2010-08-16 18:41:19 +0000539 with self.assertRaises(ImportError):
Benjamin Peterson556d8002010-06-27 22:37:28 +0000540 from .os import sep
Benjamin Peterson556d8002010-06-27 22:37:28 +0000541 self.fail("explicit relative import triggered an "
Florent Xicluna27354cc2010-08-16 18:41:19 +0000542 "implicit absolute import")
Collin Winter88e333d2010-03-17 03:09:21 +0000543
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000544
Collin Winter6498cff2010-03-17 03:14:31 +0000545class OverridingImportBuiltinTests(unittest.TestCase):
546 def test_override_builtin(self):
547 # Test that overriding builtins.__import__ can bypass sys.modules.
548 import os
549
550 def foo():
551 import os
552 return os
553 self.assertEqual(foo(), os) # Quick sanity check.
554
555 with swap_attr(builtins, "__import__", lambda *x: 5):
556 self.assertEqual(foo(), 5)
557
558 # Test what happens when we shadow __import__ in globals(); this
559 # currently does not impact the import process, but if this changes,
560 # other code will need to change, so keep this test as a tripwire.
561 with swap_item(globals(), "__import__", lambda *x: 5):
562 self.assertEqual(foo(), os)
563
564
Barry Warsaw28a691b2010-04-17 00:19:56 +0000565class PycacheTests(unittest.TestCase):
566 # Test the various PEP 3147 related behaviors.
567
568 tag = imp.get_tag()
569
570 def _clean(self):
571 forget(TESTFN)
572 rmtree('__pycache__')
573 unlink(self.source)
574
575 def setUp(self):
576 self.source = TESTFN + '.py'
577 self._clean()
578 with open(self.source, 'w') as fp:
579 print('# This is a test file written by test_import.py', file=fp)
580 sys.path.insert(0, os.curdir)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100581 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000582
583 def tearDown(self):
584 assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]'
585 del sys.path[0]
586 self._clean()
587
588 def test_import_pyc_path(self):
589 self.assertFalse(os.path.exists('__pycache__'))
590 __import__(TESTFN)
591 self.assertTrue(os.path.exists('__pycache__'))
592 self.assertTrue(os.path.exists(os.path.join(
Georg Brandlfb3c84a2010-10-14 07:24:28 +0000593 '__pycache__', '{}.{}.py{}'.format(
Georg Brandl1c2a7b72010-10-14 07:34:56 +0000594 TESTFN, self.tag, __debug__ and 'c' or 'o'))))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000595
596 @unittest.skipUnless(os.name == 'posix',
597 "test meaningful only on posix systems")
Charles-François Natali035018d2011-10-04 23:35:47 +0200598 @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
Charles-François Natali79164c82011-10-04 20:40:58 +0200599 "due to varying filesystem permission semantics (issue #11956)")
Barry Warsaw28a691b2010-04-17 00:19:56 +0000600 def test_unwritable_directory(self):
601 # When the umask causes the new __pycache__ directory to be
602 # unwritable, the import still succeeds but no .pyc file is written.
603 with temp_umask(0o222):
604 __import__(TESTFN)
605 self.assertTrue(os.path.exists('__pycache__'))
606 self.assertFalse(os.path.exists(os.path.join(
607 '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag))))
608
609 def test_missing_source(self):
610 # With PEP 3147 cache layout, removing the source but leaving the pyc
611 # file does not satisfy the import.
612 __import__(TESTFN)
613 pyc_file = imp.cache_from_source(self.source)
614 self.assertTrue(os.path.exists(pyc_file))
615 os.remove(self.source)
616 forget(TESTFN)
617 self.assertRaises(ImportError, __import__, TESTFN)
618
619 def test_missing_source_legacy(self):
620 # Like test_missing_source() except that for backward compatibility,
621 # when the pyc file lives where the py file would have been (and named
622 # without the tag), it is importable. The __file__ of the imported
623 # module is the pyc location.
624 __import__(TESTFN)
625 # pyc_file gets removed in _clean() via tearDown().
626 pyc_file = make_legacy_pyc(self.source)
627 os.remove(self.source)
628 unload(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100629 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000630 m = __import__(TESTFN)
631 self.assertEqual(m.__file__,
632 os.path.join(os.curdir, os.path.relpath(pyc_file)))
633
634 def test___cached__(self):
635 # Modules now also have an __cached__ that points to the pyc file.
636 m = __import__(TESTFN)
637 pyc_file = imp.cache_from_source(TESTFN + '.py')
638 self.assertEqual(m.__cached__, os.path.join(os.curdir, pyc_file))
639
640 def test___cached___legacy_pyc(self):
641 # Like test___cached__() except that for backward compatibility,
642 # when the pyc file lives where the py file would have been (and named
643 # without the tag), it is importable. The __cached__ of the imported
644 # module is the pyc location.
645 __import__(TESTFN)
646 # pyc_file gets removed in _clean() via tearDown().
647 pyc_file = make_legacy_pyc(self.source)
648 os.remove(self.source)
649 unload(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100650 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000651 m = __import__(TESTFN)
652 self.assertEqual(m.__cached__,
653 os.path.join(os.curdir, os.path.relpath(pyc_file)))
654
655 def test_package___cached__(self):
656 # Like test___cached__ but for packages.
657 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000658 rmtree('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000659 os.mkdir('pep3147')
660 self.addCleanup(cleanup)
661 # Touch the __init__.py
662 with open(os.path.join('pep3147', '__init__.py'), 'w'):
663 pass
664 with open(os.path.join('pep3147', 'foo.py'), 'w'):
665 pass
666 unload('pep3147.foo')
667 unload('pep3147')
Brett Cannonfd074152012-04-14 14:10:13 -0400668 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000669 m = __import__('pep3147.foo')
670 init_pyc = imp.cache_from_source(
671 os.path.join('pep3147', '__init__.py'))
672 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
673 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
674 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
675 os.path.join(os.curdir, foo_pyc))
676
677 def test_package___cached___from_pyc(self):
678 # Like test___cached__ but ensuring __cached__ when imported from a
679 # PEP 3147 pyc file.
680 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000681 rmtree('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000682 os.mkdir('pep3147')
683 self.addCleanup(cleanup)
684 unload('pep3147.foo')
685 unload('pep3147')
686 # Touch the __init__.py
687 with open(os.path.join('pep3147', '__init__.py'), 'w'):
688 pass
689 with open(os.path.join('pep3147', 'foo.py'), 'w'):
690 pass
Brett Cannonfd074152012-04-14 14:10:13 -0400691 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000692 m = __import__('pep3147.foo')
693 unload('pep3147.foo')
694 unload('pep3147')
Brett Cannonfd074152012-04-14 14:10:13 -0400695 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000696 m = __import__('pep3147.foo')
697 init_pyc = imp.cache_from_source(
698 os.path.join('pep3147', '__init__.py'))
699 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
700 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
701 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
702 os.path.join(os.curdir, foo_pyc))
703
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100704 def test_recompute_pyc_same_second(self):
705 # Even when the source file doesn't change timestamp, a change in
706 # source size is enough to trigger recomputation of the pyc file.
707 __import__(TESTFN)
708 unload(TESTFN)
709 with open(self.source, 'a') as fp:
710 print("x = 5", file=fp)
711 m = __import__(TESTFN)
712 self.assertEqual(m.x, 5)
713
Barry Warsaw28a691b2010-04-17 00:19:56 +0000714
Brett Cannon42e54b22010-07-23 14:45:19 +0000715class RelativeImportFromImportlibTests(test_relative_imports.RelativeImports):
Brett Cannon1f274792010-07-23 14:03:16 +0000716
717 def setUp(self):
718 self._importlib_util_flag = importlib_util.using___import__
719 importlib_util.using___import__ = True
720
721 def tearDown(self):
722 importlib_util.using___import__ = self._importlib_util_flag
723
724
Thomas Wouters89f507f2006-12-13 04:49:30 +0000725def test_main(verbose=None):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000726 run_unittest(ImportTests, PycacheTests,
727 PycRewritingTests, PathsTests, RelativeImportTests,
Brett Cannon1f274792010-07-23 14:03:16 +0000728 OverridingImportBuiltinTests,
Brett Cannon42e54b22010-07-23 14:45:19 +0000729 RelativeImportFromImportlibTests)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000730
Barry Warsaw28a691b2010-04-17 00:19:56 +0000731
Thomas Wouters89f507f2006-12-13 04:49:30 +0000732if __name__ == '__main__':
Collin Winter88e333d2010-03-17 03:09:21 +0000733 # Test needs to be a package, so we can do relative imports.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000734 from test.test_import import test_main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000735 test_main()