blob: 02f56e6217c8784e25cd263d541b32344d175994 [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 Pitroud35cbf62009-01-06 19:02:24 +00005import marshal
Collin Winter88e333d2010-03-17 03:09:21 +00006import os
7import py_compile
8import random
Collin Winter88e333d2010-03-17 03:09:21 +00009import stat
10import sys
11import unittest
Barry Warsaw28a691b2010-04-17 00:19:56 +000012
13from test.support import (
14 EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
15 make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
16 unlink, unload)
Guido van Rossumbd6f4fb2000-10-24 17:16:32 +000017
Tim Peters72f98e92001-05-08 15:19:57 +000018
Tim Peters08138fd2004-08-02 03:58:27 +000019def remove_files(name):
Skip Montanaro7a98be22007-08-16 14:35:24 +000020 for f in (name + ".py",
21 name + ".pyc",
22 name + ".pyo",
23 name + ".pyw",
Tim Peters08138fd2004-08-02 03:58:27 +000024 name + "$py.class"):
Florent Xicluna8fbddf12010-03-17 20:29:51 +000025 unlink(f)
Florent Xicluna27354cc2010-08-16 18:41:19 +000026 rmtree('__pycache__')
Tim Peters08138fd2004-08-02 03:58:27 +000027
Tim Petersc1731372001-08-04 08:12:36 +000028
Collin Winter88e333d2010-03-17 03:09:21 +000029class ImportTests(unittest.TestCase):
Tim Petersc1731372001-08-04 08:12:36 +000030
Florent Xicluna8fbddf12010-03-17 20:29:51 +000031 def tearDown(self):
32 unload(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +000033
Florent Xicluna8fbddf12010-03-17 20:29:51 +000034 setUp = tearDown
35
Collin Winter88e333d2010-03-17 03:09:21 +000036 def test_case_sensitivity(self):
37 # Brief digression to test that import is case-sensitive: if we got
38 # this far, we know for sure that "random" exists.
Benjamin Peterson1c87e292010-10-30 23:04:49 +000039 with self.assertRaises(ImportError):
Thomas Wouters89f507f2006-12-13 04:49:30 +000040 import RAnDoM
Tim Peters08138fd2004-08-02 03:58:27 +000041
Collin Winter88e333d2010-03-17 03:09:21 +000042 def test_double_const(self):
43 # Another brief digression to test the accuracy of manifest float
44 # constants.
Thomas Wouters89f507f2006-12-13 04:49:30 +000045 from test import double_const # don't blink -- that *was* the test
Tim Peters08138fd2004-08-02 03:58:27 +000046
Collin Winter88e333d2010-03-17 03:09:21 +000047 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000048 def test_with_extension(ext):
Collin Winter88e333d2010-03-17 03:09:21 +000049 # The extension is normally ".py", perhaps ".pyw".
Thomas Wouters89f507f2006-12-13 04:49:30 +000050 source = TESTFN + ext
Skip Montanaro7a98be22007-08-16 14:35:24 +000051 pyo = TESTFN + ".pyo"
Florent Xicluna8fbddf12010-03-17 20:29:51 +000052 if is_jython:
Thomas Wouters89f507f2006-12-13 04:49:30 +000053 pyc = TESTFN + "$py.class"
54 else:
Skip Montanaro7a98be22007-08-16 14:35:24 +000055 pyc = TESTFN + ".pyc"
Tim Peters08138fd2004-08-02 03:58:27 +000056
Benjamin Peterson16a1f632009-06-13 13:01:19 +000057 with open(source, "w") as f:
Barry Warsaw28a691b2010-04-17 00:19:56 +000058 print("# This tests Python's ability to import a",
59 ext, "file.", file=f)
Benjamin Peterson16a1f632009-06-13 13:01:19 +000060 a = random.randrange(1000)
61 b = random.randrange(1000)
62 print("a =", a, file=f)
63 print("b =", b, file=f)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064
Amaury Forgeot d'Arcdd9e3b82007-11-16 00:56:23 +000065 if TESTFN in sys.modules:
66 del sys.modules[TESTFN]
Thomas Wouters89f507f2006-12-13 04:49:30 +000067 try:
68 try:
69 mod = __import__(TESTFN)
Guido van Rossumb940e112007-01-10 16:19:56 +000070 except ImportError as err:
Thomas Wouters89f507f2006-12-13 04:49:30 +000071 self.fail("import from %s failed: %s" % (ext, err))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000072
Florent Xicluna8fbddf12010-03-17 20:29:51 +000073 self.assertEqual(mod.a, a,
Thomas Wouters89f507f2006-12-13 04:49:30 +000074 "module loaded (%s) but contents invalid" % mod)
Florent Xicluna8fbddf12010-03-17 20:29:51 +000075 self.assertEqual(mod.b, b,
Thomas Wouters89f507f2006-12-13 04:49:30 +000076 "module loaded (%s) but contents invalid" % mod)
77 finally:
Barry Warsaw28a691b2010-04-17 00:19:56 +000078 forget(TESTFN)
Guido van Rossume7ba4952007-06-06 23:52:48 +000079 unlink(source)
80 unlink(pyc)
81 unlink(pyo)
Thomas Wouters477c8d52006-05-27 19:21:47 +000082
Thomas Wouters89f507f2006-12-13 04:49:30 +000083 sys.path.insert(0, os.curdir)
84 try:
Skip Montanaro7a98be22007-08-16 14:35:24 +000085 test_with_extension(".py")
Thomas Wouters89f507f2006-12-13 04:49:30 +000086 if sys.platform.startswith("win"):
Collin Winter88e333d2010-03-17 03:09:21 +000087 for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
Thomas Wouters89f507f2006-12-13 04:49:30 +000088 test_with_extension(ext)
89 finally:
90 del sys.path[0]
Thomas Wouters477c8d52006-05-27 19:21:47 +000091
Barry Warsaw28a691b2010-04-17 00:19:56 +000092 @unittest.skipUnless(os.name == 'posix',
93 "test meaningful only on posix systems")
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +000094 def test_execute_bit_not_copied(self):
95 # Issue 6070: under posix .pyc files got their execute bit set if
96 # the .py file had the execute bit set, but they aren't executable.
Barry Warsaw28a691b2010-04-17 00:19:56 +000097 with temp_umask(0o022):
98 sys.path.insert(0, os.curdir)
99 try:
100 fname = TESTFN + os.extsep + "py"
Benjamin Peterson1a7127f2010-10-30 23:00:54 +0000101 open(fname, 'w').close()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000102 os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
103 stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
104 __import__(TESTFN)
105 fn = imp.cache_from_source(fname)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000106 if not os.path.exists(fn):
107 self.fail("__import__ did not result in creation of "
108 "either a .pyc or .pyo file")
Barry Warsaw28a691b2010-04-17 00:19:56 +0000109 s = os.stat(fn)
110 self.assertEqual(
111 stat.S_IMODE(s.st_mode),
112 stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
113 finally:
114 del sys.path[0]
115 remove_files(TESTFN)
116 unload(TESTFN)
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000117
Collin Winter88e333d2010-03-17 03:09:21 +0000118 def test_imp_module(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000119 # Verify that the imp module can correctly load and find .py files
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000120 # XXX (ncoghlan): It would be nice to use support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000121 # here, but that breaks because the os module registers some
122 # handlers in copy_reg on import. Since CleanImport doesn't
123 # revert that registration, the module is left in a broken
124 # state after reversion. Reinitialising the module contents
125 # and just reverting os.environ to its previous state is an OK
126 # workaround
127 orig_path = os.path
128 orig_getenv = os.getenv
129 with EnvironmentVarGuard():
130 x = imp.find_module("os")
Benjamin Petersone0487972010-10-30 23:06:57 +0000131 self.addCleanup(x[0].close)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000132 new_os = imp.load_module("os", *x)
133 self.assertIs(os, new_os)
134 self.assertIs(orig_path, new_os.path)
135 self.assertIsNot(orig_getenv, new_os.getenv)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000136
137 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('')
157
Brett Cannon93220d02010-05-15 22:20:16 +0000158 try:
Brett Cannon2cab50b2010-07-03 01:32:48 +0000159 make_legacy_pyc(filename)
Brett Cannon93220d02010-05-15 22:20:16 +0000160 # This used to crash.
161 exec('import ' + module)
162 finally:
163 # Cleanup.
164 del sys.path[-1]
165 unlink(filename + 'c')
166 unlink(filename + 'o')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000167
168 def test_failing_import_sticks(self):
Skip Montanaro7a98be22007-08-16 14:35:24 +0000169 source = TESTFN + ".py"
Collin Winter88e333d2010-03-17 03:09:21 +0000170 with open(source, "w") as f:
171 print("a = 1/0", file=f)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000172
173 # New in 2.4, we shouldn't be able to import that no matter how often
174 # we try.
175 sys.path.insert(0, os.curdir)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000176 if TESTFN in sys.modules:
177 del sys.modules[TESTFN]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000178 try:
Collin Winter88e333d2010-03-17 03:09:21 +0000179 for i in [1, 2, 3]:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000180 self.assertRaises(ZeroDivisionError, __import__, TESTFN)
181 self.assertNotIn(TESTFN, sys.modules,
182 "damaged module in sys.modules on %i try" % i)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000183 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000184 del sys.path[0]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000185 remove_files(TESTFN)
186
Thomas Wouters89f507f2006-12-13 04:49:30 +0000187 def test_import_name_binding(self):
188 # import x.y.z binds x in the current namespace
189 import test as x
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000190 import test.support
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000191 self.assertTrue(x is test, x.__name__)
192 self.assertTrue(hasattr(test.support, "__file__"))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000193
194 # import x.y.z as w binds z as w
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000195 import test.support as y
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000196 self.assertTrue(y is test.support, y.__name__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000197
Christian Heimes13a7a212008-01-07 17:13:09 +0000198 def test_failing_reload(self):
199 # A failing reload should leave the module object in sys.modules.
Collin Winter88e333d2010-03-17 03:09:21 +0000200 source = TESTFN + os.extsep + "py"
Christian Heimes13a7a212008-01-07 17:13:09 +0000201 with open(source, "w") as f:
202 f.write("a = 1\nb=2\n")
203
204 sys.path.insert(0, os.curdir)
205 try:
206 mod = __import__(TESTFN)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000207 self.assertIn(TESTFN, sys.modules)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000208 self.assertEqual(mod.a, 1, "module has wrong attribute values")
209 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000210
211 # On WinXP, just replacing the .py file wasn't enough to
212 # convince reload() to reparse it. Maybe the timestamp didn't
213 # move enough. We force it to get reparsed by removing the
214 # compiled file too.
215 remove_files(TESTFN)
216
217 # Now damage the module.
218 with open(source, "w") as f:
219 f.write("a = 10\nb=20//0\n")
220
221 self.assertRaises(ZeroDivisionError, imp.reload, mod)
222 # But we still expect the module to be in sys.modules.
223 mod = sys.modules.get(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000224 self.assertIsNot(mod, None, "expected module to be in sys.modules")
Christian Heimes13a7a212008-01-07 17:13:09 +0000225
226 # We should have replaced a w/ 10, but the old b value should
227 # stick.
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000228 self.assertEqual(mod.a, 10, "module has wrong attribute values")
229 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000230
231 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000232 del sys.path[0]
Christian Heimes13a7a212008-01-07 17:13:09 +0000233 remove_files(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000234 unload(TESTFN)
Christian Heimes13a7a212008-01-07 17:13:09 +0000235
Christian Heimes3b06e532008-01-07 20:12:44 +0000236 def test_file_to_source(self):
237 # check if __file__ points to the source file where available
238 source = TESTFN + ".py"
239 with open(source, "w") as f:
240 f.write("test = None\n")
241
242 sys.path.insert(0, os.curdir)
243 try:
244 mod = __import__(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000245 self.assertTrue(mod.__file__.endswith('.py'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000246 os.remove(source)
247 del sys.modules[TESTFN]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000248 make_legacy_pyc(source)
Christian Heimes3b06e532008-01-07 20:12:44 +0000249 mod = __import__(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000250 base, ext = os.path.splitext(mod.__file__)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000251 self.assertIn(ext, ('.pyc', '.pyo'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000252 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000253 del sys.path[0]
Christian Heimes3b06e532008-01-07 20:12:44 +0000254 remove_files(TESTFN)
255 if TESTFN in sys.modules:
256 del sys.modules[TESTFN]
257
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000258 def test_import_name_binding(self):
259 # import x.y.z binds x in the current namespace.
260 import test as x
261 import test.support
262 self.assertIs(x, test, x.__name__)
263 self.assertTrue(hasattr(test.support, "__file__"))
264
265 # import x.y.z as w binds z as w.
266 import test.support as y
267 self.assertIs(y, test.support, y.__name__)
268
269 def test_import_initless_directory_warning(self):
270 with check_warnings(('', ImportWarning)):
271 # Just a random non-package directory we always expect to be
272 # somewhere in sys.path...
273 self.assertRaises(ImportError, __import__, "site-packages")
274
Collin Winter88e333d2010-03-17 03:09:21 +0000275 def test_import_by_filename(self):
Christian Heimes454f37b2008-01-10 00:10:02 +0000276 path = os.path.abspath(TESTFN)
Victor Stinner6c6f8512010-08-07 10:09:35 +0000277 encoding = sys.getfilesystemencoding()
278 try:
279 path.encode(encoding)
280 except UnicodeEncodeError:
281 self.skipTest('path is not encodable to {}'.format(encoding))
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000282 with self.assertRaises(ImportError) as c:
Christian Heimes454f37b2008-01-10 00:10:02 +0000283 __import__(path)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000284 self.assertEqual("Import by filename is not supported.",
285 c.exception.args[0])
Christian Heimes454f37b2008-01-10 00:10:02 +0000286
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000287
Collin Winter88e333d2010-03-17 03:09:21 +0000288class PycRewritingTests(unittest.TestCase):
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000289 # Test that the `co_filename` attribute on code objects always points
290 # to the right file, even when various things happen (e.g. both the .py
291 # and the .pyc file are renamed).
292
293 module_name = "unlikely_module_name"
294 module_source = """
295import sys
296code_filename = sys._getframe().f_code.co_filename
297module_filename = __file__
298constant = 1
299def func():
300 pass
301func_filename = func.__code__.co_filename
302"""
303 dir_name = os.path.abspath(TESTFN)
304 file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
Barry Warsaw28a691b2010-04-17 00:19:56 +0000305 compiled_name = imp.cache_from_source(file_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000306
307 def setUp(self):
308 self.sys_path = sys.path[:]
309 self.orig_module = sys.modules.pop(self.module_name, None)
310 os.mkdir(self.dir_name)
311 with open(self.file_name, "w") as f:
312 f.write(self.module_source)
313 sys.path.insert(0, self.dir_name)
314
315 def tearDown(self):
316 sys.path[:] = self.sys_path
317 if self.orig_module is not None:
318 sys.modules[self.module_name] = self.orig_module
319 else:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000320 unload(self.module_name)
321 unlink(self.file_name)
322 unlink(self.compiled_name)
Florent Xicluna27354cc2010-08-16 18:41:19 +0000323 rmtree(self.dir_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000324
325 def import_module(self):
326 ns = globals()
327 __import__(self.module_name, ns, ns)
328 return sys.modules[self.module_name]
329
330 def test_basics(self):
331 mod = self.import_module()
332 self.assertEqual(mod.module_filename, self.file_name)
333 self.assertEqual(mod.code_filename, self.file_name)
334 self.assertEqual(mod.func_filename, self.file_name)
335 del sys.modules[self.module_name]
336 mod = self.import_module()
337 self.assertEqual(mod.module_filename, self.file_name)
338 self.assertEqual(mod.code_filename, self.file_name)
339 self.assertEqual(mod.func_filename, self.file_name)
340
341 def test_incorrect_code_name(self):
342 py_compile.compile(self.file_name, dfile="another_module.py")
343 mod = self.import_module()
344 self.assertEqual(mod.module_filename, self.file_name)
345 self.assertEqual(mod.code_filename, self.file_name)
346 self.assertEqual(mod.func_filename, self.file_name)
347
348 def test_module_without_source(self):
349 target = "another_module.py"
350 py_compile.compile(self.file_name, dfile=target)
351 os.remove(self.file_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000352 pyc_file = make_legacy_pyc(self.file_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000353 mod = self.import_module()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000354 self.assertEqual(mod.module_filename, pyc_file)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000355 self.assertEqual(mod.code_filename, target)
356 self.assertEqual(mod.func_filename, target)
357
358 def test_foreign_code(self):
359 py_compile.compile(self.file_name)
360 with open(self.compiled_name, "rb") as f:
361 header = f.read(8)
362 code = marshal.load(f)
363 constants = list(code.co_consts)
364 foreign_code = test_main.__code__
365 pos = constants.index(1)
366 constants[pos] = foreign_code
367 code = type(code)(code.co_argcount, code.co_kwonlyargcount,
368 code.co_nlocals, code.co_stacksize,
369 code.co_flags, code.co_code, tuple(constants),
370 code.co_names, code.co_varnames, code.co_filename,
371 code.co_name, code.co_firstlineno, code.co_lnotab,
372 code.co_freevars, code.co_cellvars)
373 with open(self.compiled_name, "wb") as f:
374 f.write(header)
375 marshal.dump(code, f)
376 mod = self.import_module()
377 self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
378
Collin Winter88e333d2010-03-17 03:09:21 +0000379
Christian Heimes204093a2007-11-01 22:37:07 +0000380class PathsTests(unittest.TestCase):
381 SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
382 'test\u00b0\u00b3\u00b2')
Christian Heimes90333392007-11-01 19:08:42 +0000383 path = TESTFN
384
385 def setUp(self):
386 os.mkdir(self.path)
387 self.syspath = sys.path[:]
388
389 def tearDown(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000390 rmtree(self.path)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000391 sys.path[:] = self.syspath
Christian Heimes90333392007-11-01 19:08:42 +0000392
Collin Winter88e333d2010-03-17 03:09:21 +0000393 # Regression test for http://bugs.python.org/issue1293.
Christian Heimes1d1a4002007-11-01 19:41:07 +0000394 def test_trailing_slash(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000395 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
396 f.write("testdata = 'test_trailing_slash'")
Christian Heimes1d1a4002007-11-01 19:41:07 +0000397 sys.path.append(self.path+'/')
398 mod = __import__("test_trailing_slash")
399 self.assertEqual(mod.testdata, 'test_trailing_slash')
400 unload("test_trailing_slash")
401
Collin Winter88e333d2010-03-17 03:09:21 +0000402 # Regression test for http://bugs.python.org/issue3677.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000403 def _test_UNC_path(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000404 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
405 f.write("testdata = 'test_trailing_slash'")
406 # Create the UNC path, like \\myhost\c$\foo\bar.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000407 path = os.path.abspath(self.path)
408 import socket
409 hn = socket.gethostname()
410 drive = path[0]
411 unc = "\\\\%s\\%s$"%(hn, drive)
412 unc += path[2:]
413 sys.path.append(path)
414 mod = __import__("test_trailing_slash")
415 self.assertEqual(mod.testdata, 'test_trailing_slash')
416 unload("test_trailing_slash")
417
418 if sys.platform == "win32":
419 test_UNC_path = _test_UNC_path
420
421
Collin Winter88e333d2010-03-17 03:09:21 +0000422class RelativeImportTests(unittest.TestCase):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000423
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000424 def tearDown(self):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000425 unload("test.relimport")
426 setUp = tearDown
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000427
428 def test_relimport_star(self):
429 # This will import * from .test_import.
430 from . import relimport
Collin Winter88e333d2010-03-17 03:09:21 +0000431 self.assertTrue(hasattr(relimport, "RelativeImportTests"))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000432
Georg Brandl2ee470f2008-07-16 12:55:28 +0000433 def test_issue3221(self):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000434 # Note for mergers: the 'absolute' tests from the 2.x branch
435 # are missing in Py3k because implicit relative imports are
436 # a thing of the past
Collin Winter88e333d2010-03-17 03:09:21 +0000437 #
438 # Regression test for http://bugs.python.org/issue3221.
Georg Brandl2ee470f2008-07-16 12:55:28 +0000439 def check_relative():
440 exec("from . import relimport", ns)
Collin Winter88e333d2010-03-17 03:09:21 +0000441
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000442 # Check relative import OK with __package__ and __name__ correct
Georg Brandl2ee470f2008-07-16 12:55:28 +0000443 ns = dict(__package__='test', __name__='test.notarealmodule')
444 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000445
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000446 # Check relative import OK with only __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000447 ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
448 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000449
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000450 # Check relative import fails with only __package__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000451 ns = dict(__package__='foo', __name__='test.notarealmodule')
452 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000453
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000454 # Check relative import fails with __package__ and __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000455 ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
456 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000457
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000458 # Check relative import fails with package set to a non-string
Georg Brandl2ee470f2008-07-16 12:55:28 +0000459 ns = dict(__package__=object())
460 self.assertRaises(ValueError, check_relative)
461
Benjamin Peterson556d8002010-06-27 22:37:28 +0000462 def test_absolute_import_without_future(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000463 # If explicit relative import syntax is used, then do not try
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000464 # to perform an absolute import in the face of failure.
Benjamin Peterson556d8002010-06-27 22:37:28 +0000465 # Issue #7902.
Florent Xicluna27354cc2010-08-16 18:41:19 +0000466 with self.assertRaises(ImportError):
Benjamin Peterson556d8002010-06-27 22:37:28 +0000467 from .os import sep
Benjamin Peterson556d8002010-06-27 22:37:28 +0000468 self.fail("explicit relative import triggered an "
Florent Xicluna27354cc2010-08-16 18:41:19 +0000469 "implicit absolute import")
Collin Winter88e333d2010-03-17 03:09:21 +0000470
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000471
Collin Winter6498cff2010-03-17 03:14:31 +0000472class OverridingImportBuiltinTests(unittest.TestCase):
473 def test_override_builtin(self):
474 # Test that overriding builtins.__import__ can bypass sys.modules.
475 import os
476
477 def foo():
478 import os
479 return os
480 self.assertEqual(foo(), os) # Quick sanity check.
481
482 with swap_attr(builtins, "__import__", lambda *x: 5):
483 self.assertEqual(foo(), 5)
484
485 # Test what happens when we shadow __import__ in globals(); this
486 # currently does not impact the import process, but if this changes,
487 # other code will need to change, so keep this test as a tripwire.
488 with swap_item(globals(), "__import__", lambda *x: 5):
489 self.assertEqual(foo(), os)
490
491
Barry Warsaw28a691b2010-04-17 00:19:56 +0000492class PycacheTests(unittest.TestCase):
493 # Test the various PEP 3147 related behaviors.
494
495 tag = imp.get_tag()
496
497 def _clean(self):
498 forget(TESTFN)
499 rmtree('__pycache__')
500 unlink(self.source)
501
502 def setUp(self):
503 self.source = TESTFN + '.py'
504 self._clean()
505 with open(self.source, 'w') as fp:
506 print('# This is a test file written by test_import.py', file=fp)
507 sys.path.insert(0, os.curdir)
508
509 def tearDown(self):
510 assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]'
511 del sys.path[0]
512 self._clean()
513
514 def test_import_pyc_path(self):
515 self.assertFalse(os.path.exists('__pycache__'))
516 __import__(TESTFN)
517 self.assertTrue(os.path.exists('__pycache__'))
518 self.assertTrue(os.path.exists(os.path.join(
Georg Brandlfb3c84a2010-10-14 07:24:28 +0000519 '__pycache__', '{}.{}.py{}'.format(
Georg Brandl1c2a7b72010-10-14 07:34:56 +0000520 TESTFN, self.tag, __debug__ and 'c' or 'o'))))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000521
522 @unittest.skipUnless(os.name == 'posix',
523 "test meaningful only on posix systems")
524 def test_unwritable_directory(self):
525 # When the umask causes the new __pycache__ directory to be
526 # unwritable, the import still succeeds but no .pyc file is written.
527 with temp_umask(0o222):
528 __import__(TESTFN)
529 self.assertTrue(os.path.exists('__pycache__'))
530 self.assertFalse(os.path.exists(os.path.join(
531 '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag))))
532
533 def test_missing_source(self):
534 # With PEP 3147 cache layout, removing the source but leaving the pyc
535 # file does not satisfy the import.
536 __import__(TESTFN)
537 pyc_file = imp.cache_from_source(self.source)
538 self.assertTrue(os.path.exists(pyc_file))
539 os.remove(self.source)
540 forget(TESTFN)
541 self.assertRaises(ImportError, __import__, TESTFN)
542
543 def test_missing_source_legacy(self):
544 # Like test_missing_source() except that for backward compatibility,
545 # when the pyc file lives where the py file would have been (and named
546 # without the tag), it is importable. The __file__ of the imported
547 # module is the pyc location.
548 __import__(TESTFN)
549 # pyc_file gets removed in _clean() via tearDown().
550 pyc_file = make_legacy_pyc(self.source)
551 os.remove(self.source)
552 unload(TESTFN)
553 m = __import__(TESTFN)
554 self.assertEqual(m.__file__,
555 os.path.join(os.curdir, os.path.relpath(pyc_file)))
556
557 def test___cached__(self):
558 # Modules now also have an __cached__ that points to the pyc file.
559 m = __import__(TESTFN)
560 pyc_file = imp.cache_from_source(TESTFN + '.py')
561 self.assertEqual(m.__cached__, os.path.join(os.curdir, pyc_file))
562
563 def test___cached___legacy_pyc(self):
564 # Like test___cached__() except that for backward compatibility,
565 # when the pyc file lives where the py file would have been (and named
566 # without the tag), it is importable. The __cached__ of the imported
567 # module is the pyc location.
568 __import__(TESTFN)
569 # pyc_file gets removed in _clean() via tearDown().
570 pyc_file = make_legacy_pyc(self.source)
571 os.remove(self.source)
572 unload(TESTFN)
573 m = __import__(TESTFN)
574 self.assertEqual(m.__cached__,
575 os.path.join(os.curdir, os.path.relpath(pyc_file)))
576
577 def test_package___cached__(self):
578 # Like test___cached__ but for packages.
579 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000580 rmtree('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000581 os.mkdir('pep3147')
582 self.addCleanup(cleanup)
583 # Touch the __init__.py
584 with open(os.path.join('pep3147', '__init__.py'), 'w'):
585 pass
586 with open(os.path.join('pep3147', 'foo.py'), 'w'):
587 pass
588 unload('pep3147.foo')
589 unload('pep3147')
590 m = __import__('pep3147.foo')
591 init_pyc = imp.cache_from_source(
592 os.path.join('pep3147', '__init__.py'))
593 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
594 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
595 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
596 os.path.join(os.curdir, foo_pyc))
597
598 def test_package___cached___from_pyc(self):
599 # Like test___cached__ but ensuring __cached__ when imported from a
600 # PEP 3147 pyc file.
601 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000602 rmtree('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000603 os.mkdir('pep3147')
604 self.addCleanup(cleanup)
605 unload('pep3147.foo')
606 unload('pep3147')
607 # Touch the __init__.py
608 with open(os.path.join('pep3147', '__init__.py'), 'w'):
609 pass
610 with open(os.path.join('pep3147', 'foo.py'), 'w'):
611 pass
612 m = __import__('pep3147.foo')
613 unload('pep3147.foo')
614 unload('pep3147')
615 m = __import__('pep3147.foo')
616 init_pyc = imp.cache_from_source(
617 os.path.join('pep3147', '__init__.py'))
618 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
619 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
620 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
621 os.path.join(os.curdir, foo_pyc))
622
623
Brett Cannon42e54b22010-07-23 14:45:19 +0000624class RelativeImportFromImportlibTests(test_relative_imports.RelativeImports):
Brett Cannon1f274792010-07-23 14:03:16 +0000625
626 def setUp(self):
627 self._importlib_util_flag = importlib_util.using___import__
628 importlib_util.using___import__ = True
629
630 def tearDown(self):
631 importlib_util.using___import__ = self._importlib_util_flag
632
633
Thomas Wouters89f507f2006-12-13 04:49:30 +0000634def test_main(verbose=None):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000635 run_unittest(ImportTests, PycacheTests,
636 PycRewritingTests, PathsTests, RelativeImportTests,
Brett Cannon1f274792010-07-23 14:03:16 +0000637 OverridingImportBuiltinTests,
Brett Cannon42e54b22010-07-23 14:45:19 +0000638 RelativeImportFromImportlibTests)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000639
Barry Warsaw28a691b2010-04-17 00:19:56 +0000640
Thomas Wouters89f507f2006-12-13 04:49:30 +0000641if __name__ == '__main__':
Collin Winter88e333d2010-03-17 03:09:21 +0000642 # Test needs to be a package, so we can do relative imports.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000643 from test.test_import import test_main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000644 test_main()