Nick Coghlan | be7e49f | 2012-07-20 23:40:09 +1000 | [diff] [blame] | 1 | # We import importlib *ASAP* in order to test #15386 |
| 2 | import importlib |
Brett Cannon | a53cca3 | 2013-07-06 17:56:43 -0400 | [diff] [blame] | 3 | from importlib._bootstrap import _get_sourcefile |
Collin Winter | 6498cff | 2010-03-17 03:14:31 +0000 | [diff] [blame] | 4 | import builtins |
Christian Heimes | 13a7a21 | 2008-01-07 17:13:09 +0000 | [diff] [blame] | 5 | import imp |
Brett Cannon | 86ae981 | 2012-07-20 15:40:57 -0400 | [diff] [blame] | 6 | from test.test_importlib.import_ import util as importlib_util |
Antoine Pitrou | d35cbf6 | 2009-01-06 19:02:24 +0000 | [diff] [blame] | 7 | import marshal |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 8 | import os |
Charles-François Natali | a13b1fa | 2011-10-04 19:17:26 +0200 | [diff] [blame] | 9 | import platform |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 10 | import py_compile |
| 11 | import random |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 12 | import stat |
| 13 | import sys |
| 14 | import unittest |
Brett Cannon | a53cca3 | 2013-07-06 17:56:43 -0400 | [diff] [blame] | 15 | import unittest.mock as mock |
R. David Murray | ce4b170 | 2010-12-14 23:06:25 +0000 | [diff] [blame] | 16 | import textwrap |
Antoine Pitrou | dd21f68 | 2012-01-25 03:00:57 +0100 | [diff] [blame] | 17 | import errno |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 18 | import shutil |
Nick Coghlan | eb8d627 | 2012-10-19 23:32:00 +1000 | [diff] [blame] | 19 | import contextlib |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 20 | |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 21 | import test.support |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 22 | from test.support import ( |
| 23 | EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython, |
| 24 | make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask, |
Antoine Pitrou | 48114b9 | 2012-06-17 22:33:38 +0200 | [diff] [blame] | 25 | unlink, unload, create_empty_file, cpython_only) |
R. David Murray | ce4b170 | 2010-12-14 23:06:25 +0000 | [diff] [blame] | 26 | from test import script_helper |
Guido van Rossum | bd6f4fb | 2000-10-24 17:16:32 +0000 | [diff] [blame] | 27 | |
Tim Peters | 72f98e9 | 2001-05-08 15:19:57 +0000 | [diff] [blame] | 28 | |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 29 | skip_if_dont_write_bytecode = unittest.skipIf( |
| 30 | sys.dont_write_bytecode, |
| 31 | "test meaningful only when writing bytecode") |
| 32 | |
Tim Peters | 08138fd | 2004-08-02 03:58:27 +0000 | [diff] [blame] | 33 | def remove_files(name): |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 34 | for f in (name + ".py", |
| 35 | name + ".pyc", |
| 36 | name + ".pyo", |
| 37 | name + ".pyw", |
Tim Peters | 08138fd | 2004-08-02 03:58:27 +0000 | [diff] [blame] | 38 | name + "$py.class"): |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 39 | unlink(f) |
Florent Xicluna | 27354cc | 2010-08-16 18:41:19 +0000 | [diff] [blame] | 40 | rmtree('__pycache__') |
Tim Peters | 08138fd | 2004-08-02 03:58:27 +0000 | [diff] [blame] | 41 | |
Tim Peters | c173137 | 2001-08-04 08:12:36 +0000 | [diff] [blame] | 42 | |
Nick Coghlan | eb8d627 | 2012-10-19 23:32:00 +1000 | [diff] [blame] | 43 | @contextlib.contextmanager |
| 44 | def _ready_to_import(name=None, source=""): |
| 45 | # sets up a temporary directory and removes it |
| 46 | # creates the module file |
| 47 | # temporarily clears the module from sys.modules (if any) |
Nick Coghlan | f1465f0 | 2013-04-15 22:56:51 +1000 | [diff] [blame] | 48 | # reverts or removes the module when cleaning up |
Nick Coghlan | eb8d627 | 2012-10-19 23:32:00 +1000 | [diff] [blame] | 49 | name = name or "spam" |
| 50 | with script_helper.temp_dir() as tempdir: |
| 51 | path = script_helper.make_script(tempdir, name, source) |
| 52 | old_module = sys.modules.pop(name, None) |
| 53 | try: |
| 54 | sys.path.insert(0, tempdir) |
| 55 | yield name, path |
| 56 | sys.path.remove(tempdir) |
| 57 | finally: |
| 58 | if old_module is not None: |
| 59 | sys.modules[name] = old_module |
Nick Coghlan | f1465f0 | 2013-04-15 22:56:51 +1000 | [diff] [blame] | 60 | elif name in sys.modules: |
| 61 | del sys.modules[name] |
Nick Coghlan | eb8d627 | 2012-10-19 23:32:00 +1000 | [diff] [blame] | 62 | |
| 63 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 64 | class ImportTests(unittest.TestCase): |
Tim Peters | c173137 | 2001-08-04 08:12:36 +0000 | [diff] [blame] | 65 | |
Antoine Pitrou | 46719af | 2011-03-21 19:05:02 +0100 | [diff] [blame] | 66 | def setUp(self): |
| 67 | remove_files(TESTFN) |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 68 | importlib.invalidate_caches() |
Antoine Pitrou | 46719af | 2011-03-21 19:05:02 +0100 | [diff] [blame] | 69 | |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 70 | def tearDown(self): |
| 71 | unload(TESTFN) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 72 | |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 73 | setUp = tearDown |
| 74 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 75 | def test_case_sensitivity(self): |
| 76 | # Brief digression to test that import is case-sensitive: if we got |
| 77 | # this far, we know for sure that "random" exists. |
Benjamin Peterson | 1c87e29 | 2010-10-30 23:04:49 +0000 | [diff] [blame] | 78 | with self.assertRaises(ImportError): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 79 | import RAnDoM |
Tim Peters | 08138fd | 2004-08-02 03:58:27 +0000 | [diff] [blame] | 80 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 81 | def test_double_const(self): |
| 82 | # Another brief digression to test the accuracy of manifest float |
| 83 | # constants. |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 84 | from test import double_const # don't blink -- that *was* the test |
Tim Peters | 08138fd | 2004-08-02 03:58:27 +0000 | [diff] [blame] | 85 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 86 | def test_import(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 87 | def test_with_extension(ext): |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 88 | # The extension is normally ".py", perhaps ".pyw". |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 89 | source = TESTFN + ext |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 90 | pyo = TESTFN + ".pyo" |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 91 | if is_jython: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 92 | pyc = TESTFN + "$py.class" |
| 93 | else: |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 94 | pyc = TESTFN + ".pyc" |
Tim Peters | 08138fd | 2004-08-02 03:58:27 +0000 | [diff] [blame] | 95 | |
Benjamin Peterson | 16a1f63 | 2009-06-13 13:01:19 +0000 | [diff] [blame] | 96 | with open(source, "w") as f: |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 97 | print("# This tests Python's ability to import a", |
| 98 | ext, "file.", file=f) |
Benjamin Peterson | 16a1f63 | 2009-06-13 13:01:19 +0000 | [diff] [blame] | 99 | a = random.randrange(1000) |
| 100 | b = random.randrange(1000) |
| 101 | print("a =", a, file=f) |
| 102 | print("b =", b, file=f) |
Jeremy Hylton | 3e0055f | 2005-10-20 19:59:25 +0000 | [diff] [blame] | 103 | |
Amaury Forgeot d'Arc | dd9e3b8 | 2007-11-16 00:56:23 +0000 | [diff] [blame] | 104 | if TESTFN in sys.modules: |
| 105 | del sys.modules[TESTFN] |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 106 | importlib.invalidate_caches() |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 107 | try: |
| 108 | try: |
| 109 | mod = __import__(TESTFN) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 110 | except ImportError as err: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 111 | self.fail("import from %s failed: %s" % (ext, err)) |
Jeremy Hylton | 3e0055f | 2005-10-20 19:59:25 +0000 | [diff] [blame] | 112 | |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 113 | self.assertEqual(mod.a, a, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 114 | "module loaded (%s) but contents invalid" % mod) |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 115 | self.assertEqual(mod.b, b, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 116 | "module loaded (%s) but contents invalid" % mod) |
| 117 | finally: |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 118 | forget(TESTFN) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 119 | unlink(source) |
| 120 | unlink(pyc) |
| 121 | unlink(pyo) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 122 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 123 | sys.path.insert(0, os.curdir) |
| 124 | try: |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 125 | test_with_extension(".py") |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 126 | if sys.platform.startswith("win"): |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 127 | for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 128 | test_with_extension(ext) |
| 129 | finally: |
| 130 | del sys.path[0] |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 131 | |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 132 | @skip_if_dont_write_bytecode |
Victor Stinner | 53ffdc5 | 2011-09-23 18:54:40 +0200 | [diff] [blame] | 133 | def test_bug7732(self): |
| 134 | source = TESTFN + '.py' |
| 135 | os.mkdir(source) |
| 136 | try: |
| 137 | self.assertRaisesRegex(ImportError, '^No module', |
| 138 | imp.find_module, TESTFN, ["."]) |
| 139 | finally: |
| 140 | os.rmdir(source) |
| 141 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 142 | def test_module_with_large_stack(self, module='longlist'): |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 143 | # Regression test for http://bugs.python.org/issue561858. |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 144 | filename = module + '.py' |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 145 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 146 | # Create a file with a list of 65000 elements. |
Brett Cannon | 2cab50b | 2010-07-03 01:32:48 +0000 | [diff] [blame] | 147 | with open(filename, 'w') as f: |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 148 | f.write('d = [\n') |
| 149 | for i in range(65000): |
| 150 | f.write('"",\n') |
| 151 | f.write(']') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 152 | |
Brett Cannon | 2cab50b | 2010-07-03 01:32:48 +0000 | [diff] [blame] | 153 | try: |
| 154 | # Compile & remove .py file; we only need .pyc (or .pyo). |
| 155 | # Bytecode must be relocated from the PEP 3147 bytecode-only location. |
| 156 | py_compile.compile(filename) |
| 157 | finally: |
| 158 | unlink(filename) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 159 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 160 | # Need to be able to load from current dir. |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 161 | sys.path.append('') |
Brett Cannon | 73def61 | 2012-04-14 14:38:19 -0400 | [diff] [blame] | 162 | importlib.invalidate_caches() |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 163 | |
Brett Cannon | 93220d0 | 2010-05-15 22:20:16 +0000 | [diff] [blame] | 164 | try: |
Brett Cannon | 2cab50b | 2010-07-03 01:32:48 +0000 | [diff] [blame] | 165 | make_legacy_pyc(filename) |
Brett Cannon | 93220d0 | 2010-05-15 22:20:16 +0000 | [diff] [blame] | 166 | # This used to crash. |
| 167 | exec('import ' + module) |
| 168 | finally: |
| 169 | # Cleanup. |
| 170 | del sys.path[-1] |
| 171 | unlink(filename + 'c') |
| 172 | unlink(filename + 'o') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 173 | |
| 174 | def test_failing_import_sticks(self): |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 175 | source = TESTFN + ".py" |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 176 | with open(source, "w") as f: |
| 177 | print("a = 1/0", file=f) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 178 | |
| 179 | # New in 2.4, we shouldn't be able to import that no matter how often |
| 180 | # we try. |
| 181 | sys.path.insert(0, os.curdir) |
Antoine Pitrou | 021548c | 2012-07-12 19:21:43 +0200 | [diff] [blame] | 182 | importlib.invalidate_caches() |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 183 | if TESTFN in sys.modules: |
| 184 | del sys.modules[TESTFN] |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 185 | try: |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 186 | for i in [1, 2, 3]: |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 187 | self.assertRaises(ZeroDivisionError, __import__, TESTFN) |
| 188 | self.assertNotIn(TESTFN, sys.modules, |
| 189 | "damaged module in sys.modules on %i try" % i) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 190 | finally: |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 191 | del sys.path[0] |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 192 | remove_files(TESTFN) |
| 193 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 194 | def test_import_name_binding(self): |
| 195 | # import x.y.z binds x in the current namespace |
| 196 | import test as x |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 197 | import test.support |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 198 | self.assertTrue(x is test, x.__name__) |
| 199 | self.assertTrue(hasattr(test.support, "__file__")) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 200 | |
| 201 | # import x.y.z as w binds z as w |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 202 | import test.support as y |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 203 | self.assertTrue(y is test.support, y.__name__) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 204 | |
Christian Heimes | 13a7a21 | 2008-01-07 17:13:09 +0000 | [diff] [blame] | 205 | def test_failing_reload(self): |
| 206 | # A failing reload should leave the module object in sys.modules. |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 207 | source = TESTFN + os.extsep + "py" |
Christian Heimes | 13a7a21 | 2008-01-07 17:13:09 +0000 | [diff] [blame] | 208 | with open(source, "w") as f: |
| 209 | f.write("a = 1\nb=2\n") |
| 210 | |
| 211 | sys.path.insert(0, os.curdir) |
| 212 | try: |
| 213 | mod = __import__(TESTFN) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 214 | self.assertIn(TESTFN, sys.modules) |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 215 | self.assertEqual(mod.a, 1, "module has wrong attribute values") |
| 216 | self.assertEqual(mod.b, 2, "module has wrong attribute values") |
Christian Heimes | 13a7a21 | 2008-01-07 17:13:09 +0000 | [diff] [blame] | 217 | |
| 218 | # On WinXP, just replacing the .py file wasn't enough to |
| 219 | # convince reload() to reparse it. Maybe the timestamp didn't |
| 220 | # move enough. We force it to get reparsed by removing the |
| 221 | # compiled file too. |
| 222 | remove_files(TESTFN) |
| 223 | |
| 224 | # Now damage the module. |
| 225 | with open(source, "w") as f: |
| 226 | f.write("a = 10\nb=20//0\n") |
| 227 | |
| 228 | self.assertRaises(ZeroDivisionError, imp.reload, mod) |
| 229 | # But we still expect the module to be in sys.modules. |
| 230 | mod = sys.modules.get(TESTFN) |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 231 | self.assertIsNot(mod, None, "expected module to be in sys.modules") |
Christian Heimes | 13a7a21 | 2008-01-07 17:13:09 +0000 | [diff] [blame] | 232 | |
| 233 | # We should have replaced a w/ 10, but the old b value should |
| 234 | # stick. |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 235 | self.assertEqual(mod.a, 10, "module has wrong attribute values") |
| 236 | self.assertEqual(mod.b, 2, "module has wrong attribute values") |
Christian Heimes | 13a7a21 | 2008-01-07 17:13:09 +0000 | [diff] [blame] | 237 | |
| 238 | finally: |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 239 | del sys.path[0] |
Christian Heimes | 13a7a21 | 2008-01-07 17:13:09 +0000 | [diff] [blame] | 240 | remove_files(TESTFN) |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 241 | unload(TESTFN) |
Christian Heimes | 13a7a21 | 2008-01-07 17:13:09 +0000 | [diff] [blame] | 242 | |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 243 | @skip_if_dont_write_bytecode |
Christian Heimes | 3b06e53 | 2008-01-07 20:12:44 +0000 | [diff] [blame] | 244 | def test_file_to_source(self): |
| 245 | # check if __file__ points to the source file where available |
| 246 | source = TESTFN + ".py" |
| 247 | with open(source, "w") as f: |
| 248 | f.write("test = None\n") |
| 249 | |
| 250 | sys.path.insert(0, os.curdir) |
| 251 | try: |
| 252 | mod = __import__(TESTFN) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 253 | self.assertTrue(mod.__file__.endswith('.py')) |
Christian Heimes | 3b06e53 | 2008-01-07 20:12:44 +0000 | [diff] [blame] | 254 | os.remove(source) |
| 255 | del sys.modules[TESTFN] |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 256 | make_legacy_pyc(source) |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 257 | importlib.invalidate_caches() |
Christian Heimes | 3b06e53 | 2008-01-07 20:12:44 +0000 | [diff] [blame] | 258 | mod = __import__(TESTFN) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 259 | base, ext = os.path.splitext(mod.__file__) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 260 | self.assertIn(ext, ('.pyc', '.pyo')) |
Christian Heimes | 3b06e53 | 2008-01-07 20:12:44 +0000 | [diff] [blame] | 261 | finally: |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 262 | del sys.path[0] |
Christian Heimes | 3b06e53 | 2008-01-07 20:12:44 +0000 | [diff] [blame] | 263 | remove_files(TESTFN) |
| 264 | if TESTFN in sys.modules: |
| 265 | del sys.modules[TESTFN] |
| 266 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 267 | def test_import_by_filename(self): |
Christian Heimes | 454f37b | 2008-01-10 00:10:02 +0000 | [diff] [blame] | 268 | path = os.path.abspath(TESTFN) |
Victor Stinner | 6c6f851 | 2010-08-07 10:09:35 +0000 | [diff] [blame] | 269 | encoding = sys.getfilesystemencoding() |
| 270 | try: |
| 271 | path.encode(encoding) |
| 272 | except UnicodeEncodeError: |
| 273 | self.skipTest('path is not encodable to {}'.format(encoding)) |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 274 | with self.assertRaises(ImportError) as c: |
Christian Heimes | 454f37b | 2008-01-10 00:10:02 +0000 | [diff] [blame] | 275 | __import__(path) |
Christian Heimes | 454f37b | 2008-01-10 00:10:02 +0000 | [diff] [blame] | 276 | |
R. David Murray | ce4b170 | 2010-12-14 23:06:25 +0000 | [diff] [blame] | 277 | def test_import_in_del_does_not_crash(self): |
| 278 | # Issue 4236 |
| 279 | testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\ |
| 280 | import sys |
| 281 | class C: |
| 282 | def __del__(self): |
| 283 | import imp |
| 284 | sys.argv.insert(0, C()) |
| 285 | """)) |
| 286 | script_helper.assert_python_ok(testfn) |
| 287 | |
Antoine Pitrou | 2be60af | 2012-01-24 17:44:06 +0100 | [diff] [blame] | 288 | def test_timestamp_overflow(self): |
| 289 | # A modification timestamp larger than 2**32 should not be a problem |
| 290 | # when importing a module (issue #11235). |
Antoine Pitrou | 05f29b7 | 2012-01-25 01:35:26 +0100 | [diff] [blame] | 291 | sys.path.insert(0, os.curdir) |
| 292 | try: |
| 293 | source = TESTFN + ".py" |
| 294 | compiled = imp.cache_from_source(source) |
| 295 | with open(source, 'w') as f: |
| 296 | pass |
| 297 | try: |
Antoine Pitrou | 33d15f7 | 2012-01-25 18:01:45 +0100 | [diff] [blame] | 298 | os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5)) |
Antoine Pitrou | 05f29b7 | 2012-01-25 01:35:26 +0100 | [diff] [blame] | 299 | except OverflowError: |
| 300 | self.skipTest("cannot set modification time to large integer") |
Antoine Pitrou | dd21f68 | 2012-01-25 03:00:57 +0100 | [diff] [blame] | 301 | except OSError as e: |
| 302 | if e.errno != getattr(errno, 'EOVERFLOW', None): |
| 303 | raise |
| 304 | self.skipTest("cannot set modification time to large integer ({})".format(e)) |
Antoine Pitrou | 05f29b7 | 2012-01-25 01:35:26 +0100 | [diff] [blame] | 305 | __import__(TESTFN) |
| 306 | # The pyc file was created. |
| 307 | os.stat(compiled) |
| 308 | finally: |
| 309 | del sys.path[0] |
| 310 | remove_files(TESTFN) |
Antoine Pitrou | 2be60af | 2012-01-24 17:44:06 +0100 | [diff] [blame] | 311 | |
Brett Cannon | 7385adc | 2012-08-17 13:21:16 -0400 | [diff] [blame] | 312 | def test_bogus_fromlist(self): |
| 313 | try: |
| 314 | __import__('http', fromlist=['blah']) |
| 315 | except ImportError: |
| 316 | self.fail("fromlist must allow bogus names") |
| 317 | |
Benjamin Peterson | 7d11004 | 2013-04-29 09:08:14 -0400 | [diff] [blame] | 318 | @cpython_only |
| 319 | def test_delete_builtins_import(self): |
| 320 | args = ["-c", "del __builtins__.__import__; import os"] |
| 321 | popen = script_helper.spawn_python(*args) |
| 322 | stdout, stderr = popen.communicate() |
| 323 | self.assertIn(b"ImportError", stdout) |
| 324 | |
Alexandre Vassalotti | 9d58e3e | 2009-07-17 10:55:50 +0000 | [diff] [blame] | 325 | |
Ezio Melotti | e5e7a7c | 2013-03-16 21:49:20 +0200 | [diff] [blame] | 326 | @skip_if_dont_write_bytecode |
Nick Coghlan | eb8d627 | 2012-10-19 23:32:00 +1000 | [diff] [blame] | 327 | class FilePermissionTests(unittest.TestCase): |
| 328 | # tests for file mode on cached .pyc/.pyo files |
| 329 | |
| 330 | @unittest.skipUnless(os.name == 'posix', |
| 331 | "test meaningful only on posix systems") |
| 332 | def test_creation_mode(self): |
| 333 | mask = 0o022 |
| 334 | with temp_umask(mask), _ready_to_import() as (name, path): |
| 335 | cached_path = imp.cache_from_source(path) |
| 336 | module = __import__(name) |
| 337 | if not os.path.exists(cached_path): |
| 338 | self.fail("__import__ did not result in creation of " |
| 339 | "either a .pyc or .pyo file") |
| 340 | stat_info = os.stat(cached_path) |
| 341 | |
| 342 | # Check that the umask is respected, and the executable bits |
| 343 | # aren't set. |
| 344 | self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), |
| 345 | oct(0o666 & ~mask)) |
| 346 | |
| 347 | @unittest.skipUnless(os.name == 'posix', |
| 348 | "test meaningful only on posix systems") |
| 349 | def test_cached_mode_issue_2051(self): |
| 350 | # permissions of .pyc should match those of .py, regardless of mask |
| 351 | mode = 0o600 |
| 352 | with temp_umask(0o022), _ready_to_import() as (name, path): |
| 353 | cached_path = imp.cache_from_source(path) |
| 354 | os.chmod(path, mode) |
| 355 | __import__(name) |
| 356 | if not os.path.exists(cached_path): |
| 357 | self.fail("__import__ did not result in creation of " |
| 358 | "either a .pyc or .pyo file") |
| 359 | stat_info = os.stat(cached_path) |
| 360 | |
| 361 | self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(mode)) |
| 362 | |
| 363 | @unittest.skipUnless(os.name == 'posix', |
| 364 | "test meaningful only on posix systems") |
| 365 | def test_cached_readonly(self): |
| 366 | mode = 0o400 |
| 367 | with temp_umask(0o022), _ready_to_import() as (name, path): |
| 368 | cached_path = imp.cache_from_source(path) |
| 369 | os.chmod(path, mode) |
| 370 | __import__(name) |
| 371 | if not os.path.exists(cached_path): |
| 372 | self.fail("__import__ did not result in creation of " |
| 373 | "either a .pyc or .pyo file") |
| 374 | stat_info = os.stat(cached_path) |
| 375 | |
| 376 | expected = mode | 0o200 # Account for fix for issue #6074 |
| 377 | self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(expected)) |
| 378 | |
| 379 | def test_pyc_always_writable(self): |
| 380 | # Initially read-only .pyc files on Windows used to cause problems |
| 381 | # with later updates, see issue #6074 for details |
| 382 | with _ready_to_import() as (name, path): |
| 383 | # Write a Python file, make it read-only and import it |
| 384 | with open(path, 'w') as f: |
| 385 | f.write("x = 'original'\n") |
| 386 | # Tweak the mtime of the source to ensure pyc gets updated later |
| 387 | s = os.stat(path) |
| 388 | os.utime(path, (s.st_atime, s.st_mtime-100000000)) |
| 389 | os.chmod(path, 0o400) |
| 390 | m = __import__(name) |
| 391 | self.assertEqual(m.x, 'original') |
| 392 | # Change the file and then reimport it |
| 393 | os.chmod(path, 0o600) |
| 394 | with open(path, 'w') as f: |
| 395 | f.write("x = 'rewritten'\n") |
| 396 | unload(name) |
| 397 | importlib.invalidate_caches() |
| 398 | m = __import__(name) |
| 399 | self.assertEqual(m.x, 'rewritten') |
| 400 | # Now delete the source file and check the pyc was rewritten |
| 401 | unlink(path) |
| 402 | unload(name) |
| 403 | importlib.invalidate_caches() |
| 404 | if __debug__: |
| 405 | bytecode_only = path + "c" |
| 406 | else: |
| 407 | bytecode_only = path + "o" |
| 408 | os.rename(imp.cache_from_source(path), bytecode_only) |
| 409 | m = __import__(name) |
| 410 | self.assertEqual(m.x, 'rewritten') |
| 411 | |
| 412 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 413 | class PycRewritingTests(unittest.TestCase): |
Antoine Pitrou | d35cbf6 | 2009-01-06 19:02:24 +0000 | [diff] [blame] | 414 | # Test that the `co_filename` attribute on code objects always points |
| 415 | # to the right file, even when various things happen (e.g. both the .py |
| 416 | # and the .pyc file are renamed). |
| 417 | |
| 418 | module_name = "unlikely_module_name" |
| 419 | module_source = """ |
| 420 | import sys |
| 421 | code_filename = sys._getframe().f_code.co_filename |
| 422 | module_filename = __file__ |
| 423 | constant = 1 |
| 424 | def func(): |
| 425 | pass |
| 426 | func_filename = func.__code__.co_filename |
| 427 | """ |
| 428 | dir_name = os.path.abspath(TESTFN) |
| 429 | file_name = os.path.join(dir_name, module_name) + os.extsep + "py" |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 430 | compiled_name = imp.cache_from_source(file_name) |
Antoine Pitrou | d35cbf6 | 2009-01-06 19:02:24 +0000 | [diff] [blame] | 431 | |
| 432 | def setUp(self): |
| 433 | self.sys_path = sys.path[:] |
| 434 | self.orig_module = sys.modules.pop(self.module_name, None) |
| 435 | os.mkdir(self.dir_name) |
| 436 | with open(self.file_name, "w") as f: |
| 437 | f.write(self.module_source) |
| 438 | sys.path.insert(0, self.dir_name) |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 439 | importlib.invalidate_caches() |
Antoine Pitrou | d35cbf6 | 2009-01-06 19:02:24 +0000 | [diff] [blame] | 440 | |
| 441 | def tearDown(self): |
| 442 | sys.path[:] = self.sys_path |
| 443 | if self.orig_module is not None: |
| 444 | sys.modules[self.module_name] = self.orig_module |
| 445 | else: |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 446 | unload(self.module_name) |
| 447 | unlink(self.file_name) |
| 448 | unlink(self.compiled_name) |
Florent Xicluna | 27354cc | 2010-08-16 18:41:19 +0000 | [diff] [blame] | 449 | rmtree(self.dir_name) |
Antoine Pitrou | d35cbf6 | 2009-01-06 19:02:24 +0000 | [diff] [blame] | 450 | |
| 451 | def import_module(self): |
| 452 | ns = globals() |
| 453 | __import__(self.module_name, ns, ns) |
| 454 | return sys.modules[self.module_name] |
| 455 | |
| 456 | def test_basics(self): |
| 457 | mod = self.import_module() |
| 458 | self.assertEqual(mod.module_filename, self.file_name) |
| 459 | self.assertEqual(mod.code_filename, self.file_name) |
| 460 | self.assertEqual(mod.func_filename, self.file_name) |
| 461 | del sys.modules[self.module_name] |
| 462 | mod = self.import_module() |
| 463 | self.assertEqual(mod.module_filename, self.file_name) |
| 464 | self.assertEqual(mod.code_filename, self.file_name) |
| 465 | self.assertEqual(mod.func_filename, self.file_name) |
| 466 | |
| 467 | def test_incorrect_code_name(self): |
| 468 | py_compile.compile(self.file_name, dfile="another_module.py") |
| 469 | mod = self.import_module() |
| 470 | self.assertEqual(mod.module_filename, self.file_name) |
| 471 | self.assertEqual(mod.code_filename, self.file_name) |
| 472 | self.assertEqual(mod.func_filename, self.file_name) |
| 473 | |
| 474 | def test_module_without_source(self): |
| 475 | target = "another_module.py" |
| 476 | py_compile.compile(self.file_name, dfile=target) |
| 477 | os.remove(self.file_name) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 478 | pyc_file = make_legacy_pyc(self.file_name) |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 479 | importlib.invalidate_caches() |
Antoine Pitrou | d35cbf6 | 2009-01-06 19:02:24 +0000 | [diff] [blame] | 480 | mod = self.import_module() |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 481 | self.assertEqual(mod.module_filename, pyc_file) |
Antoine Pitrou | d35cbf6 | 2009-01-06 19:02:24 +0000 | [diff] [blame] | 482 | self.assertEqual(mod.code_filename, target) |
| 483 | self.assertEqual(mod.func_filename, target) |
| 484 | |
| 485 | def test_foreign_code(self): |
| 486 | py_compile.compile(self.file_name) |
| 487 | with open(self.compiled_name, "rb") as f: |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 488 | header = f.read(12) |
Antoine Pitrou | d35cbf6 | 2009-01-06 19:02:24 +0000 | [diff] [blame] | 489 | code = marshal.load(f) |
| 490 | constants = list(code.co_consts) |
| 491 | foreign_code = test_main.__code__ |
| 492 | pos = constants.index(1) |
| 493 | constants[pos] = foreign_code |
| 494 | code = type(code)(code.co_argcount, code.co_kwonlyargcount, |
| 495 | code.co_nlocals, code.co_stacksize, |
| 496 | code.co_flags, code.co_code, tuple(constants), |
| 497 | code.co_names, code.co_varnames, code.co_filename, |
| 498 | code.co_name, code.co_firstlineno, code.co_lnotab, |
| 499 | code.co_freevars, code.co_cellvars) |
| 500 | with open(self.compiled_name, "wb") as f: |
| 501 | f.write(header) |
| 502 | marshal.dump(code, f) |
| 503 | mod = self.import_module() |
| 504 | self.assertEqual(mod.constant.co_filename, foreign_code.co_filename) |
| 505 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 506 | |
Christian Heimes | 204093a | 2007-11-01 22:37:07 +0000 | [diff] [blame] | 507 | class PathsTests(unittest.TestCase): |
| 508 | SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8', |
| 509 | 'test\u00b0\u00b3\u00b2') |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 510 | path = TESTFN |
| 511 | |
| 512 | def setUp(self): |
| 513 | os.mkdir(self.path) |
| 514 | self.syspath = sys.path[:] |
| 515 | |
| 516 | def tearDown(self): |
Florent Xicluna | 27354cc | 2010-08-16 18:41:19 +0000 | [diff] [blame] | 517 | rmtree(self.path) |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 518 | sys.path[:] = self.syspath |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 519 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 520 | # Regression test for http://bugs.python.org/issue1293. |
Christian Heimes | 1d1a400 | 2007-11-01 19:41:07 +0000 | [diff] [blame] | 521 | def test_trailing_slash(self): |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 522 | with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f: |
| 523 | f.write("testdata = 'test_trailing_slash'") |
Christian Heimes | 1d1a400 | 2007-11-01 19:41:07 +0000 | [diff] [blame] | 524 | sys.path.append(self.path+'/') |
| 525 | mod = __import__("test_trailing_slash") |
| 526 | self.assertEqual(mod.testdata, 'test_trailing_slash') |
| 527 | unload("test_trailing_slash") |
| 528 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 529 | # Regression test for http://bugs.python.org/issue3677. |
Brett Cannon | bbdc9cd | 2012-04-20 16:29:39 -0400 | [diff] [blame] | 530 | @unittest.skipUnless(sys.platform == 'win32', 'Windows-specific') |
Brett Cannon | 9e924ed | 2012-04-20 17:34:59 -0400 | [diff] [blame] | 531 | def test_UNC_path(self): |
Antoine Pitrou | f189e80 | 2012-07-12 19:48:49 +0200 | [diff] [blame] | 532 | with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f: |
| 533 | f.write("testdata = 'test_unc_path'") |
Brett Cannon | b8c0206 | 2012-04-21 19:11:58 -0400 | [diff] [blame] | 534 | importlib.invalidate_caches() |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 535 | # Create the UNC path, like \\myhost\c$\foo\bar. |
Kristján Valur Jónsson | d9aab51 | 2009-01-24 10:50:45 +0000 | [diff] [blame] | 536 | path = os.path.abspath(self.path) |
| 537 | import socket |
| 538 | hn = socket.gethostname() |
| 539 | drive = path[0] |
| 540 | unc = "\\\\%s\\%s$"%(hn, drive) |
| 541 | unc += path[2:] |
Brett Cannon | b8c0206 | 2012-04-21 19:11:58 -0400 | [diff] [blame] | 542 | try: |
Antoine Pitrou | 5df0204 | 2012-07-12 19:50:03 +0200 | [diff] [blame] | 543 | os.listdir(unc) |
Antoine Pitrou | 68f4247 | 2012-07-13 20:54:42 +0200 | [diff] [blame] | 544 | except OSError as e: |
| 545 | if e.errno in (errno.EPERM, errno.EACCES): |
| 546 | # See issue #15338 |
| 547 | self.skipTest("cannot access administrative share %r" % (unc,)) |
| 548 | raise |
Antoine Pitrou | c27ace6 | 2012-07-13 20:59:19 +0200 | [diff] [blame] | 549 | sys.path.insert(0, unc) |
| 550 | try: |
| 551 | mod = __import__("test_unc_path") |
| 552 | except ImportError as e: |
| 553 | self.fail("could not import 'test_unc_path' from %r: %r" |
| 554 | % (unc, e)) |
| 555 | self.assertEqual(mod.testdata, 'test_unc_path') |
| 556 | self.assertTrue(mod.__file__.startswith(unc), mod.__file__) |
| 557 | unload("test_unc_path") |
Kristján Valur Jónsson | d9aab51 | 2009-01-24 10:50:45 +0000 | [diff] [blame] | 558 | |
Kristján Valur Jónsson | d9aab51 | 2009-01-24 10:50:45 +0000 | [diff] [blame] | 559 | |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 560 | class RelativeImportTests(unittest.TestCase): |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 561 | |
Christian Heimes | d5e2b6f | 2008-03-19 21:50:51 +0000 | [diff] [blame] | 562 | def tearDown(self): |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 563 | unload("test.relimport") |
| 564 | setUp = tearDown |
Christian Heimes | d5e2b6f | 2008-03-19 21:50:51 +0000 | [diff] [blame] | 565 | |
| 566 | def test_relimport_star(self): |
| 567 | # This will import * from .test_import. |
| 568 | from . import relimport |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 569 | self.assertTrue(hasattr(relimport, "RelativeImportTests")) |
Christian Heimes | d5e2b6f | 2008-03-19 21:50:51 +0000 | [diff] [blame] | 570 | |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 571 | def test_issue3221(self): |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 572 | # Note for mergers: the 'absolute' tests from the 2.x branch |
| 573 | # are missing in Py3k because implicit relative imports are |
| 574 | # a thing of the past |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 575 | # |
| 576 | # Regression test for http://bugs.python.org/issue3221. |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 577 | def check_relative(): |
| 578 | exec("from . import relimport", ns) |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 579 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 580 | # Check relative import OK with __package__ and __name__ correct |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 581 | ns = dict(__package__='test', __name__='test.notarealmodule') |
| 582 | check_relative() |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 583 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 584 | # Check relative import OK with only __name__ wrong |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 585 | ns = dict(__package__='test', __name__='notarealpkg.notarealmodule') |
| 586 | check_relative() |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 587 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 588 | # Check relative import fails with only __package__ wrong |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 589 | ns = dict(__package__='foo', __name__='test.notarealmodule') |
| 590 | self.assertRaises(SystemError, check_relative) |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 591 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 592 | # Check relative import fails with __package__ and __name__ wrong |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 593 | ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule') |
| 594 | self.assertRaises(SystemError, check_relative) |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 595 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 596 | # Check relative import fails with package set to a non-string |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 597 | ns = dict(__package__=object()) |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 598 | self.assertRaises(TypeError, check_relative) |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 599 | |
Benjamin Peterson | 556d800 | 2010-06-27 22:37:28 +0000 | [diff] [blame] | 600 | def test_absolute_import_without_future(self): |
Florent Xicluna | 27354cc | 2010-08-16 18:41:19 +0000 | [diff] [blame] | 601 | # If explicit relative import syntax is used, then do not try |
Florent Xicluna | c9c29e2 | 2010-08-16 19:03:05 +0000 | [diff] [blame] | 602 | # to perform an absolute import in the face of failure. |
Benjamin Peterson | 556d800 | 2010-06-27 22:37:28 +0000 | [diff] [blame] | 603 | # Issue #7902. |
Florent Xicluna | 27354cc | 2010-08-16 18:41:19 +0000 | [diff] [blame] | 604 | with self.assertRaises(ImportError): |
Benjamin Peterson | 556d800 | 2010-06-27 22:37:28 +0000 | [diff] [blame] | 605 | from .os import sep |
Benjamin Peterson | 556d800 | 2010-06-27 22:37:28 +0000 | [diff] [blame] | 606 | self.fail("explicit relative import triggered an " |
Florent Xicluna | 27354cc | 2010-08-16 18:41:19 +0000 | [diff] [blame] | 607 | "implicit absolute import") |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 608 | |
Florent Xicluna | c9c29e2 | 2010-08-16 19:03:05 +0000 | [diff] [blame] | 609 | |
Collin Winter | 6498cff | 2010-03-17 03:14:31 +0000 | [diff] [blame] | 610 | class OverridingImportBuiltinTests(unittest.TestCase): |
| 611 | def test_override_builtin(self): |
| 612 | # Test that overriding builtins.__import__ can bypass sys.modules. |
| 613 | import os |
| 614 | |
| 615 | def foo(): |
| 616 | import os |
| 617 | return os |
| 618 | self.assertEqual(foo(), os) # Quick sanity check. |
| 619 | |
| 620 | with swap_attr(builtins, "__import__", lambda *x: 5): |
| 621 | self.assertEqual(foo(), 5) |
| 622 | |
| 623 | # Test what happens when we shadow __import__ in globals(); this |
| 624 | # currently does not impact the import process, but if this changes, |
| 625 | # other code will need to change, so keep this test as a tripwire. |
| 626 | with swap_item(globals(), "__import__", lambda *x: 5): |
| 627 | self.assertEqual(foo(), os) |
| 628 | |
| 629 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 630 | class PycacheTests(unittest.TestCase): |
| 631 | # Test the various PEP 3147 related behaviors. |
| 632 | |
| 633 | tag = imp.get_tag() |
| 634 | |
| 635 | def _clean(self): |
| 636 | forget(TESTFN) |
| 637 | rmtree('__pycache__') |
| 638 | unlink(self.source) |
| 639 | |
| 640 | def setUp(self): |
| 641 | self.source = TESTFN + '.py' |
| 642 | self._clean() |
| 643 | with open(self.source, 'w') as fp: |
| 644 | print('# This is a test file written by test_import.py', file=fp) |
| 645 | sys.path.insert(0, os.curdir) |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 646 | importlib.invalidate_caches() |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 647 | |
| 648 | def tearDown(self): |
| 649 | assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]' |
| 650 | del sys.path[0] |
| 651 | self._clean() |
| 652 | |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 653 | @skip_if_dont_write_bytecode |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 654 | def test_import_pyc_path(self): |
| 655 | self.assertFalse(os.path.exists('__pycache__')) |
| 656 | __import__(TESTFN) |
| 657 | self.assertTrue(os.path.exists('__pycache__')) |
| 658 | self.assertTrue(os.path.exists(os.path.join( |
Georg Brandl | fb3c84a | 2010-10-14 07:24:28 +0000 | [diff] [blame] | 659 | '__pycache__', '{}.{}.py{}'.format( |
Benjamin Peterson | d388c4e | 2012-09-25 11:01:41 -0400 | [diff] [blame] | 660 | TESTFN, self.tag, 'c' if __debug__ else 'o')))) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 661 | |
| 662 | @unittest.skipUnless(os.name == 'posix', |
| 663 | "test meaningful only on posix systems") |
Charles-François Natali | 035018d | 2011-10-04 23:35:47 +0200 | [diff] [blame] | 664 | @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, |
Charles-François Natali | 79164c8 | 2011-10-04 20:40:58 +0200 | [diff] [blame] | 665 | "due to varying filesystem permission semantics (issue #11956)") |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 666 | @skip_if_dont_write_bytecode |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 667 | def test_unwritable_directory(self): |
| 668 | # When the umask causes the new __pycache__ directory to be |
| 669 | # unwritable, the import still succeeds but no .pyc file is written. |
| 670 | with temp_umask(0o222): |
| 671 | __import__(TESTFN) |
| 672 | self.assertTrue(os.path.exists('__pycache__')) |
| 673 | self.assertFalse(os.path.exists(os.path.join( |
| 674 | '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag)))) |
| 675 | |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 676 | @skip_if_dont_write_bytecode |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 677 | def test_missing_source(self): |
| 678 | # With PEP 3147 cache layout, removing the source but leaving the pyc |
| 679 | # file does not satisfy the import. |
| 680 | __import__(TESTFN) |
| 681 | pyc_file = imp.cache_from_source(self.source) |
| 682 | self.assertTrue(os.path.exists(pyc_file)) |
| 683 | os.remove(self.source) |
| 684 | forget(TESTFN) |
| 685 | self.assertRaises(ImportError, __import__, TESTFN) |
| 686 | |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 687 | @skip_if_dont_write_bytecode |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 688 | def test_missing_source_legacy(self): |
| 689 | # Like test_missing_source() except that for backward compatibility, |
| 690 | # when the pyc file lives where the py file would have been (and named |
| 691 | # without the tag), it is importable. The __file__ of the imported |
| 692 | # module is the pyc location. |
| 693 | __import__(TESTFN) |
| 694 | # pyc_file gets removed in _clean() via tearDown(). |
| 695 | pyc_file = make_legacy_pyc(self.source) |
| 696 | os.remove(self.source) |
| 697 | unload(TESTFN) |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 698 | importlib.invalidate_caches() |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 699 | m = __import__(TESTFN) |
| 700 | self.assertEqual(m.__file__, |
| 701 | os.path.join(os.curdir, os.path.relpath(pyc_file))) |
| 702 | |
| 703 | def test___cached__(self): |
| 704 | # Modules now also have an __cached__ that points to the pyc file. |
| 705 | m = __import__(TESTFN) |
| 706 | pyc_file = imp.cache_from_source(TESTFN + '.py') |
| 707 | self.assertEqual(m.__cached__, os.path.join(os.curdir, pyc_file)) |
| 708 | |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 709 | @skip_if_dont_write_bytecode |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 710 | def test___cached___legacy_pyc(self): |
| 711 | # Like test___cached__() except that for backward compatibility, |
| 712 | # when the pyc file lives where the py file would have been (and named |
| 713 | # without the tag), it is importable. The __cached__ of the imported |
| 714 | # module is the pyc location. |
| 715 | __import__(TESTFN) |
| 716 | # pyc_file gets removed in _clean() via tearDown(). |
| 717 | pyc_file = make_legacy_pyc(self.source) |
| 718 | os.remove(self.source) |
| 719 | unload(TESTFN) |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 720 | importlib.invalidate_caches() |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 721 | m = __import__(TESTFN) |
| 722 | self.assertEqual(m.__cached__, |
| 723 | os.path.join(os.curdir, os.path.relpath(pyc_file))) |
| 724 | |
Ezio Melotti | c28f6fa | 2013-03-16 19:48:51 +0200 | [diff] [blame] | 725 | @skip_if_dont_write_bytecode |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 726 | def test_package___cached__(self): |
| 727 | # Like test___cached__ but for packages. |
| 728 | def cleanup(): |
Florent Xicluna | 27354cc | 2010-08-16 18:41:19 +0000 | [diff] [blame] | 729 | rmtree('pep3147') |
Antoine Pitrou | d4daa87 | 2012-06-23 18:09:55 +0200 | [diff] [blame] | 730 | unload('pep3147.foo') |
| 731 | unload('pep3147') |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 732 | os.mkdir('pep3147') |
| 733 | self.addCleanup(cleanup) |
| 734 | # Touch the __init__.py |
| 735 | with open(os.path.join('pep3147', '__init__.py'), 'w'): |
| 736 | pass |
| 737 | with open(os.path.join('pep3147', 'foo.py'), 'w'): |
| 738 | pass |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 739 | importlib.invalidate_caches() |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 740 | m = __import__('pep3147.foo') |
| 741 | init_pyc = imp.cache_from_source( |
| 742 | os.path.join('pep3147', '__init__.py')) |
| 743 | self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc)) |
| 744 | foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py')) |
| 745 | self.assertEqual(sys.modules['pep3147.foo'].__cached__, |
| 746 | os.path.join(os.curdir, foo_pyc)) |
| 747 | |
| 748 | def test_package___cached___from_pyc(self): |
| 749 | # Like test___cached__ but ensuring __cached__ when imported from a |
| 750 | # PEP 3147 pyc file. |
| 751 | def cleanup(): |
Florent Xicluna | 27354cc | 2010-08-16 18:41:19 +0000 | [diff] [blame] | 752 | rmtree('pep3147') |
Antoine Pitrou | d4daa87 | 2012-06-23 18:09:55 +0200 | [diff] [blame] | 753 | unload('pep3147.foo') |
| 754 | unload('pep3147') |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 755 | os.mkdir('pep3147') |
| 756 | self.addCleanup(cleanup) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 757 | # Touch the __init__.py |
| 758 | with open(os.path.join('pep3147', '__init__.py'), 'w'): |
| 759 | pass |
| 760 | with open(os.path.join('pep3147', 'foo.py'), 'w'): |
| 761 | pass |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 762 | importlib.invalidate_caches() |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 763 | m = __import__('pep3147.foo') |
| 764 | unload('pep3147.foo') |
| 765 | unload('pep3147') |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 766 | importlib.invalidate_caches() |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 767 | m = __import__('pep3147.foo') |
| 768 | init_pyc = imp.cache_from_source( |
| 769 | os.path.join('pep3147', '__init__.py')) |
| 770 | self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc)) |
| 771 | foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py')) |
| 772 | self.assertEqual(sys.modules['pep3147.foo'].__cached__, |
| 773 | os.path.join(os.curdir, foo_pyc)) |
| 774 | |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 775 | def test_recompute_pyc_same_second(self): |
| 776 | # Even when the source file doesn't change timestamp, a change in |
| 777 | # source size is enough to trigger recomputation of the pyc file. |
| 778 | __import__(TESTFN) |
| 779 | unload(TESTFN) |
| 780 | with open(self.source, 'a') as fp: |
| 781 | print("x = 5", file=fp) |
| 782 | m = __import__(TESTFN) |
| 783 | self.assertEqual(m.x, 5) |
| 784 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 785 | |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 786 | class TestSymbolicallyLinkedPackage(unittest.TestCase): |
| 787 | package_name = 'sample' |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 788 | tagged = package_name + '-tagged' |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 789 | |
| 790 | def setUp(self): |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 791 | test.support.rmtree(self.tagged) |
| 792 | test.support.rmtree(self.package_name) |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 793 | self.orig_sys_path = sys.path[:] |
| 794 | |
| 795 | # create a sample package; imagine you have a package with a tag and |
| 796 | # you want to symbolically link it from its untagged name. |
| 797 | os.mkdir(self.tagged) |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 798 | self.addCleanup(test.support.rmtree, self.tagged) |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 799 | init_file = os.path.join(self.tagged, '__init__.py') |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 800 | test.support.create_empty_file(init_file) |
| 801 | assert os.path.exists(init_file) |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 802 | |
| 803 | # now create a symlink to the tagged package |
| 804 | # sample -> sample-tagged |
Jason R. Coombs | d0118e1 | 2012-07-26 15:21:17 -0400 | [diff] [blame] | 805 | os.symlink(self.tagged, self.package_name, target_is_directory=True) |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 806 | self.addCleanup(test.support.unlink, self.package_name) |
| 807 | importlib.invalidate_caches() |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 808 | |
Jason R. Coombs | d0118e1 | 2012-07-26 15:21:17 -0400 | [diff] [blame] | 809 | self.assertEqual(os.path.isdir(self.package_name), True) |
Jason R. Coombs | 42c9b04 | 2012-06-20 10:24:24 -0400 | [diff] [blame] | 810 | |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 811 | assert os.path.isfile(os.path.join(self.package_name, '__init__.py')) |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 812 | |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 813 | def tearDown(self): |
| 814 | sys.path[:] = self.orig_sys_path |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 815 | |
| 816 | # regression test for issue6727 |
| 817 | @unittest.skipUnless( |
| 818 | not hasattr(sys, 'getwindowsversion') |
| 819 | or sys.getwindowsversion() >= (6, 0), |
| 820 | "Windows Vista or later required") |
| 821 | @test.support.skip_unless_symlink |
| 822 | def test_symlinked_dir_importable(self): |
| 823 | # make sure sample can only be imported from the current directory. |
| 824 | sys.path[:] = ['.'] |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 825 | assert os.path.exists(self.package_name) |
| 826 | assert os.path.exists(os.path.join(self.package_name, '__init__.py')) |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 827 | |
Brett Cannon | 6ee9695 | 2012-07-20 14:22:04 -0400 | [diff] [blame] | 828 | # Try to import the package |
| 829 | importlib.import_module(self.package_name) |
Jason R. Coombs | 71fde31 | 2012-06-17 03:53:47 -0400 | [diff] [blame] | 830 | |
| 831 | |
Antoine Pitrou | 48114b9 | 2012-06-17 22:33:38 +0200 | [diff] [blame] | 832 | @cpython_only |
| 833 | class ImportlibBootstrapTests(unittest.TestCase): |
| 834 | # These tests check that importlib is bootstrapped. |
| 835 | |
| 836 | def test_frozen_importlib(self): |
| 837 | mod = sys.modules['_frozen_importlib'] |
| 838 | self.assertTrue(mod) |
| 839 | |
| 840 | def test_frozen_importlib_is_bootstrap(self): |
| 841 | from importlib import _bootstrap |
| 842 | mod = sys.modules['_frozen_importlib'] |
| 843 | self.assertIs(mod, _bootstrap) |
| 844 | self.assertEqual(mod.__name__, 'importlib._bootstrap') |
| 845 | self.assertEqual(mod.__package__, 'importlib') |
| 846 | self.assertTrue(mod.__file__.endswith('_bootstrap.py'), mod.__file__) |
| 847 | |
Nick Coghlan | be7e49f | 2012-07-20 23:40:09 +1000 | [diff] [blame] | 848 | def test_there_can_be_only_one(self): |
| 849 | # Issue #15386 revealed a tricky loophole in the bootstrapping |
| 850 | # This test is technically redundant, since the bug caused importing |
| 851 | # this test module to crash completely, but it helps prove the point |
| 852 | from importlib import machinery |
| 853 | mod = sys.modules['_frozen_importlib'] |
| 854 | self.assertIs(machinery.FileFinder, mod.FileFinder) |
| 855 | self.assertIs(imp.new_module, mod.new_module) |
| 856 | |
Antoine Pitrou | 48114b9 | 2012-06-17 22:33:38 +0200 | [diff] [blame] | 857 | |
Brett Cannon | a53cca3 | 2013-07-06 17:56:43 -0400 | [diff] [blame] | 858 | @cpython_only |
| 859 | class GetSourcefileTests(unittest.TestCase): |
| 860 | |
| 861 | """Test importlib._bootstrap._get_sourcefile() as used by the C API. |
| 862 | |
| 863 | Because of the peculiarities of the need of this function, the tests are |
| 864 | knowingly whitebox tests. |
| 865 | |
| 866 | """ |
| 867 | |
| 868 | def test_get_sourcefile(self): |
| 869 | # Given a valid bytecode path, return the path to the corresponding |
| 870 | # source file if it exists. |
| 871 | with mock.patch('importlib._bootstrap._path_isfile') as _path_isfile: |
| 872 | _path_isfile.return_value = True; |
| 873 | path = TESTFN + '.pyc' |
| 874 | expect = TESTFN + '.py' |
| 875 | self.assertEqual(_get_sourcefile(path), expect) |
| 876 | |
| 877 | def test_get_sourcefile_no_source(self): |
| 878 | # Given a valid bytecode path without a corresponding source path, |
| 879 | # return the original bytecode path. |
| 880 | with mock.patch('importlib._bootstrap._path_isfile') as _path_isfile: |
| 881 | _path_isfile.return_value = False; |
| 882 | path = TESTFN + '.pyc' |
| 883 | self.assertEqual(_get_sourcefile(path), path) |
| 884 | |
| 885 | def test_get_sourcefile_bad_ext(self): |
| 886 | # Given a path with an invalid bytecode extension, return the |
| 887 | # bytecode path passed as the argument. |
| 888 | path = TESTFN + '.bad_ext' |
| 889 | self.assertEqual(_get_sourcefile(path), path) |
| 890 | |
| 891 | |
Antoine Pitrou | bc07a5c | 2012-07-08 12:01:27 +0200 | [diff] [blame] | 892 | class ImportTracebackTests(unittest.TestCase): |
| 893 | |
| 894 | def setUp(self): |
| 895 | os.mkdir(TESTFN) |
| 896 | self.old_path = sys.path[:] |
| 897 | sys.path.insert(0, TESTFN) |
| 898 | |
| 899 | def tearDown(self): |
| 900 | sys.path[:] = self.old_path |
| 901 | rmtree(TESTFN) |
| 902 | |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 903 | def create_module(self, mod, contents, ext=".py"): |
| 904 | fname = os.path.join(TESTFN, mod + ext) |
| 905 | with open(fname, "w") as f: |
Antoine Pitrou | bc07a5c | 2012-07-08 12:01:27 +0200 | [diff] [blame] | 906 | f.write(contents) |
| 907 | self.addCleanup(unload, mod) |
| 908 | importlib.invalidate_caches() |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 909 | return fname |
Antoine Pitrou | bc07a5c | 2012-07-08 12:01:27 +0200 | [diff] [blame] | 910 | |
| 911 | def assert_traceback(self, tb, files): |
| 912 | deduped_files = [] |
| 913 | while tb: |
| 914 | code = tb.tb_frame.f_code |
| 915 | fn = code.co_filename |
| 916 | if not deduped_files or fn != deduped_files[-1]: |
| 917 | deduped_files.append(fn) |
| 918 | tb = tb.tb_next |
| 919 | self.assertEqual(len(deduped_files), len(files), deduped_files) |
| 920 | for fn, pat in zip(deduped_files, files): |
Antoine Pitrou | 6803855 | 2012-07-08 13:16:15 +0200 | [diff] [blame] | 921 | self.assertIn(pat, fn) |
Antoine Pitrou | bc07a5c | 2012-07-08 12:01:27 +0200 | [diff] [blame] | 922 | |
| 923 | def test_nonexistent_module(self): |
| 924 | try: |
| 925 | # assertRaises() clears __traceback__ |
| 926 | import nonexistent_xyzzy |
| 927 | except ImportError as e: |
| 928 | tb = e.__traceback__ |
| 929 | else: |
| 930 | self.fail("ImportError should have been raised") |
| 931 | self.assert_traceback(tb, [__file__]) |
| 932 | |
| 933 | def test_nonexistent_module_nested(self): |
| 934 | self.create_module("foo", "import nonexistent_xyzzy") |
| 935 | try: |
| 936 | import foo |
| 937 | except ImportError as e: |
| 938 | tb = e.__traceback__ |
| 939 | else: |
| 940 | self.fail("ImportError should have been raised") |
| 941 | self.assert_traceback(tb, [__file__, 'foo.py']) |
| 942 | |
| 943 | def test_exec_failure(self): |
| 944 | self.create_module("foo", "1/0") |
| 945 | try: |
| 946 | import foo |
| 947 | except ZeroDivisionError as e: |
| 948 | tb = e.__traceback__ |
| 949 | else: |
| 950 | self.fail("ZeroDivisionError should have been raised") |
| 951 | self.assert_traceback(tb, [__file__, 'foo.py']) |
| 952 | |
| 953 | def test_exec_failure_nested(self): |
| 954 | self.create_module("foo", "import bar") |
| 955 | self.create_module("bar", "1/0") |
| 956 | try: |
| 957 | import foo |
| 958 | except ZeroDivisionError as e: |
| 959 | tb = e.__traceback__ |
| 960 | else: |
| 961 | self.fail("ZeroDivisionError should have been raised") |
| 962 | self.assert_traceback(tb, [__file__, 'foo.py', 'bar.py']) |
| 963 | |
Nick Coghlan | 5ee9892 | 2012-07-29 20:30:36 +1000 | [diff] [blame] | 964 | # A few more examples from issue #15425 |
| 965 | def test_syntax_error(self): |
| 966 | self.create_module("foo", "invalid syntax is invalid") |
| 967 | try: |
| 968 | import foo |
| 969 | except SyntaxError as e: |
| 970 | tb = e.__traceback__ |
| 971 | else: |
| 972 | self.fail("SyntaxError should have been raised") |
| 973 | self.assert_traceback(tb, [__file__]) |
| 974 | |
| 975 | def _setup_broken_package(self, parent, child): |
| 976 | pkg_name = "_parent_foo" |
Nick Coghlan | 336d9ac | 2012-07-31 21:39:42 +1000 | [diff] [blame] | 977 | self.addCleanup(unload, pkg_name) |
| 978 | pkg_path = os.path.join(TESTFN, pkg_name) |
| 979 | os.mkdir(pkg_path) |
Nick Coghlan | 5ee9892 | 2012-07-29 20:30:36 +1000 | [diff] [blame] | 980 | # Touch the __init__.py |
Nick Coghlan | 336d9ac | 2012-07-31 21:39:42 +1000 | [diff] [blame] | 981 | init_path = os.path.join(pkg_path, '__init__.py') |
Nick Coghlan | 5ee9892 | 2012-07-29 20:30:36 +1000 | [diff] [blame] | 982 | with open(init_path, 'w') as f: |
| 983 | f.write(parent) |
Nick Coghlan | 336d9ac | 2012-07-31 21:39:42 +1000 | [diff] [blame] | 984 | bar_path = os.path.join(pkg_path, 'bar.py') |
Nick Coghlan | 5ee9892 | 2012-07-29 20:30:36 +1000 | [diff] [blame] | 985 | with open(bar_path, 'w') as f: |
| 986 | f.write(child) |
| 987 | importlib.invalidate_caches() |
| 988 | return init_path, bar_path |
| 989 | |
| 990 | def test_broken_submodule(self): |
| 991 | init_path, bar_path = self._setup_broken_package("", "1/0") |
| 992 | try: |
| 993 | import _parent_foo.bar |
| 994 | except ZeroDivisionError as e: |
| 995 | tb = e.__traceback__ |
| 996 | else: |
| 997 | self.fail("ZeroDivisionError should have been raised") |
| 998 | self.assert_traceback(tb, [__file__, bar_path]) |
| 999 | |
| 1000 | def test_broken_from(self): |
| 1001 | init_path, bar_path = self._setup_broken_package("", "1/0") |
| 1002 | try: |
| 1003 | from _parent_foo import bar |
| 1004 | except ZeroDivisionError as e: |
| 1005 | tb = e.__traceback__ |
| 1006 | else: |
| 1007 | self.fail("ImportError should have been raised") |
| 1008 | self.assert_traceback(tb, [__file__, bar_path]) |
| 1009 | |
| 1010 | def test_broken_parent(self): |
| 1011 | init_path, bar_path = self._setup_broken_package("1/0", "") |
| 1012 | try: |
| 1013 | import _parent_foo.bar |
| 1014 | except ZeroDivisionError as e: |
| 1015 | tb = e.__traceback__ |
| 1016 | else: |
| 1017 | self.fail("ZeroDivisionError should have been raised") |
| 1018 | self.assert_traceback(tb, [__file__, init_path]) |
| 1019 | |
| 1020 | def test_broken_parent_from(self): |
| 1021 | init_path, bar_path = self._setup_broken_package("1/0", "") |
| 1022 | try: |
| 1023 | from _parent_foo import bar |
| 1024 | except ZeroDivisionError as e: |
| 1025 | tb = e.__traceback__ |
| 1026 | else: |
| 1027 | self.fail("ZeroDivisionError should have been raised") |
| 1028 | self.assert_traceback(tb, [__file__, init_path]) |
| 1029 | |
Antoine Pitrou | bc07a5c | 2012-07-08 12:01:27 +0200 | [diff] [blame] | 1030 | @cpython_only |
| 1031 | def test_import_bug(self): |
| 1032 | # We simulate a bug in importlib and check that it's not stripped |
| 1033 | # away from the traceback. |
| 1034 | self.create_module("foo", "") |
| 1035 | importlib = sys.modules['_frozen_importlib'] |
| 1036 | old_load_module = importlib.SourceLoader.load_module |
| 1037 | try: |
| 1038 | def load_module(*args): |
| 1039 | 1/0 |
| 1040 | importlib.SourceLoader.load_module = load_module |
| 1041 | try: |
| 1042 | import foo |
| 1043 | except ZeroDivisionError as e: |
| 1044 | tb = e.__traceback__ |
| 1045 | else: |
| 1046 | self.fail("ZeroDivisionError should have been raised") |
| 1047 | self.assert_traceback(tb, [__file__, '<frozen importlib', __file__]) |
| 1048 | finally: |
| 1049 | importlib.SourceLoader.load_module = old_load_module |
| 1050 | |
| 1051 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1052 | def test_main(verbose=None): |
Nick Coghlan | eb8d627 | 2012-10-19 23:32:00 +1000 | [diff] [blame] | 1053 | run_unittest(ImportTests, PycacheTests, FilePermissionTests, |
Brett Cannon | ba52586 | 2012-07-20 14:01:34 -0400 | [diff] [blame] | 1054 | PycRewritingTests, PathsTests, RelativeImportTests, |
| 1055 | OverridingImportBuiltinTests, |
Brett Cannon | a53cca3 | 2013-07-06 17:56:43 -0400 | [diff] [blame] | 1056 | ImportlibBootstrapTests, GetSourcefileTests, |
Brett Cannon | ba52586 | 2012-07-20 14:01:34 -0400 | [diff] [blame] | 1057 | TestSymbolicallyLinkedPackage, |
| 1058 | ImportTracebackTests) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1059 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 1060 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1061 | if __name__ == '__main__': |
Collin Winter | 88e333d | 2010-03-17 03:09:21 +0000 | [diff] [blame] | 1062 | # Test needs to be a package, so we can do relative imports. |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 1063 | from test.test_import import test_main |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1064 | test_main() |