blob: be82b2223be6e34a43f709970f290a93c2e24edf [file] [log] [blame]
Collin Winter6498cff2010-03-17 03:14:31 +00001import builtins
Barry Warsaw28a691b2010-04-17 00:19:56 +00002import errno
Christian Heimes13a7a212008-01-07 17:13:09 +00003import imp
Brett Cannon1f274792010-07-23 14:03:16 +00004from importlib.test.import_ import test_relative_imports
5from importlib.test.import_ import util as importlib_util
Antoine Pitroud35cbf62009-01-06 19:02:24 +00006import marshal
Collin Winter88e333d2010-03-17 03:09:21 +00007import os
8import py_compile
9import random
10import shutil
11import stat
12import sys
13import unittest
Barry Warsaw28a691b2010-04-17 00:19:56 +000014
15from test.support import (
16 EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
17 make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
18 unlink, unload)
Guido van Rossumbd6f4fb2000-10-24 17:16:32 +000019
Tim Peters72f98e92001-05-08 15:19:57 +000020
Tim Peters08138fd2004-08-02 03:58:27 +000021def remove_files(name):
Skip Montanaro7a98be22007-08-16 14:35:24 +000022 for f in (name + ".py",
23 name + ".pyc",
24 name + ".pyo",
25 name + ".pyw",
Tim Peters08138fd2004-08-02 03:58:27 +000026 name + "$py.class"):
Florent Xicluna8fbddf12010-03-17 20:29:51 +000027 unlink(f)
Barry Warsaw28a691b2010-04-17 00:19:56 +000028 try:
29 shutil.rmtree('__pycache__')
30 except OSError as error:
31 if error.errno != errno.ENOENT:
32 raise
Tim Peters08138fd2004-08-02 03:58:27 +000033
Tim Petersc1731372001-08-04 08:12:36 +000034
Collin Winter88e333d2010-03-17 03:09:21 +000035class ImportTests(unittest.TestCase):
Tim Petersc1731372001-08-04 08:12:36 +000036
Florent Xicluna8fbddf12010-03-17 20:29:51 +000037 def tearDown(self):
38 unload(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +000039
Florent Xicluna8fbddf12010-03-17 20:29:51 +000040 setUp = tearDown
41
Collin Winter88e333d2010-03-17 03:09:21 +000042 def test_case_sensitivity(self):
43 # Brief digression to test that import is case-sensitive: if we got
44 # this far, we know for sure that "random" exists.
Tim Petersc1731372001-08-04 08:12:36 +000045 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +000046 import RAnDoM
47 except ImportError:
Tim Peters08138fd2004-08-02 03:58:27 +000048 pass
49 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +000050 self.fail("import of RAnDoM should have failed (case mismatch)")
Tim Peters08138fd2004-08-02 03:58:27 +000051
Collin Winter88e333d2010-03-17 03:09:21 +000052 def test_double_const(self):
53 # Another brief digression to test the accuracy of manifest float
54 # constants.
Thomas Wouters89f507f2006-12-13 04:49:30 +000055 from test import double_const # don't blink -- that *was* the test
Tim Peters08138fd2004-08-02 03:58:27 +000056
Collin Winter88e333d2010-03-17 03:09:21 +000057 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000058 def test_with_extension(ext):
Collin Winter88e333d2010-03-17 03:09:21 +000059 # The extension is normally ".py", perhaps ".pyw".
Thomas Wouters89f507f2006-12-13 04:49:30 +000060 source = TESTFN + ext
Skip Montanaro7a98be22007-08-16 14:35:24 +000061 pyo = TESTFN + ".pyo"
Florent Xicluna8fbddf12010-03-17 20:29:51 +000062 if is_jython:
Thomas Wouters89f507f2006-12-13 04:49:30 +000063 pyc = TESTFN + "$py.class"
64 else:
Skip Montanaro7a98be22007-08-16 14:35:24 +000065 pyc = TESTFN + ".pyc"
Tim Peters08138fd2004-08-02 03:58:27 +000066
Benjamin Peterson16a1f632009-06-13 13:01:19 +000067 with open(source, "w") as f:
Barry Warsaw28a691b2010-04-17 00:19:56 +000068 print("# This tests Python's ability to import a",
69 ext, "file.", file=f)
Benjamin Peterson16a1f632009-06-13 13:01:19 +000070 a = random.randrange(1000)
71 b = random.randrange(1000)
72 print("a =", a, file=f)
73 print("b =", b, file=f)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074
Amaury Forgeot d'Arcdd9e3b82007-11-16 00:56:23 +000075 if TESTFN in sys.modules:
76 del sys.modules[TESTFN]
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")
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000104 def test_execute_bit_not_copied(self):
105 # Issue 6070: under posix .pyc files got their execute bit set if
106 # the .py file had the execute bit set, but they aren't executable.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000107 with temp_umask(0o022):
108 sys.path.insert(0, os.curdir)
109 try:
110 fname = TESTFN + os.extsep + "py"
111 f = open(fname, 'w').close()
112 os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
113 stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
114 __import__(TESTFN)
115 fn = imp.cache_from_source(fname)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000116 if not os.path.exists(fn):
117 self.fail("__import__ did not result in creation of "
118 "either a .pyc or .pyo file")
Barry Warsaw28a691b2010-04-17 00:19:56 +0000119 s = os.stat(fn)
120 self.assertEqual(
121 stat.S_IMODE(s.st_mode),
122 stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
123 finally:
124 del sys.path[0]
125 remove_files(TESTFN)
126 unload(TESTFN)
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000127
Collin Winter88e333d2010-03-17 03:09:21 +0000128 def test_imp_module(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000129 # Verify that the imp module can correctly load and find .py files
Nick Coghlan6ead5522009-10-18 13:19:33 +0000130 import imp, os
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000131 # XXX (ncoghlan): It would be nice to use support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000132 # here, but that breaks because the os module registers some
133 # handlers in copy_reg on import. Since CleanImport doesn't
134 # revert that registration, the module is left in a broken
135 # state after reversion. Reinitialising the module contents
136 # and just reverting os.environ to its previous state is an OK
137 # workaround
138 orig_path = os.path
139 orig_getenv = os.getenv
140 with EnvironmentVarGuard():
141 x = imp.find_module("os")
142 new_os = imp.load_module("os", *x)
143 self.assertIs(os, new_os)
144 self.assertIs(orig_path, new_os.path)
145 self.assertIsNot(orig_getenv, new_os.getenv)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000146
147 def test_module_with_large_stack(self, module='longlist'):
Collin Winter88e333d2010-03-17 03:09:21 +0000148 # Regression test for http://bugs.python.org/issue561858.
Skip Montanaro7a98be22007-08-16 14:35:24 +0000149 filename = module + '.py'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000150
Collin Winter88e333d2010-03-17 03:09:21 +0000151 # Create a file with a list of 65000 elements.
Brett Cannon2cab50b2010-07-03 01:32:48 +0000152 with open(filename, 'w') as f:
Collin Winter88e333d2010-03-17 03:09:21 +0000153 f.write('d = [\n')
154 for i in range(65000):
155 f.write('"",\n')
156 f.write(']')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000157
Brett Cannon2cab50b2010-07-03 01:32:48 +0000158 try:
159 # Compile & remove .py file; we only need .pyc (or .pyo).
160 # Bytecode must be relocated from the PEP 3147 bytecode-only location.
161 py_compile.compile(filename)
162 finally:
163 unlink(filename)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000164
Collin Winter88e333d2010-03-17 03:09:21 +0000165 # Need to be able to load from current dir.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000166 sys.path.append('')
167
Brett Cannon93220d02010-05-15 22:20:16 +0000168 try:
Brett Cannon2cab50b2010-07-03 01:32:48 +0000169 make_legacy_pyc(filename)
Brett Cannon93220d02010-05-15 22:20:16 +0000170 # This used to crash.
171 exec('import ' + module)
172 finally:
173 # Cleanup.
174 del sys.path[-1]
175 unlink(filename + 'c')
176 unlink(filename + 'o')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177
178 def test_failing_import_sticks(self):
Skip Montanaro7a98be22007-08-16 14:35:24 +0000179 source = TESTFN + ".py"
Collin Winter88e333d2010-03-17 03:09:21 +0000180 with open(source, "w") as f:
181 print("a = 1/0", file=f)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000182
183 # New in 2.4, we shouldn't be able to import that no matter how often
184 # we try.
185 sys.path.insert(0, os.curdir)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000186 if TESTFN in sys.modules:
187 del sys.modules[TESTFN]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188 try:
Collin Winter88e333d2010-03-17 03:09:21 +0000189 for i in [1, 2, 3]:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000190 self.assertRaises(ZeroDivisionError, __import__, TESTFN)
191 self.assertNotIn(TESTFN, sys.modules,
192 "damaged module in sys.modules on %i try" % i)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000193 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000194 del sys.path[0]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000195 remove_files(TESTFN)
196
Thomas Wouters89f507f2006-12-13 04:49:30 +0000197 def test_import_name_binding(self):
198 # import x.y.z binds x in the current namespace
199 import test as x
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000200 import test.support
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000201 self.assertTrue(x is test, x.__name__)
202 self.assertTrue(hasattr(test.support, "__file__"))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000203
204 # import x.y.z as w binds z as w
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000205 import test.support as y
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000206 self.assertTrue(y is test.support, y.__name__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000207
208 def test_import_initless_directory_warning(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000209 with warnings.catch_warnings():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000210 # Just a random non-package directory we always expect to be
211 # somewhere in sys.path...
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000212 warnings.simplefilter('error', ImportWarning)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000213 self.assertRaises(ImportWarning, __import__, "site-packages")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000214
Christian Heimes13a7a212008-01-07 17:13:09 +0000215 def test_failing_reload(self):
216 # A failing reload should leave the module object in sys.modules.
Collin Winter88e333d2010-03-17 03:09:21 +0000217 source = TESTFN + os.extsep + "py"
Christian Heimes13a7a212008-01-07 17:13:09 +0000218 with open(source, "w") as f:
219 f.write("a = 1\nb=2\n")
220
221 sys.path.insert(0, os.curdir)
222 try:
223 mod = __import__(TESTFN)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000224 self.assertIn(TESTFN, sys.modules)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000225 self.assertEqual(mod.a, 1, "module has wrong attribute values")
226 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000227
228 # On WinXP, just replacing the .py file wasn't enough to
229 # convince reload() to reparse it. Maybe the timestamp didn't
230 # move enough. We force it to get reparsed by removing the
231 # compiled file too.
232 remove_files(TESTFN)
233
234 # Now damage the module.
235 with open(source, "w") as f:
236 f.write("a = 10\nb=20//0\n")
237
238 self.assertRaises(ZeroDivisionError, imp.reload, mod)
239 # But we still expect the module to be in sys.modules.
240 mod = sys.modules.get(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000241 self.assertIsNot(mod, None, "expected module to be in sys.modules")
Christian Heimes13a7a212008-01-07 17:13:09 +0000242
243 # We should have replaced a w/ 10, but the old b value should
244 # stick.
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000245 self.assertEqual(mod.a, 10, "module has wrong attribute values")
246 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000247
248 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000249 del sys.path[0]
Christian Heimes13a7a212008-01-07 17:13:09 +0000250 remove_files(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000251 unload(TESTFN)
Christian Heimes13a7a212008-01-07 17:13:09 +0000252
Christian Heimes3b06e532008-01-07 20:12:44 +0000253 def test_file_to_source(self):
254 # check if __file__ points to the source file where available
255 source = TESTFN + ".py"
256 with open(source, "w") as f:
257 f.write("test = None\n")
258
259 sys.path.insert(0, os.curdir)
260 try:
261 mod = __import__(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000262 self.assertTrue(mod.__file__.endswith('.py'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000263 os.remove(source)
264 del sys.modules[TESTFN]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000265 make_legacy_pyc(source)
Christian Heimes3b06e532008-01-07 20:12:44 +0000266 mod = __import__(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000267 base, ext = os.path.splitext(mod.__file__)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000268 self.assertIn(ext, ('.pyc', '.pyo'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000269 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000270 del sys.path[0]
Christian Heimes3b06e532008-01-07 20:12:44 +0000271 remove_files(TESTFN)
272 if TESTFN in sys.modules:
273 del sys.modules[TESTFN]
274
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000275 def test_import_name_binding(self):
276 # import x.y.z binds x in the current namespace.
277 import test as x
278 import test.support
279 self.assertIs(x, test, x.__name__)
280 self.assertTrue(hasattr(test.support, "__file__"))
281
282 # import x.y.z as w binds z as w.
283 import test.support as y
284 self.assertIs(y, test.support, y.__name__)
285
286 def test_import_initless_directory_warning(self):
287 with check_warnings(('', ImportWarning)):
288 # Just a random non-package directory we always expect to be
289 # somewhere in sys.path...
290 self.assertRaises(ImportError, __import__, "site-packages")
291
Collin Winter88e333d2010-03-17 03:09:21 +0000292 def test_import_by_filename(self):
Christian Heimes454f37b2008-01-10 00:10:02 +0000293 path = os.path.abspath(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000294 with self.assertRaises(ImportError) as c:
Christian Heimes454f37b2008-01-10 00:10:02 +0000295 __import__(path)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000296 self.assertEqual("Import by filename is not supported.",
297 c.exception.args[0])
Christian Heimes454f37b2008-01-10 00:10:02 +0000298
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000299
Collin Winter88e333d2010-03-17 03:09:21 +0000300class PycRewritingTests(unittest.TestCase):
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000301 # Test that the `co_filename` attribute on code objects always points
302 # to the right file, even when various things happen (e.g. both the .py
303 # and the .pyc file are renamed).
304
305 module_name = "unlikely_module_name"
306 module_source = """
307import sys
308code_filename = sys._getframe().f_code.co_filename
309module_filename = __file__
310constant = 1
311def func():
312 pass
313func_filename = func.__code__.co_filename
314"""
315 dir_name = os.path.abspath(TESTFN)
316 file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
Barry Warsaw28a691b2010-04-17 00:19:56 +0000317 compiled_name = imp.cache_from_source(file_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000318
319 def setUp(self):
320 self.sys_path = sys.path[:]
321 self.orig_module = sys.modules.pop(self.module_name, None)
322 os.mkdir(self.dir_name)
323 with open(self.file_name, "w") as f:
324 f.write(self.module_source)
325 sys.path.insert(0, self.dir_name)
326
327 def tearDown(self):
328 sys.path[:] = self.sys_path
329 if self.orig_module is not None:
330 sys.modules[self.module_name] = self.orig_module
331 else:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000332 unload(self.module_name)
333 unlink(self.file_name)
334 unlink(self.compiled_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000335 if os.path.exists(self.dir_name):
336 shutil.rmtree(self.dir_name)
337
338 def import_module(self):
339 ns = globals()
340 __import__(self.module_name, ns, ns)
341 return sys.modules[self.module_name]
342
343 def test_basics(self):
344 mod = self.import_module()
345 self.assertEqual(mod.module_filename, self.file_name)
346 self.assertEqual(mod.code_filename, self.file_name)
347 self.assertEqual(mod.func_filename, self.file_name)
348 del sys.modules[self.module_name]
349 mod = self.import_module()
350 self.assertEqual(mod.module_filename, self.file_name)
351 self.assertEqual(mod.code_filename, self.file_name)
352 self.assertEqual(mod.func_filename, self.file_name)
353
354 def test_incorrect_code_name(self):
355 py_compile.compile(self.file_name, dfile="another_module.py")
356 mod = self.import_module()
357 self.assertEqual(mod.module_filename, self.file_name)
358 self.assertEqual(mod.code_filename, self.file_name)
359 self.assertEqual(mod.func_filename, self.file_name)
360
361 def test_module_without_source(self):
362 target = "another_module.py"
363 py_compile.compile(self.file_name, dfile=target)
364 os.remove(self.file_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000365 pyc_file = make_legacy_pyc(self.file_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000366 mod = self.import_module()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000367 self.assertEqual(mod.module_filename, pyc_file)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000368 self.assertEqual(mod.code_filename, target)
369 self.assertEqual(mod.func_filename, target)
370
371 def test_foreign_code(self):
372 py_compile.compile(self.file_name)
373 with open(self.compiled_name, "rb") as f:
374 header = f.read(8)
375 code = marshal.load(f)
376 constants = list(code.co_consts)
377 foreign_code = test_main.__code__
378 pos = constants.index(1)
379 constants[pos] = foreign_code
380 code = type(code)(code.co_argcount, code.co_kwonlyargcount,
381 code.co_nlocals, code.co_stacksize,
382 code.co_flags, code.co_code, tuple(constants),
383 code.co_names, code.co_varnames, code.co_filename,
384 code.co_name, code.co_firstlineno, code.co_lnotab,
385 code.co_freevars, code.co_cellvars)
386 with open(self.compiled_name, "wb") as f:
387 f.write(header)
388 marshal.dump(code, f)
389 mod = self.import_module()
390 self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
391
Collin Winter88e333d2010-03-17 03:09:21 +0000392
Christian Heimes204093a2007-11-01 22:37:07 +0000393class PathsTests(unittest.TestCase):
394 SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
395 'test\u00b0\u00b3\u00b2')
Christian Heimes90333392007-11-01 19:08:42 +0000396 path = TESTFN
397
398 def setUp(self):
399 os.mkdir(self.path)
400 self.syspath = sys.path[:]
401
402 def tearDown(self):
403 shutil.rmtree(self.path)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000404 sys.path[:] = self.syspath
Christian Heimes90333392007-11-01 19:08:42 +0000405
Collin Winter88e333d2010-03-17 03:09:21 +0000406 # Regression test for http://bugs.python.org/issue1293.
Christian Heimes1d1a4002007-11-01 19:41:07 +0000407 def test_trailing_slash(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000408 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
409 f.write("testdata = 'test_trailing_slash'")
Christian Heimes1d1a4002007-11-01 19:41:07 +0000410 sys.path.append(self.path+'/')
411 mod = __import__("test_trailing_slash")
412 self.assertEqual(mod.testdata, 'test_trailing_slash')
413 unload("test_trailing_slash")
414
Collin Winter88e333d2010-03-17 03:09:21 +0000415 # Regression test for http://bugs.python.org/issue3677.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000416 def _test_UNC_path(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000417 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
418 f.write("testdata = 'test_trailing_slash'")
419 # Create the UNC path, like \\myhost\c$\foo\bar.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000420 path = os.path.abspath(self.path)
421 import socket
422 hn = socket.gethostname()
423 drive = path[0]
424 unc = "\\\\%s\\%s$"%(hn, drive)
425 unc += path[2:]
426 sys.path.append(path)
427 mod = __import__("test_trailing_slash")
428 self.assertEqual(mod.testdata, 'test_trailing_slash')
429 unload("test_trailing_slash")
430
431 if sys.platform == "win32":
432 test_UNC_path = _test_UNC_path
433
434
Collin Winter88e333d2010-03-17 03:09:21 +0000435class RelativeImportTests(unittest.TestCase):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000436
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000437 def tearDown(self):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000438 unload("test.relimport")
439 setUp = tearDown
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000440
441 def test_relimport_star(self):
442 # This will import * from .test_import.
443 from . import relimport
Collin Winter88e333d2010-03-17 03:09:21 +0000444 self.assertTrue(hasattr(relimport, "RelativeImportTests"))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000445
Georg Brandl2ee470f2008-07-16 12:55:28 +0000446 def test_issue3221(self):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000447 # Note for mergers: the 'absolute' tests from the 2.x branch
448 # are missing in Py3k because implicit relative imports are
449 # a thing of the past
Collin Winter88e333d2010-03-17 03:09:21 +0000450 #
451 # Regression test for http://bugs.python.org/issue3221.
Georg Brandl2ee470f2008-07-16 12:55:28 +0000452 def check_relative():
453 exec("from . import relimport", ns)
Collin Winter88e333d2010-03-17 03:09:21 +0000454
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000455 # Check relative import OK with __package__ and __name__ correct
Georg Brandl2ee470f2008-07-16 12:55:28 +0000456 ns = dict(__package__='test', __name__='test.notarealmodule')
457 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000458
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000459 # Check relative import OK with only __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000460 ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
461 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000462
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000463 # Check relative import fails with only __package__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000464 ns = dict(__package__='foo', __name__='test.notarealmodule')
465 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000466
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000467 # Check relative import fails with __package__ and __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000468 ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
469 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000470
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000471 # Check relative import fails with package set to a non-string
Georg Brandl2ee470f2008-07-16 12:55:28 +0000472 ns = dict(__package__=object())
473 self.assertRaises(ValueError, check_relative)
474
Benjamin Peterson556d8002010-06-27 22:37:28 +0000475 def test_absolute_import_without_future(self):
476 # If absolute import syntax is used, then do not try to perform
477 # a relative import in the face of failure.
478 # Issue #7902.
479 try:
480 from .os import sep
481 except ImportError:
482 pass
483 else:
484 self.fail("explicit relative import triggered an "
485 "implicit relative import")
Collin Winter88e333d2010-03-17 03:09:21 +0000486
Collin Winter6498cff2010-03-17 03:14:31 +0000487class OverridingImportBuiltinTests(unittest.TestCase):
488 def test_override_builtin(self):
489 # Test that overriding builtins.__import__ can bypass sys.modules.
490 import os
491
492 def foo():
493 import os
494 return os
495 self.assertEqual(foo(), os) # Quick sanity check.
496
497 with swap_attr(builtins, "__import__", lambda *x: 5):
498 self.assertEqual(foo(), 5)
499
500 # Test what happens when we shadow __import__ in globals(); this
501 # currently does not impact the import process, but if this changes,
502 # other code will need to change, so keep this test as a tripwire.
503 with swap_item(globals(), "__import__", lambda *x: 5):
504 self.assertEqual(foo(), os)
505
506
Barry Warsaw28a691b2010-04-17 00:19:56 +0000507class PycacheTests(unittest.TestCase):
508 # Test the various PEP 3147 related behaviors.
509
510 tag = imp.get_tag()
511
512 def _clean(self):
513 forget(TESTFN)
514 rmtree('__pycache__')
515 unlink(self.source)
516
517 def setUp(self):
518 self.source = TESTFN + '.py'
519 self._clean()
520 with open(self.source, 'w') as fp:
521 print('# This is a test file written by test_import.py', file=fp)
522 sys.path.insert(0, os.curdir)
523
524 def tearDown(self):
525 assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]'
526 del sys.path[0]
527 self._clean()
528
529 def test_import_pyc_path(self):
530 self.assertFalse(os.path.exists('__pycache__'))
531 __import__(TESTFN)
532 self.assertTrue(os.path.exists('__pycache__'))
533 self.assertTrue(os.path.exists(os.path.join(
534 '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag))))
535
536 @unittest.skipUnless(os.name == 'posix',
537 "test meaningful only on posix systems")
538 def test_unwritable_directory(self):
539 # When the umask causes the new __pycache__ directory to be
540 # unwritable, the import still succeeds but no .pyc file is written.
541 with temp_umask(0o222):
542 __import__(TESTFN)
543 self.assertTrue(os.path.exists('__pycache__'))
544 self.assertFalse(os.path.exists(os.path.join(
545 '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag))))
546
547 def test_missing_source(self):
548 # With PEP 3147 cache layout, removing the source but leaving the pyc
549 # file does not satisfy the import.
550 __import__(TESTFN)
551 pyc_file = imp.cache_from_source(self.source)
552 self.assertTrue(os.path.exists(pyc_file))
553 os.remove(self.source)
554 forget(TESTFN)
555 self.assertRaises(ImportError, __import__, TESTFN)
556
557 def test_missing_source_legacy(self):
558 # Like test_missing_source() except that for backward compatibility,
559 # when the pyc file lives where the py file would have been (and named
560 # without the tag), it is importable. The __file__ of the imported
561 # module is the pyc location.
562 __import__(TESTFN)
563 # pyc_file gets removed in _clean() via tearDown().
564 pyc_file = make_legacy_pyc(self.source)
565 os.remove(self.source)
566 unload(TESTFN)
567 m = __import__(TESTFN)
568 self.assertEqual(m.__file__,
569 os.path.join(os.curdir, os.path.relpath(pyc_file)))
570
571 def test___cached__(self):
572 # Modules now also have an __cached__ that points to the pyc file.
573 m = __import__(TESTFN)
574 pyc_file = imp.cache_from_source(TESTFN + '.py')
575 self.assertEqual(m.__cached__, os.path.join(os.curdir, pyc_file))
576
577 def test___cached___legacy_pyc(self):
578 # Like test___cached__() except that for backward compatibility,
579 # when the pyc file lives where the py file would have been (and named
580 # without the tag), it is importable. The __cached__ of the imported
581 # module is the pyc location.
582 __import__(TESTFN)
583 # pyc_file gets removed in _clean() via tearDown().
584 pyc_file = make_legacy_pyc(self.source)
585 os.remove(self.source)
586 unload(TESTFN)
587 m = __import__(TESTFN)
588 self.assertEqual(m.__cached__,
589 os.path.join(os.curdir, os.path.relpath(pyc_file)))
590
591 def test_package___cached__(self):
592 # Like test___cached__ but for packages.
593 def cleanup():
594 shutil.rmtree('pep3147')
595 os.mkdir('pep3147')
596 self.addCleanup(cleanup)
597 # Touch the __init__.py
598 with open(os.path.join('pep3147', '__init__.py'), 'w'):
599 pass
600 with open(os.path.join('pep3147', 'foo.py'), 'w'):
601 pass
602 unload('pep3147.foo')
603 unload('pep3147')
604 m = __import__('pep3147.foo')
605 init_pyc = imp.cache_from_source(
606 os.path.join('pep3147', '__init__.py'))
607 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
608 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
609 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
610 os.path.join(os.curdir, foo_pyc))
611
612 def test_package___cached___from_pyc(self):
613 # Like test___cached__ but ensuring __cached__ when imported from a
614 # PEP 3147 pyc file.
615 def cleanup():
616 shutil.rmtree('pep3147')
617 os.mkdir('pep3147')
618 self.addCleanup(cleanup)
619 unload('pep3147.foo')
620 unload('pep3147')
621 # Touch the __init__.py
622 with open(os.path.join('pep3147', '__init__.py'), 'w'):
623 pass
624 with open(os.path.join('pep3147', 'foo.py'), 'w'):
625 pass
626 m = __import__('pep3147.foo')
627 unload('pep3147.foo')
628 unload('pep3147')
629 m = __import__('pep3147.foo')
630 init_pyc = imp.cache_from_source(
631 os.path.join('pep3147', '__init__.py'))
632 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
633 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
634 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
635 os.path.join(os.curdir, foo_pyc))
636
637
Brett Cannon1f274792010-07-23 14:03:16 +0000638class RelativeImportTests(test_relative_imports.RelativeImports):
639
640 def setUp(self):
641 self._importlib_util_flag = importlib_util.using___import__
642 importlib_util.using___import__ = True
643
644 def tearDown(self):
645 importlib_util.using___import__ = self._importlib_util_flag
646
647
Thomas Wouters89f507f2006-12-13 04:49:30 +0000648def test_main(verbose=None):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000649 run_unittest(ImportTests, PycacheTests,
650 PycRewritingTests, PathsTests, RelativeImportTests,
Brett Cannon1f274792010-07-23 14:03:16 +0000651 OverridingImportBuiltinTests,
652 RelativeImportTests)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000653
Barry Warsaw28a691b2010-04-17 00:19:56 +0000654
Thomas Wouters89f507f2006-12-13 04:49:30 +0000655if __name__ == '__main__':
Collin Winter88e333d2010-03-17 03:09:21 +0000656 # Test needs to be a package, so we can do relative imports.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000657 from test.test_import import test_main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000658 test_main()