| 1 |
import builtins |
| 2 |
import errno |
| 3 |
import glob |
| 4 |
import importlib.util |
| 5 |
from importlib._bootstrap_external import _get_sourcefile |
| 6 |
import marshal |
| 7 |
import os |
| 8 |
import py_compile |
| 9 |
import random |
| 10 |
import shutil |
| 11 |
import stat |
| 12 |
import subprocess |
| 13 |
import sys |
| 14 |
import textwrap |
| 15 |
import threading |
| 16 |
import time |
| 17 |
import unittest |
| 18 |
from unittest import mock |
| 19 |
import _imp |
| 20 |
|
| 21 |
from test.support import os_helper, impl_detail |
| 22 |
from test.support import ( |
| 23 |
STDLIB_DIR, is_jython, swap_attr, swap_item, cpython_only, is_emscripten, |
| 24 |
is_wasi) |
| 25 |
from test.support.import_helper import ( |
| 26 |
forget, make_legacy_pyc, unlink, unload, ready_to_import, |
| 27 |
DirsOnSysPath, CleanImport) |
| 28 |
from test.support.os_helper import ( |
| 29 |
TESTFN, rmtree, temp_umask, TESTFN_UNENCODABLE) |
| 30 |
from test.support import script_helper |
| 31 |
from test.support import threading_helper |
| 32 |
from test.test_importlib.util import uncache |
| 33 |
from types import ModuleType |
| 34 |
|
| 35 |
|
| 36 |
skip_if_dont_write_bytecode = unittest.skipIf( |
| 37 |
sys.dont_write_bytecode, |
| 38 |
"test meaningful only when writing bytecode") |
| 39 |
|
| 40 |
def remove_files(name): |
| 41 |
for f in (name + ".py", |
| 42 |
name + ".pyc", |
| 43 |
name + ".pyw", |
| 44 |
name + "$py.class"): |
| 45 |
unlink(f) |
| 46 |
rmtree('__pycache__') |
| 47 |
|
| 48 |
|
| 49 |
class ImportTests(unittest.TestCase): |
| 50 |
|
| 51 |
def setUp(self): |
| 52 |
remove_files(TESTFN) |
| 53 |
importlib.invalidate_caches() |
| 54 |
|
| 55 |
def tearDown(self): |
| 56 |
unload(TESTFN) |
| 57 |
|
| 58 |
def test_import_raises_ModuleNotFoundError(self): |
| 59 |
with self.assertRaises(ModuleNotFoundError): |
| 60 |
import something_that_should_not_exist_anywhere |
| 61 |
|
| 62 |
def test_from_import_missing_module_raises_ModuleNotFoundError(self): |
| 63 |
with self.assertRaises(ModuleNotFoundError): |
| 64 |
from something_that_should_not_exist_anywhere import blah |
| 65 |
|
| 66 |
def test_from_import_missing_attr_raises_ImportError(self): |
| 67 |
with self.assertRaises(ImportError): |
| 68 |
from importlib import something_that_should_not_exist_anywhere |
| 69 |
|
| 70 |
def test_from_import_missing_attr_has_name_and_path(self): |
| 71 |
with CleanImport('os'): |
| 72 |
import os |
| 73 |
with self.assertRaises(ImportError) as cm: |
| 74 |
from os import i_dont_exist |
| 75 |
self.assertEqual(cm.exception.name, 'os') |
| 76 |
self.assertEqual(cm.exception.path, os.__file__) |
| 77 |
self.assertRegex(str(cm.exception), r"cannot import name 'i_dont_exist' from 'os' \(.*os.py\)") |
| 78 |
|
| 79 |
@cpython_only |
| 80 |
def test_from_import_missing_attr_has_name_and_so_path(self): |
| 81 |
import _testcapi |
| 82 |
with self.assertRaises(ImportError) as cm: |
| 83 |
from _testcapi import i_dont_exist |
| 84 |
self.assertEqual(cm.exception.name, '_testcapi') |
| 85 |
if hasattr(_testcapi, "__file__"): |
| 86 |
self.assertEqual(cm.exception.path, _testcapi.__file__) |
| 87 |
self.assertRegex( |
| 88 |
str(cm.exception), |
| 89 |
r"cannot import name 'i_dont_exist' from '_testcapi' \(.*\.(so|pyd)\)" |
| 90 |
) |
| 91 |
else: |
| 92 |
self.assertEqual( |
| 93 |
str(cm.exception), |
| 94 |
"cannot import name 'i_dont_exist' from '_testcapi' (unknown location)" |
| 95 |
) |
| 96 |
|
| 97 |
def test_from_import_missing_attr_has_name(self): |
| 98 |
with self.assertRaises(ImportError) as cm: |
| 99 |
|
| 100 |
from _warning import i_dont_exist |
| 101 |
self.assertEqual(cm.exception.name, '_warning') |
| 102 |
self.assertIsNone(cm.exception.path) |
| 103 |
|
| 104 |
def test_from_import_missing_attr_path_is_canonical(self): |
| 105 |
with self.assertRaises(ImportError) as cm: |
| 106 |
from os.path import i_dont_exist |
| 107 |
self.assertIn(cm.exception.name, {'posixpath', 'ntpath'}) |
| 108 |
self.assertIsNotNone(cm.exception) |
| 109 |
|
| 110 |
def test_from_import_star_invalid_type(self): |
| 111 |
import re |
| 112 |
with ready_to_import() as (name, path): |
| 113 |
with open(path, 'w', encoding='utf-8') as f: |
| 114 |
f.write("__all__ = [b'invalid_type']") |
| 115 |
globals = {} |
| 116 |
with self.assertRaisesRegex( |
| 117 |
TypeError, f"{re.escape(name)}\\.__all__ must be str" |
| 118 |
): |
| 119 |
exec(f"from {name} import *", globals) |
| 120 |
self.assertNotIn(b"invalid_type", globals) |
| 121 |
with ready_to_import() as (name, path): |
| 122 |
with open(path, 'w', encoding='utf-8') as f: |
| 123 |
f.write("globals()[b'invalid_type'] = object()") |
| 124 |
globals = {} |
| 125 |
with self.assertRaisesRegex( |
| 126 |
TypeError, f"{re.escape(name)}\\.__dict__ must be str" |
| 127 |
): |
| 128 |
exec(f"from {name} import *", globals) |
| 129 |
self.assertNotIn(b"invalid_type", globals) |
| 130 |
|
| 131 |
def test_case_sensitivity(self): |
| 132 |
|
| 133 |
|
| 134 |
with self.assertRaises(ImportError): |
| 135 |
import RAnDoM |
| 136 |
|
| 137 |
def test_double_const(self): |
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
from test.test_import.data import double_const |
| 142 |
unload('test.test_import.data.double_const') |
| 143 |
from test.test_import.data import double_const |
| 144 |
|
| 145 |
def test_import(self): |
| 146 |
def test_with_extension(ext): |
| 147 |
|
| 148 |
source = TESTFN + ext |
| 149 |
if is_jython: |
| 150 |
pyc = TESTFN + "$py.class" |
| 151 |
else: |
| 152 |
pyc = TESTFN + ".pyc" |
| 153 |
|
| 154 |
with open(source, "w", encoding='utf-8') as f: |
| 155 |
print("# This tests Python's ability to import a", |
| 156 |
ext, "file.", file=f) |
| 157 |
a = random.randrange(1000) |
| 158 |
b = random.randrange(1000) |
| 159 |
print("a =", a, file=f) |
| 160 |
print("b =", b, file=f) |
| 161 |
|
| 162 |
if TESTFN in sys.modules: |
| 163 |
del sys.modules[TESTFN] |
| 164 |
importlib.invalidate_caches() |
| 165 |
try: |
| 166 |
try: |
| 167 |
mod = __import__(TESTFN) |
| 168 |
except ImportError as err: |
| 169 |
self.fail("import from %s failed: %s" % (ext, err)) |
| 170 |
|
| 171 |
self.assertEqual(mod.a, a, |
| 172 |
"module loaded (%s) but contents invalid" % mod) |
| 173 |
self.assertEqual(mod.b, b, |
| 174 |
"module loaded (%s) but contents invalid" % mod) |
| 175 |
finally: |
| 176 |
forget(TESTFN) |
| 177 |
unlink(source) |
| 178 |
unlink(pyc) |
| 179 |
|
| 180 |
sys.path.insert(0, os.curdir) |
| 181 |
try: |
| 182 |
test_with_extension(".py") |
| 183 |
if sys.platform.startswith("win"): |
| 184 |
for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]: |
| 185 |
test_with_extension(ext) |
| 186 |
finally: |
| 187 |
del sys.path[0] |
| 188 |
|
| 189 |
def test_module_with_large_stack(self, module='longlist'): |
| 190 |
|
| 191 |
filename = module + '.py' |
| 192 |
|
| 193 |
|
| 194 |
with open(filename, 'w', encoding='utf-8') as f: |
| 195 |
f.write('d = [\n') |
| 196 |
for i in range(65000): |
| 197 |
f.write('"",\n') |
| 198 |
f.write(']') |
| 199 |
|
| 200 |
try: |
| 201 |
|
| 202 |
|
| 203 |
py_compile.compile(filename) |
| 204 |
finally: |
| 205 |
unlink(filename) |
| 206 |
|
| 207 |
|
| 208 |
sys.path.append('') |
| 209 |
importlib.invalidate_caches() |
| 210 |
|
| 211 |
namespace = {} |
| 212 |
try: |
| 213 |
make_legacy_pyc(filename) |
| 214 |
|
| 215 |
exec('import ' + module, None, namespace) |
| 216 |
finally: |
| 217 |
|
| 218 |
del sys.path[-1] |
| 219 |
unlink(filename + 'c') |
| 220 |
unlink(filename + 'o') |
| 221 |
|
| 222 |
|
| 223 |
namespace.clear() |
| 224 |
try: |
| 225 |
del sys.modules[module] |
| 226 |
except KeyError: |
| 227 |
pass |
| 228 |
|
| 229 |
def test_failing_import_sticks(self): |
| 230 |
source = TESTFN + ".py" |
| 231 |
with open(source, "w", encoding='utf-8') as f: |
| 232 |
print("a = 1/0", file=f) |
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
sys.path.insert(0, os.curdir) |
| 237 |
importlib.invalidate_caches() |
| 238 |
if TESTFN in sys.modules: |
| 239 |
del sys.modules[TESTFN] |
| 240 |
try: |
| 241 |
for i in [1, 2, 3]: |
| 242 |
self.assertRaises(ZeroDivisionError, __import__, TESTFN) |
| 243 |
self.assertNotIn(TESTFN, sys.modules, |
| 244 |
"damaged module in sys.modules on %i try" % i) |
| 245 |
finally: |
| 246 |
del sys.path[0] |
| 247 |
remove_files(TESTFN) |
| 248 |
|
| 249 |
def test_import_name_binding(self): |
| 250 |
|
| 251 |
import test as x |
| 252 |
import test.support |
| 253 |
self.assertIs(x, test, x.__name__) |
| 254 |
self.assertTrue(hasattr(test.support, "__file__")) |
| 255 |
|
| 256 |
|
| 257 |
import test.support as y |
| 258 |
self.assertIs(y, test.support, y.__name__) |
| 259 |
|
| 260 |
def test_issue31286(self): |
| 261 |
|
| 262 |
try: |
| 263 |
x = ... |
| 264 |
finally: |
| 265 |
import test.support.script_helper as x |
| 266 |
|
| 267 |
|
| 268 |
i = 0 |
| 269 |
while i < 10: |
| 270 |
import test.support.script_helper as x |
| 271 |
i += 1 |
| 272 |
|
| 273 |
|
| 274 |
for i in range(2): |
| 275 |
import test.support.script_helper as x |
| 276 |
|
| 277 |
def test_failing_reload(self): |
| 278 |
|
| 279 |
source = TESTFN + os.extsep + "py" |
| 280 |
with open(source, "w", encoding='utf-8') as f: |
| 281 |
f.write("a = 1\nb=2\n") |
| 282 |
|
| 283 |
sys.path.insert(0, os.curdir) |
| 284 |
try: |
| 285 |
mod = __import__(TESTFN) |
| 286 |
self.assertIn(TESTFN, sys.modules) |
| 287 |
self.assertEqual(mod.a, 1, "module has wrong attribute values") |
| 288 |
self.assertEqual(mod.b, 2, "module has wrong attribute values") |
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
remove_files(TESTFN) |
| 295 |
|
| 296 |
|
| 297 |
with open(source, "w", encoding='utf-8') as f: |
| 298 |
f.write("a = 10\nb=20//0\n") |
| 299 |
|
| 300 |
self.assertRaises(ZeroDivisionError, importlib.reload, mod) |
| 301 |
|
| 302 |
mod = sys.modules.get(TESTFN) |
| 303 |
self.assertIsNotNone(mod, "expected module to be in sys.modules") |
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
self.assertEqual(mod.a, 10, "module has wrong attribute values") |
| 308 |
self.assertEqual(mod.b, 2, "module has wrong attribute values") |
| 309 |
|
| 310 |
finally: |
| 311 |
del sys.path[0] |
| 312 |
remove_files(TESTFN) |
| 313 |
unload(TESTFN) |
| 314 |
|
| 315 |
@skip_if_dont_write_bytecode |
| 316 |
def test_file_to_source(self): |
| 317 |
|
| 318 |
source = TESTFN + ".py" |
| 319 |
with open(source, "w", encoding='utf-8') as f: |
| 320 |
f.write("test = None\n") |
| 321 |
|
| 322 |
sys.path.insert(0, os.curdir) |
| 323 |
try: |
| 324 |
mod = __import__(TESTFN) |
| 325 |
self.assertTrue(mod.__file__.endswith('.py')) |
| 326 |
os.remove(source) |
| 327 |
del sys.modules[TESTFN] |
| 328 |
make_legacy_pyc(source) |
| 329 |
importlib.invalidate_caches() |
| 330 |
mod = __import__(TESTFN) |
| 331 |
base, ext = os.path.splitext(mod.__file__) |
| 332 |
self.assertEqual(ext, '.pyc') |
| 333 |
finally: |
| 334 |
del sys.path[0] |
| 335 |
remove_files(TESTFN) |
| 336 |
if TESTFN in sys.modules: |
| 337 |
del sys.modules[TESTFN] |
| 338 |
|
| 339 |
def test_import_by_filename(self): |
| 340 |
path = os.path.abspath(TESTFN) |
| 341 |
encoding = sys.getfilesystemencoding() |
| 342 |
try: |
| 343 |
path.encode(encoding) |
| 344 |
except UnicodeEncodeError: |
| 345 |
self.skipTest('path is not encodable to {}'.format(encoding)) |
| 346 |
with self.assertRaises(ImportError) as c: |
| 347 |
__import__(path) |
| 348 |
|
| 349 |
def test_import_in_del_does_not_crash(self): |
| 350 |
|
| 351 |
testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\ |
| 352 |
import sys |
| 353 |
class C: |
| 354 |
def __del__(self): |
| 355 |
import importlib |
| 356 |
sys.argv.insert(0, C()) |
| 357 |
""")) |
| 358 |
script_helper.assert_python_ok(testfn) |
| 359 |
|
| 360 |
@skip_if_dont_write_bytecode |
| 361 |
def test_timestamp_overflow(self): |
| 362 |
|
| 363 |
|
| 364 |
sys.path.insert(0, os.curdir) |
| 365 |
try: |
| 366 |
source = TESTFN + ".py" |
| 367 |
compiled = importlib.util.cache_from_source(source) |
| 368 |
with open(source, 'w', encoding='utf-8') as f: |
| 369 |
pass |
| 370 |
try: |
| 371 |
os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5)) |
| 372 |
except OverflowError: |
| 373 |
self.skipTest("cannot set modification time to large integer") |
| 374 |
except OSError as e: |
| 375 |
if e.errno not in (getattr(errno, 'EOVERFLOW', None), |
| 376 |
getattr(errno, 'EINVAL', None)): |
| 377 |
raise |
| 378 |
self.skipTest("cannot set modification time to large integer ({})".format(e)) |
| 379 |
__import__(TESTFN) |
| 380 |
|
| 381 |
os.stat(compiled) |
| 382 |
finally: |
| 383 |
del sys.path[0] |
| 384 |
remove_files(TESTFN) |
| 385 |
|
| 386 |
def test_bogus_fromlist(self): |
| 387 |
try: |
| 388 |
__import__('http', fromlist=['blah']) |
| 389 |
except ImportError: |
| 390 |
self.fail("fromlist must allow bogus names") |
| 391 |
|
| 392 |
@cpython_only |
| 393 |
def test_delete_builtins_import(self): |
| 394 |
args = ["-c", "del __builtins__.__import__; import os"] |
| 395 |
popen = script_helper.spawn_python(*args) |
| 396 |
stdout, stderr = popen.communicate() |
| 397 |
self.assertIn(b"ImportError", stdout) |
| 398 |
|
| 399 |
def test_from_import_message_for_nonexistent_module(self): |
| 400 |
with self.assertRaisesRegex(ImportError, "^No module named 'bogus'"): |
| 401 |
from bogus import foo |
| 402 |
|
| 403 |
def test_from_import_message_for_existing_module(self): |
| 404 |
with self.assertRaisesRegex(ImportError, "^cannot import name 'bogus'"): |
| 405 |
from re import bogus |
| 406 |
|
| 407 |
def test_from_import_AttributeError(self): |
| 408 |
|
| 409 |
|
| 410 |
class AlwaysAttributeError: |
| 411 |
def __getattr__(self, _): |
| 412 |
raise AttributeError |
| 413 |
|
| 414 |
module_name = 'test_from_import_AttributeError' |
| 415 |
self.addCleanup(unload, module_name) |
| 416 |
sys.modules[module_name] = AlwaysAttributeError() |
| 417 |
with self.assertRaises(ImportError) as cm: |
| 418 |
from test_from_import_AttributeError import does_not_exist |
| 419 |
|
| 420 |
self.assertEqual(str(cm.exception), |
| 421 |
"cannot import name 'does_not_exist' from '<unknown module name>' (unknown location)") |
| 422 |
|
| 423 |
@cpython_only |
| 424 |
def test_issue31492(self): |
| 425 |
|
| 426 |
|
| 427 |
|
| 428 |
with swap_attr(os, '__name__', None): |
| 429 |
with self.assertRaises(ImportError): |
| 430 |
from os import does_not_exist |
| 431 |
|
| 432 |
with self.assertRaises(AttributeError): |
| 433 |
os.does_not_exist |
| 434 |
|
| 435 |
@threading_helper.requires_working_threading() |
| 436 |
def test_concurrency(self): |
| 437 |
|
| 438 |
|
| 439 |
def delay_has_deadlock(frame, event, arg): |
| 440 |
if event == 'call' and frame.f_code.co_name == 'has_deadlock': |
| 441 |
time.sleep(0.1) |
| 442 |
|
| 443 |
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'data')) |
| 444 |
try: |
| 445 |
exc = None |
| 446 |
def run(): |
| 447 |
sys.settrace(delay_has_deadlock) |
| 448 |
event.wait() |
| 449 |
try: |
| 450 |
import package |
| 451 |
except BaseException as e: |
| 452 |
nonlocal exc |
| 453 |
exc = e |
| 454 |
sys.settrace(None) |
| 455 |
|
| 456 |
for i in range(10): |
| 457 |
event = threading.Event() |
| 458 |
threads = [threading.Thread(target=run) for x in range(2)] |
| 459 |
try: |
| 460 |
with threading_helper.start_threads(threads, event.set): |
| 461 |
time.sleep(0) |
| 462 |
finally: |
| 463 |
sys.modules.pop('package', None) |
| 464 |
sys.modules.pop('package.submodule', None) |
| 465 |
if exc is not None: |
| 466 |
raise exc |
| 467 |
finally: |
| 468 |
del sys.path[0] |
| 469 |
|
| 470 |
@unittest.skipUnless(sys.platform == "win32", "Windows-specific") |
| 471 |
def test_dll_dependency_import(self): |
| 472 |
from _winapi import GetModuleFileName |
| 473 |
dllname = GetModuleFileName(sys.dllhandle) |
| 474 |
pydname = importlib.util.find_spec("_sqlite3").origin |
| 475 |
depname = os.path.join( |
| 476 |
os.path.dirname(pydname), |
| 477 |
"sqlite3{}.dll".format("_d" if "_d" in pydname else "")) |
| 478 |
|
| 479 |
with os_helper.temp_dir() as tmp: |
| 480 |
tmp2 = os.path.join(tmp, "DLLs") |
| 481 |
os.mkdir(tmp2) |
| 482 |
|
| 483 |
pyexe = os.path.join(tmp, os.path.basename(sys.executable)) |
| 484 |
shutil.copy(sys.executable, pyexe) |
| 485 |
shutil.copy(dllname, tmp) |
| 486 |
for f in glob.glob(os.path.join(glob.escape(sys.prefix), "vcruntime*.dll")): |
| 487 |
shutil.copy(f, tmp) |
| 488 |
|
| 489 |
shutil.copy(pydname, tmp2) |
| 490 |
|
| 491 |
env = None |
| 492 |
env = {k.upper(): os.environ[k] for k in os.environ} |
| 493 |
env["PYTHONPATH"] = tmp2 + ";" + STDLIB_DIR |
| 494 |
|
| 495 |
|
| 496 |
subprocess.check_call([ |
| 497 |
pyexe, "-Sc", ";".join([ |
| 498 |
"import os", |
| 499 |
"p = os.add_dll_directory({!r})".format( |
| 500 |
os.path.dirname(depname)), |
| 501 |
"import _sqlite3", |
| 502 |
"p.close" |
| 503 |
])], |
| 504 |
stderr=subprocess.STDOUT, |
| 505 |
env=env, |
| 506 |
cwd=os.path.dirname(pyexe)) |
| 507 |
|
| 508 |
|
| 509 |
shutil.copy(depname, tmp2) |
| 510 |
subprocess.check_call([pyexe, "-Sc", "import _sqlite3"], |
| 511 |
stderr=subprocess.STDOUT, |
| 512 |
env=env, |
| 513 |
cwd=os.path.dirname(pyexe)) |
| 514 |
|
| 515 |
@impl_detail("pypy does not accept a data argument to get_frozen_object", pypy=False) |
| 516 |
def test_issue105979(self): |
| 517 |
|
| 518 |
with self.assertRaises(ImportError) as cm: |
| 519 |
_imp.get_frozen_object("x", b"6\'\xd5Cu\x12") |
| 520 |
self.assertIn("Frozen object named 'x' is invalid", |
| 521 |
str(cm.exception)) |
| 522 |
|
| 523 |
|
| 524 |
@skip_if_dont_write_bytecode |
| 525 |
class FilePermissionTests(unittest.TestCase): |
| 526 |
|
| 527 |
|
| 528 |
@unittest.skipUnless(os.name == 'posix', |
| 529 |
"test meaningful only on posix systems") |
| 530 |
@unittest.skipIf( |
| 531 |
is_emscripten or is_wasi, |
| 532 |
"Emscripten's/WASI's umask is a stub." |
| 533 |
) |
| 534 |
def test_creation_mode(self): |
| 535 |
mask = 0o022 |
| 536 |
with temp_umask(mask), ready_to_import() as (name, path): |
| 537 |
cached_path = importlib.util.cache_from_source(path) |
| 538 |
module = __import__(name) |
| 539 |
if not os.path.exists(cached_path): |
| 540 |
self.fail("__import__ did not result in creation of " |
| 541 |
"a .pyc file") |
| 542 |
stat_info = os.stat(cached_path) |
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), |
| 547 |
oct(0o666 & ~mask)) |
| 548 |
|
| 549 |
@unittest.skipUnless(os.name == 'posix', |
| 550 |
"test meaningful only on posix systems") |
| 551 |
@os_helper.skip_unless_working_chmod |
| 552 |
def test_cached_mode_issue_2051(self): |
| 553 |
|
| 554 |
mode = 0o600 |
| 555 |
with temp_umask(0o022), ready_to_import() as (name, path): |
| 556 |
cached_path = importlib.util.cache_from_source(path) |
| 557 |
os.chmod(path, mode) |
| 558 |
__import__(name) |
| 559 |
if not os.path.exists(cached_path): |
| 560 |
self.fail("__import__ did not result in creation of " |
| 561 |
"a .pyc file") |
| 562 |
stat_info = os.stat(cached_path) |
| 563 |
|
| 564 |
self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(mode)) |
| 565 |
|
| 566 |
@unittest.skipUnless(os.name == 'posix', |
| 567 |
"test meaningful only on posix systems") |
| 568 |
@os_helper.skip_unless_working_chmod |
| 569 |
def test_cached_readonly(self): |
| 570 |
mode = 0o400 |
| 571 |
with temp_umask(0o022), ready_to_import() as (name, path): |
| 572 |
cached_path = importlib.util.cache_from_source(path) |
| 573 |
os.chmod(path, mode) |
| 574 |
__import__(name) |
| 575 |
if not os.path.exists(cached_path): |
| 576 |
self.fail("__import__ did not result in creation of " |
| 577 |
"a .pyc file") |
| 578 |
stat_info = os.stat(cached_path) |
| 579 |
|
| 580 |
expected = mode | 0o200 |
| 581 |
self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(expected)) |
| 582 |
|
| 583 |
def test_pyc_always_writable(self): |
| 584 |
|
| 585 |
|
| 586 |
with ready_to_import() as (name, path): |
| 587 |
|
| 588 |
with open(path, 'w', encoding='utf-8') as f: |
| 589 |
f.write("x = 'original'\n") |
| 590 |
|
| 591 |
s = os.stat(path) |
| 592 |
os.utime(path, (s.st_atime, s.st_mtime-100000000)) |
| 593 |
os.chmod(path, 0o400) |
| 594 |
m = __import__(name) |
| 595 |
self.assertEqual(m.x, 'original') |
| 596 |
|
| 597 |
os.chmod(path, 0o600) |
| 598 |
with open(path, 'w', encoding='utf-8') as f: |
| 599 |
f.write("x = 'rewritten'\n") |
| 600 |
unload(name) |
| 601 |
importlib.invalidate_caches() |
| 602 |
m = __import__(name) |
| 603 |
self.assertEqual(m.x, 'rewritten') |
| 604 |
|
| 605 |
unlink(path) |
| 606 |
unload(name) |
| 607 |
importlib.invalidate_caches() |
| 608 |
bytecode_only = path + "c" |
| 609 |
os.rename(importlib.util.cache_from_source(path), bytecode_only) |
| 610 |
m = __import__(name) |
| 611 |
self.assertEqual(m.x, 'rewritten') |
| 612 |
|
| 613 |
|
| 614 |
class PycRewritingTests(unittest.TestCase): |
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
module_name = "unlikely_module_name" |
| 620 |
module_source = """ |
| 621 |
import sys |
| 622 |
code_filename = sys._getframe().f_code.co_filename |
| 623 |
module_filename = __file__ |
| 624 |
constant = 1 |
| 625 |
def func(): |
| 626 |
pass |
| 627 |
func_filename = func.__code__.co_filename |
| 628 |
""" |
| 629 |
dir_name = os.path.abspath(TESTFN) |
| 630 |
file_name = os.path.join(dir_name, module_name) + os.extsep + "py" |
| 631 |
compiled_name = importlib.util.cache_from_source(file_name) |
| 632 |
|
| 633 |
def setUp(self): |
| 634 |
self.sys_path = sys.path[:] |
| 635 |
self.orig_module = sys.modules.pop(self.module_name, None) |
| 636 |
os.mkdir(self.dir_name) |
| 637 |
with open(self.file_name, "w", encoding='utf-8') as f: |
| 638 |
f.write(self.module_source) |
| 639 |
sys.path.insert(0, self.dir_name) |
| 640 |
importlib.invalidate_caches() |
| 641 |
|
| 642 |
def tearDown(self): |
| 643 |
sys.path[:] = self.sys_path |
| 644 |
if self.orig_module is not None: |
| 645 |
sys.modules[self.module_name] = self.orig_module |
| 646 |
else: |
| 647 |
unload(self.module_name) |
| 648 |
unlink(self.file_name) |
| 649 |
unlink(self.compiled_name) |
| 650 |
rmtree(self.dir_name) |
| 651 |
|
| 652 |
def import_module(self): |
| 653 |
ns = globals() |
| 654 |
__import__(self.module_name, ns, ns) |
| 655 |
return sys.modules[self.module_name] |
| 656 |
|
| 657 |
def test_basics(self): |
| 658 |
mod = self.import_module() |
| 659 |
self.assertEqual(mod.module_filename, self.file_name) |
| 660 |
self.assertEqual(mod.code_filename, self.file_name) |
| 661 |
self.assertEqual(mod.func_filename, self.file_name) |
| 662 |
del sys.modules[self.module_name] |
| 663 |
mod = self.import_module() |
| 664 |
self.assertEqual(mod.module_filename, self.file_name) |
| 665 |
self.assertEqual(mod.code_filename, self.file_name) |
| 666 |
self.assertEqual(mod.func_filename, self.file_name) |
| 667 |
|
| 668 |
def test_incorrect_code_name(self): |
| 669 |
py_compile.compile(self.file_name, dfile="another_module.py") |
| 670 |
mod = self.import_module() |
| 671 |
self.assertEqual(mod.module_filename, self.file_name) |
| 672 |
self.assertEqual(mod.code_filename, self.file_name) |
| 673 |
self.assertEqual(mod.func_filename, self.file_name) |
| 674 |
|
| 675 |
def test_module_without_source(self): |
| 676 |
target = "another_module.py" |
| 677 |
py_compile.compile(self.file_name, dfile=target) |
| 678 |
os.remove(self.file_name) |
| 679 |
pyc_file = make_legacy_pyc(self.file_name) |
| 680 |
importlib.invalidate_caches() |
| 681 |
mod = self.import_module() |
| 682 |
self.assertEqual(mod.module_filename, pyc_file) |
| 683 |
self.assertEqual(mod.code_filename, target) |
| 684 |
self.assertEqual(mod.func_filename, target) |
| 685 |
|
| 686 |
def test_foreign_code(self): |
| 687 |
py_compile.compile(self.file_name) |
| 688 |
with open(self.compiled_name, "rb") as f: |
| 689 |
header = f.read(16) |
| 690 |
code = marshal.load(f) |
| 691 |
constants = list(code.co_consts) |
| 692 |
foreign_code = importlib.import_module.__code__ |
| 693 |
pos = constants.index(1) |
| 694 |
constants[pos] = foreign_code |
| 695 |
code = code.replace(co_consts=tuple(constants)) |
| 696 |
with open(self.compiled_name, "wb") as f: |
| 697 |
f.write(header) |
| 698 |
marshal.dump(code, f) |
| 699 |
mod = self.import_module() |
| 700 |
self.assertEqual(mod.constant.co_filename, foreign_code.co_filename) |
| 701 |
|
| 702 |
|
| 703 |
class PathsTests(unittest.TestCase): |
| 704 |
SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8', |
| 705 |
'test\u00b0\u00b3\u00b2') |
| 706 |
path = TESTFN |
| 707 |
|
| 708 |
def setUp(self): |
| 709 |
os.mkdir(self.path) |
| 710 |
self.syspath = sys.path[:] |
| 711 |
|
| 712 |
def tearDown(self): |
| 713 |
rmtree(self.path) |
| 714 |
sys.path[:] = self.syspath |
| 715 |
|
| 716 |
|
| 717 |
def test_trailing_slash(self): |
| 718 |
with open(os.path.join(self.path, 'test_trailing_slash.py'), |
| 719 |
'w', encoding='utf-8') as f: |
| 720 |
f.write("testdata = 'test_trailing_slash'") |
| 721 |
sys.path.append(self.path+'/') |
| 722 |
mod = __import__("test_trailing_slash") |
| 723 |
self.assertEqual(mod.testdata, 'test_trailing_slash') |
| 724 |
unload("test_trailing_slash") |
| 725 |
|
| 726 |
|
| 727 |
@unittest.skipUnless(sys.platform == 'win32', 'Windows-specific') |
| 728 |
def test_UNC_path(self): |
| 729 |
with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f: |
| 730 |
f.write("testdata = 'test_unc_path'") |
| 731 |
importlib.invalidate_caches() |
| 732 |
|
| 733 |
path = os.path.abspath(self.path) |
| 734 |
import socket |
| 735 |
hn = socket.gethostname() |
| 736 |
drive = path[0] |
| 737 |
unc = "\\\\%s\\%s$"%(hn, drive) |
| 738 |
unc += path[2:] |
| 739 |
try: |
| 740 |
os.listdir(unc) |
| 741 |
except OSError as e: |
| 742 |
if e.errno in (errno.EPERM, errno.EACCES, errno.ENOENT): |
| 743 |
|
| 744 |
self.skipTest("cannot access administrative share %r" % (unc,)) |
| 745 |
raise |
| 746 |
sys.path.insert(0, unc) |
| 747 |
try: |
| 748 |
mod = __import__("test_unc_path") |
| 749 |
except ImportError as e: |
| 750 |
self.fail("could not import 'test_unc_path' from %r: %r" |
| 751 |
% (unc, e)) |
| 752 |
self.assertEqual(mod.testdata, 'test_unc_path') |
| 753 |
self.assertTrue(mod.__file__.startswith(unc), mod.__file__) |
| 754 |
unload("test_unc_path") |
| 755 |
|
| 756 |
|
| 757 |
class RelativeImportTests(unittest.TestCase): |
| 758 |
|
| 759 |
def tearDown(self): |
| 760 |
unload("test.relimport") |
| 761 |
setUp = tearDown |
| 762 |
|
| 763 |
def test_relimport_star(self): |
| 764 |
|
| 765 |
from .. import relimport |
| 766 |
self.assertTrue(hasattr(relimport, "RelativeImportTests")) |
| 767 |
|
| 768 |
def test_issue3221(self): |
| 769 |
|
| 770 |
|
| 771 |
|
| 772 |
|
| 773 |
|
| 774 |
def check_relative(): |
| 775 |
exec("from . import relimport", ns) |
| 776 |
|
| 777 |
|
| 778 |
ns = dict(__package__='test', __name__='test.notarealmodule') |
| 779 |
check_relative() |
| 780 |
|
| 781 |
|
| 782 |
ns = dict(__package__='test', __name__='notarealpkg.notarealmodule') |
| 783 |
check_relative() |
| 784 |
|
| 785 |
|
| 786 |
ns = dict(__package__='foo', __name__='test.notarealmodule') |
| 787 |
self.assertRaises(ModuleNotFoundError, check_relative) |
| 788 |
|
| 789 |
|
| 790 |
ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule') |
| 791 |
self.assertRaises(ModuleNotFoundError, check_relative) |
| 792 |
|
| 793 |
|
| 794 |
ns = dict(__package__=object()) |
| 795 |
self.assertRaises(TypeError, check_relative) |
| 796 |
|
| 797 |
def test_parentless_import_shadowed_by_global(self): |
| 798 |
|
| 799 |
script_helper.assert_python_failure('-W', 'ignore', '-c', |
| 800 |
"foo = 1; from . import foo") |
| 801 |
|
| 802 |
def test_absolute_import_without_future(self): |
| 803 |
|
| 804 |
|
| 805 |
|
| 806 |
with self.assertRaises(ImportError): |
| 807 |
from .os import sep |
| 808 |
self.fail("explicit relative import triggered an " |
| 809 |
"implicit absolute import") |
| 810 |
|
| 811 |
def test_import_from_non_package(self): |
| 812 |
path = os.path.join(os.path.dirname(__file__), 'data', 'package2') |
| 813 |
with uncache('submodule1', 'submodule2'), DirsOnSysPath(path): |
| 814 |
with self.assertRaises(ImportError): |
| 815 |
import submodule1 |
| 816 |
self.assertNotIn('submodule1', sys.modules) |
| 817 |
self.assertNotIn('submodule2', sys.modules) |
| 818 |
|
| 819 |
def test_import_from_unloaded_package(self): |
| 820 |
with uncache('package2', 'package2.submodule1', 'package2.submodule2'), \ |
| 821 |
DirsOnSysPath(os.path.join(os.path.dirname(__file__), 'data')): |
| 822 |
import package2.submodule1 |
| 823 |
package2.submodule1.submodule2 |
| 824 |
|
| 825 |
|
| 826 |
class OverridingImportBuiltinTests(unittest.TestCase): |
| 827 |
def test_override_builtin(self): |
| 828 |
|
| 829 |
import os |
| 830 |
|
| 831 |
def foo(): |
| 832 |
import os |
| 833 |
return os |
| 834 |
self.assertEqual(foo(), os) |
| 835 |
|
| 836 |
with swap_attr(builtins, "__import__", lambda *x: 5): |
| 837 |
self.assertEqual(foo(), 5) |
| 838 |
|
| 839 |
|
| 840 |
|
| 841 |
|
| 842 |
with swap_item(globals(), "__import__", lambda *x: 5): |
| 843 |
self.assertEqual(foo(), os) |
| 844 |
|
| 845 |
|
| 846 |
class PycacheTests(unittest.TestCase): |
| 847 |
|
| 848 |
|
| 849 |
def _clean(self): |
| 850 |
forget(TESTFN) |
| 851 |
rmtree('__pycache__') |
| 852 |
unlink(self.source) |
| 853 |
|
| 854 |
def setUp(self): |
| 855 |
self.source = TESTFN + '.py' |
| 856 |
self._clean() |
| 857 |
with open(self.source, 'w', encoding='utf-8') as fp: |
| 858 |
print('# This is a test file written by test_import.py', file=fp) |
| 859 |
sys.path.insert(0, os.curdir) |
| 860 |
importlib.invalidate_caches() |
| 861 |
|
| 862 |
def tearDown(self): |
| 863 |
assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]' |
| 864 |
del sys.path[0] |
| 865 |
self._clean() |
| 866 |
|
| 867 |
@skip_if_dont_write_bytecode |
| 868 |
def test_import_pyc_path(self): |
| 869 |
self.assertFalse(os.path.exists('__pycache__')) |
| 870 |
__import__(TESTFN) |
| 871 |
self.assertTrue(os.path.exists('__pycache__')) |
| 872 |
pyc_path = importlib.util.cache_from_source(self.source) |
| 873 |
self.assertTrue(os.path.exists(pyc_path), |
| 874 |
'bytecode file {!r} for {!r} does not ' |
| 875 |
'exist'.format(pyc_path, TESTFN)) |
| 876 |
|
| 877 |
@unittest.skipUnless(os.name == 'posix', |
| 878 |
"test meaningful only on posix systems") |
| 879 |
@skip_if_dont_write_bytecode |
| 880 |
@os_helper.skip_unless_working_chmod |
| 881 |
@os_helper.skip_if_dac_override |
| 882 |
@unittest.skipIf(is_emscripten, "umask is a stub") |
| 883 |
def test_unwritable_directory(self): |
| 884 |
|
| 885 |
|
| 886 |
with temp_umask(0o222): |
| 887 |
__import__(TESTFN) |
| 888 |
self.assertTrue(os.path.exists('__pycache__')) |
| 889 |
pyc_path = importlib.util.cache_from_source(self.source) |
| 890 |
self.assertFalse(os.path.exists(pyc_path), |
| 891 |
'bytecode file {!r} for {!r} ' |
| 892 |
'exists'.format(pyc_path, TESTFN)) |
| 893 |
|
| 894 |
@skip_if_dont_write_bytecode |
| 895 |
def test_missing_source(self): |
| 896 |
|
| 897 |
|
| 898 |
__import__(TESTFN) |
| 899 |
pyc_file = importlib.util.cache_from_source(self.source) |
| 900 |
self.assertTrue(os.path.exists(pyc_file)) |
| 901 |
os.remove(self.source) |
| 902 |
forget(TESTFN) |
| 903 |
importlib.invalidate_caches() |
| 904 |
self.assertRaises(ImportError, __import__, TESTFN) |
| 905 |
|
| 906 |
@skip_if_dont_write_bytecode |
| 907 |
def test_missing_source_legacy(self): |
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
__import__(TESTFN) |
| 913 |
|
| 914 |
pyc_file = make_legacy_pyc(self.source) |
| 915 |
os.remove(self.source) |
| 916 |
unload(TESTFN) |
| 917 |
importlib.invalidate_caches() |
| 918 |
m = __import__(TESTFN) |
| 919 |
try: |
| 920 |
self.assertEqual(m.__file__, |
| 921 |
os.path.join(os.getcwd(), os.path.relpath(pyc_file))) |
| 922 |
finally: |
| 923 |
os.remove(pyc_file) |
| 924 |
|
| 925 |
def test___cached__(self): |
| 926 |
|
| 927 |
m = __import__(TESTFN) |
| 928 |
pyc_file = importlib.util.cache_from_source(TESTFN + '.py') |
| 929 |
self.assertEqual(m.__cached__, os.path.join(os.getcwd(), pyc_file)) |
| 930 |
|
| 931 |
@skip_if_dont_write_bytecode |
| 932 |
def test___cached___legacy_pyc(self): |
| 933 |
|
| 934 |
|
| 935 |
|
| 936 |
|
| 937 |
__import__(TESTFN) |
| 938 |
|
| 939 |
pyc_file = make_legacy_pyc(self.source) |
| 940 |
os.remove(self.source) |
| 941 |
unload(TESTFN) |
| 942 |
importlib.invalidate_caches() |
| 943 |
m = __import__(TESTFN) |
| 944 |
self.assertEqual(m.__cached__, |
| 945 |
os.path.join(os.getcwd(), os.path.relpath(pyc_file))) |
| 946 |
|
| 947 |
@skip_if_dont_write_bytecode |
| 948 |
def test_package___cached__(self): |
| 949 |
|
| 950 |
def cleanup(): |
| 951 |
rmtree('pep3147') |
| 952 |
unload('pep3147.foo') |
| 953 |
unload('pep3147') |
| 954 |
os.mkdir('pep3147') |
| 955 |
self.addCleanup(cleanup) |
| 956 |
|
| 957 |
with open(os.path.join('pep3147', '__init__.py'), 'wb'): |
| 958 |
pass |
| 959 |
with open(os.path.join('pep3147', 'foo.py'), 'wb'): |
| 960 |
pass |
| 961 |
importlib.invalidate_caches() |
| 962 |
m = __import__('pep3147.foo') |
| 963 |
init_pyc = importlib.util.cache_from_source( |
| 964 |
os.path.join('pep3147', '__init__.py')) |
| 965 |
self.assertEqual(m.__cached__, os.path.join(os.getcwd(), init_pyc)) |
| 966 |
foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py')) |
| 967 |
self.assertEqual(sys.modules['pep3147.foo'].__cached__, |
| 968 |
os.path.join(os.getcwd(), foo_pyc)) |
| 969 |
|
| 970 |
def test_package___cached___from_pyc(self): |
| 971 |
|
| 972 |
|
| 973 |
def cleanup(): |
| 974 |
rmtree('pep3147') |
| 975 |
unload('pep3147.foo') |
| 976 |
unload('pep3147') |
| 977 |
os.mkdir('pep3147') |
| 978 |
self.addCleanup(cleanup) |
| 979 |
|
| 980 |
with open(os.path.join('pep3147', '__init__.py'), 'wb'): |
| 981 |
pass |
| 982 |
with open(os.path.join('pep3147', 'foo.py'), 'wb'): |
| 983 |
pass |
| 984 |
importlib.invalidate_caches() |
| 985 |
m = __import__('pep3147.foo') |
| 986 |
unload('pep3147.foo') |
| 987 |
unload('pep3147') |
| 988 |
importlib.invalidate_caches() |
| 989 |
m = __import__('pep3147.foo') |
| 990 |
init_pyc = importlib.util.cache_from_source( |
| 991 |
os.path.join('pep3147', '__init__.py')) |
| 992 |
self.assertEqual(m.__cached__, os.path.join(os.getcwd(), init_pyc)) |
| 993 |
foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py')) |
| 994 |
self.assertEqual(sys.modules['pep3147.foo'].__cached__, |
| 995 |
os.path.join(os.getcwd(), foo_pyc)) |
| 996 |
|
| 997 |
def test_recompute_pyc_same_second(self): |
| 998 |
|
| 999 |
|
| 1000 |
__import__(TESTFN) |
| 1001 |
unload(TESTFN) |
| 1002 |
with open(self.source, 'a', encoding='utf-8') as fp: |
| 1003 |
print("x = 5", file=fp) |
| 1004 |
m = __import__(TESTFN) |
| 1005 |
self.assertEqual(m.x, 5) |
| 1006 |
|
| 1007 |
|
| 1008 |
class TestSymbolicallyLinkedPackage(unittest.TestCase): |
| 1009 |
package_name = 'sample' |
| 1010 |
tagged = package_name + '-tagged' |
| 1011 |
|
| 1012 |
def setUp(self): |
| 1013 |
os_helper.rmtree(self.tagged) |
| 1014 |
os_helper.rmtree(self.package_name) |
| 1015 |
self.orig_sys_path = sys.path[:] |
| 1016 |
|
| 1017 |
|
| 1018 |
|
| 1019 |
os.mkdir(self.tagged) |
| 1020 |
self.addCleanup(os_helper.rmtree, self.tagged) |
| 1021 |
init_file = os.path.join(self.tagged, '__init__.py') |
| 1022 |
os_helper.create_empty_file(init_file) |
| 1023 |
assert os.path.exists(init_file) |
| 1024 |
|
| 1025 |
|
| 1026 |
|
| 1027 |
os.symlink(self.tagged, self.package_name, target_is_directory=True) |
| 1028 |
self.addCleanup(os_helper.unlink, self.package_name) |
| 1029 |
importlib.invalidate_caches() |
| 1030 |
|
| 1031 |
self.assertEqual(os.path.isdir(self.package_name), True) |
| 1032 |
|
| 1033 |
assert os.path.isfile(os.path.join(self.package_name, '__init__.py')) |
| 1034 |
|
| 1035 |
def tearDown(self): |
| 1036 |
sys.path[:] = self.orig_sys_path |
| 1037 |
|
| 1038 |
|
| 1039 |
@unittest.skipUnless( |
| 1040 |
not hasattr(sys, 'getwindowsversion') |
| 1041 |
or sys.getwindowsversion() >= (6, 0), |
| 1042 |
"Windows Vista or later required") |
| 1043 |
@os_helper.skip_unless_symlink |
| 1044 |
def test_symlinked_dir_importable(self): |
| 1045 |
|
| 1046 |
sys.path[:] = ['.'] |
| 1047 |
assert os.path.exists(self.package_name) |
| 1048 |
assert os.path.exists(os.path.join(self.package_name, '__init__.py')) |
| 1049 |
|
| 1050 |
|
| 1051 |
importlib.import_module(self.package_name) |
| 1052 |
|
| 1053 |
|
| 1054 |
@cpython_only |
| 1055 |
class ImportlibBootstrapTests(unittest.TestCase): |
| 1056 |
|
| 1057 |
|
| 1058 |
def test_frozen_importlib(self): |
| 1059 |
mod = sys.modules['_frozen_importlib'] |
| 1060 |
self.assertTrue(mod) |
| 1061 |
|
| 1062 |
def test_frozen_importlib_is_bootstrap(self): |
| 1063 |
from importlib import _bootstrap |
| 1064 |
mod = sys.modules['_frozen_importlib'] |
| 1065 |
self.assertIs(mod, _bootstrap) |
| 1066 |
self.assertEqual(mod.__name__, 'importlib._bootstrap') |
| 1067 |
self.assertEqual(mod.__package__, 'importlib') |
| 1068 |
self.assertTrue(mod.__file__.endswith('_bootstrap.py'), mod.__file__) |
| 1069 |
|
| 1070 |
def test_frozen_importlib_external_is_bootstrap_external(self): |
| 1071 |
from importlib import _bootstrap_external |
| 1072 |
mod = sys.modules['_frozen_importlib_external'] |
| 1073 |
self.assertIs(mod, _bootstrap_external) |
| 1074 |
self.assertEqual(mod.__name__, 'importlib._bootstrap_external') |
| 1075 |
self.assertEqual(mod.__package__, 'importlib') |
| 1076 |
self.assertTrue(mod.__file__.endswith('_bootstrap_external.py'), mod.__file__) |
| 1077 |
|
| 1078 |
def test_there_can_be_only_one(self): |
| 1079 |
|
| 1080 |
|
| 1081 |
|
| 1082 |
from importlib import machinery |
| 1083 |
mod = sys.modules['_frozen_importlib'] |
| 1084 |
self.assertIs(machinery.ModuleSpec, mod.ModuleSpec) |
| 1085 |
|
| 1086 |
|
| 1087 |
@cpython_only |
| 1088 |
class GetSourcefileTests(unittest.TestCase): |
| 1089 |
|
| 1090 |
"""Test importlib._bootstrap_external._get_sourcefile() as used by the C API. |
| 1091 |
|
| 1092 |
Because of the peculiarities of the need of this function, the tests are |
| 1093 |
knowingly whitebox tests. |
| 1094 |
|
| 1095 |
""" |
| 1096 |
|
| 1097 |
def test_get_sourcefile(self): |
| 1098 |
|
| 1099 |
|
| 1100 |
with mock.patch('importlib._bootstrap_external._path_isfile') as _path_isfile: |
| 1101 |
_path_isfile.return_value = True |
| 1102 |
path = TESTFN + '.pyc' |
| 1103 |
expect = TESTFN + '.py' |
| 1104 |
self.assertEqual(_get_sourcefile(path), expect) |
| 1105 |
|
| 1106 |
def test_get_sourcefile_no_source(self): |
| 1107 |
|
| 1108 |
|
| 1109 |
with mock.patch('importlib._bootstrap_external._path_isfile') as _path_isfile: |
| 1110 |
_path_isfile.return_value = False |
| 1111 |
path = TESTFN + '.pyc' |
| 1112 |
self.assertEqual(_get_sourcefile(path), path) |
| 1113 |
|
| 1114 |
def test_get_sourcefile_bad_ext(self): |
| 1115 |
|
| 1116 |
|
| 1117 |
path = TESTFN + '.bad_ext' |
| 1118 |
self.assertEqual(_get_sourcefile(path), path) |
| 1119 |
|
| 1120 |
|
| 1121 |
class ImportTracebackTests(unittest.TestCase): |
| 1122 |
|
| 1123 |
def setUp(self): |
| 1124 |
os.mkdir(TESTFN) |
| 1125 |
self.old_path = sys.path[:] |
| 1126 |
sys.path.insert(0, TESTFN) |
| 1127 |
|
| 1128 |
def tearDown(self): |
| 1129 |
sys.path[:] = self.old_path |
| 1130 |
rmtree(TESTFN) |
| 1131 |
|
| 1132 |
def create_module(self, mod, contents, ext=".py"): |
| 1133 |
fname = os.path.join(TESTFN, mod + ext) |
| 1134 |
with open(fname, "w", encoding='utf-8') as f: |
| 1135 |
f.write(contents) |
| 1136 |
self.addCleanup(unload, mod) |
| 1137 |
importlib.invalidate_caches() |
| 1138 |
return fname |
| 1139 |
|
| 1140 |
def assert_traceback(self, tb, files): |
| 1141 |
deduped_files = [] |
| 1142 |
while tb: |
| 1143 |
code = tb.tb_frame.f_code |
| 1144 |
fn = code.co_filename |
| 1145 |
if not deduped_files or fn != deduped_files[-1]: |
| 1146 |
deduped_files.append(fn) |
| 1147 |
tb = tb.tb_next |
| 1148 |
self.assertEqual(len(deduped_files), len(files), deduped_files) |
| 1149 |
for fn, pat in zip(deduped_files, files): |
| 1150 |
self.assertIn(pat, fn) |
| 1151 |
|
| 1152 |
def test_nonexistent_module(self): |
| 1153 |
try: |
| 1154 |
|
| 1155 |
import nonexistent_xyzzy |
| 1156 |
except ImportError as e: |
| 1157 |
tb = e.__traceback__ |
| 1158 |
else: |
| 1159 |
self.fail("ImportError should have been raised") |
| 1160 |
self.assert_traceback(tb, [__file__]) |
| 1161 |
|
| 1162 |
def test_nonexistent_module_nested(self): |
| 1163 |
self.create_module("foo", "import nonexistent_xyzzy") |
| 1164 |
try: |
| 1165 |
import foo |
| 1166 |
except ImportError as e: |
| 1167 |
tb = e.__traceback__ |
| 1168 |
else: |
| 1169 |
self.fail("ImportError should have been raised") |
| 1170 |
self.assert_traceback(tb, [__file__, 'foo.py']) |
| 1171 |
|
| 1172 |
def test_exec_failure(self): |
| 1173 |
self.create_module("foo", "1/0") |
| 1174 |
try: |
| 1175 |
import foo |
| 1176 |
except ZeroDivisionError as e: |
| 1177 |
tb = e.__traceback__ |
| 1178 |
else: |
| 1179 |
self.fail("ZeroDivisionError should have been raised") |
| 1180 |
self.assert_traceback(tb, [__file__, 'foo.py']) |
| 1181 |
|
| 1182 |
def test_exec_failure_nested(self): |
| 1183 |
self.create_module("foo", "import bar") |
| 1184 |
self.create_module("bar", "1/0") |
| 1185 |
try: |
| 1186 |
import foo |
| 1187 |
except ZeroDivisionError as e: |
| 1188 |
tb = e.__traceback__ |
| 1189 |
else: |
| 1190 |
self.fail("ZeroDivisionError should have been raised") |
| 1191 |
self.assert_traceback(tb, [__file__, 'foo.py', 'bar.py']) |
| 1192 |
|
| 1193 |
|
| 1194 |
def test_syntax_error(self): |
| 1195 |
self.create_module("foo", "invalid syntax is invalid") |
| 1196 |
try: |
| 1197 |
import foo |
| 1198 |
except SyntaxError as e: |
| 1199 |
tb = e.__traceback__ |
| 1200 |
else: |
| 1201 |
self.fail("SyntaxError should have been raised") |
| 1202 |
self.assert_traceback(tb, [__file__]) |
| 1203 |
|
| 1204 |
def _setup_broken_package(self, parent, child): |
| 1205 |
pkg_name = "_parent_foo" |
| 1206 |
self.addCleanup(unload, pkg_name) |
| 1207 |
pkg_path = os.path.join(TESTFN, pkg_name) |
| 1208 |
os.mkdir(pkg_path) |
| 1209 |
|
| 1210 |
init_path = os.path.join(pkg_path, '__init__.py') |
| 1211 |
with open(init_path, 'w', encoding='utf-8') as f: |
| 1212 |
f.write(parent) |
| 1213 |
bar_path = os.path.join(pkg_path, 'bar.py') |
| 1214 |
with open(bar_path, 'w', encoding='utf-8') as f: |
| 1215 |
f.write(child) |
| 1216 |
importlib.invalidate_caches() |
| 1217 |
return init_path, bar_path |
| 1218 |
|
| 1219 |
def test_broken_submodule(self): |
| 1220 |
init_path, bar_path = self._setup_broken_package("", "1/0") |
| 1221 |
try: |
| 1222 |
import _parent_foo.bar |
| 1223 |
except ZeroDivisionError as e: |
| 1224 |
tb = e.__traceback__ |
| 1225 |
else: |
| 1226 |
self.fail("ZeroDivisionError should have been raised") |
| 1227 |
self.assert_traceback(tb, [__file__, bar_path]) |
| 1228 |
|
| 1229 |
def test_broken_from(self): |
| 1230 |
init_path, bar_path = self._setup_broken_package("", "1/0") |
| 1231 |
try: |
| 1232 |
from _parent_foo import bar |
| 1233 |
except ZeroDivisionError as e: |
| 1234 |
tb = e.__traceback__ |
| 1235 |
else: |
| 1236 |
self.fail("ImportError should have been raised") |
| 1237 |
self.assert_traceback(tb, [__file__, bar_path]) |
| 1238 |
|
| 1239 |
def test_broken_parent(self): |
| 1240 |
init_path, bar_path = self._setup_broken_package("1/0", "") |
| 1241 |
try: |
| 1242 |
import _parent_foo.bar |
| 1243 |
except ZeroDivisionError as e: |
| 1244 |
tb = e.__traceback__ |
| 1245 |
else: |
| 1246 |
self.fail("ZeroDivisionError should have been raised") |
| 1247 |
self.assert_traceback(tb, [__file__, init_path]) |
| 1248 |
|
| 1249 |
def test_broken_parent_from(self): |
| 1250 |
init_path, bar_path = self._setup_broken_package("1/0", "") |
| 1251 |
try: |
| 1252 |
from _parent_foo import bar |
| 1253 |
except ZeroDivisionError as e: |
| 1254 |
tb = e.__traceback__ |
| 1255 |
else: |
| 1256 |
self.fail("ZeroDivisionError should have been raised") |
| 1257 |
self.assert_traceback(tb, [__file__, init_path]) |
| 1258 |
|
| 1259 |
@cpython_only |
| 1260 |
def test_import_bug(self): |
| 1261 |
|
| 1262 |
|
| 1263 |
self.create_module("foo", "") |
| 1264 |
importlib = sys.modules['_frozen_importlib_external'] |
| 1265 |
if 'load_module' in vars(importlib.SourceLoader): |
| 1266 |
old_exec_module = importlib.SourceLoader.exec_module |
| 1267 |
else: |
| 1268 |
old_exec_module = None |
| 1269 |
try: |
| 1270 |
def exec_module(*args): |
| 1271 |
1/0 |
| 1272 |
importlib.SourceLoader.exec_module = exec_module |
| 1273 |
try: |
| 1274 |
import foo |
| 1275 |
except ZeroDivisionError as e: |
| 1276 |
tb = e.__traceback__ |
| 1277 |
else: |
| 1278 |
self.fail("ZeroDivisionError should have been raised") |
| 1279 |
self.assert_traceback(tb, [__file__, '<frozen importlib', __file__]) |
| 1280 |
finally: |
| 1281 |
if old_exec_module is None: |
| 1282 |
del importlib.SourceLoader.exec_module |
| 1283 |
else: |
| 1284 |
importlib.SourceLoader.exec_module = old_exec_module |
| 1285 |
|
| 1286 |
@unittest.skipUnless(TESTFN_UNENCODABLE, 'need TESTFN_UNENCODABLE') |
| 1287 |
def test_unencodable_filename(self): |
| 1288 |
|
| 1289 |
|
| 1290 |
pyname = script_helper.make_script('', TESTFN_UNENCODABLE, 'pass') |
| 1291 |
self.addCleanup(unlink, pyname) |
| 1292 |
name = pyname[:-3] |
| 1293 |
script_helper.assert_python_ok("-c", "mod = __import__(%a)" % name, |
| 1294 |
__isolated=False) |
| 1295 |
|
| 1296 |
|
| 1297 |
class CircularImportTests(unittest.TestCase): |
| 1298 |
|
| 1299 |
"""See the docstrings of the modules being imported for the purpose of the |
| 1300 |
test.""" |
| 1301 |
|
| 1302 |
def tearDown(self): |
| 1303 |
"""Make sure no modules pre-exist in sys.modules which are being used to |
| 1304 |
test.""" |
| 1305 |
for key in list(sys.modules.keys()): |
| 1306 |
if key.startswith('test.test_import.data.circular_imports'): |
| 1307 |
del sys.modules[key] |
| 1308 |
|
| 1309 |
def test_direct(self): |
| 1310 |
try: |
| 1311 |
import test.test_import.data.circular_imports.basic |
| 1312 |
except ImportError: |
| 1313 |
self.fail('circular import through relative imports failed') |
| 1314 |
|
| 1315 |
def test_indirect(self): |
| 1316 |
try: |
| 1317 |
import test.test_import.data.circular_imports.indirect |
| 1318 |
except ImportError: |
| 1319 |
self.fail('relative import in module contributing to circular ' |
| 1320 |
'import failed') |
| 1321 |
|
| 1322 |
def test_subpackage(self): |
| 1323 |
try: |
| 1324 |
import test.test_import.data.circular_imports.subpackage |
| 1325 |
except ImportError: |
| 1326 |
self.fail('circular import involving a subpackage failed') |
| 1327 |
|
| 1328 |
def test_rebinding(self): |
| 1329 |
try: |
| 1330 |
import test.test_import.data.circular_imports.rebinding as rebinding |
| 1331 |
except ImportError: |
| 1332 |
self.fail('circular import with rebinding of module attribute failed') |
| 1333 |
from test.test_import.data.circular_imports.subpkg import util |
| 1334 |
self.assertIs(util.util, rebinding.util) |
| 1335 |
|
| 1336 |
def test_binding(self): |
| 1337 |
try: |
| 1338 |
import test.test_import.data.circular_imports.binding |
| 1339 |
except ImportError: |
| 1340 |
self.fail('circular import with binding a submodule to a name failed') |
| 1341 |
|
| 1342 |
def test_crossreference1(self): |
| 1343 |
import test.test_import.data.circular_imports.use |
| 1344 |
import test.test_import.data.circular_imports.source |
| 1345 |
|
| 1346 |
def test_crossreference2(self): |
| 1347 |
with self.assertRaises(AttributeError) as cm: |
| 1348 |
import test.test_import.data.circular_imports.source |
| 1349 |
errmsg = str(cm.exception) |
| 1350 |
self.assertIn('test.test_import.data.circular_imports.source', errmsg) |
| 1351 |
self.assertIn('spam', errmsg) |
| 1352 |
self.assertIn('partially initialized module', errmsg) |
| 1353 |
self.assertIn('circular import', errmsg) |
| 1354 |
|
| 1355 |
def test_circular_from_import(self): |
| 1356 |
with self.assertRaises(ImportError) as cm: |
| 1357 |
import test.test_import.data.circular_imports.from_cycle1 |
| 1358 |
self.assertIn( |
| 1359 |
"cannot import name 'b' from partially initialized module " |
| 1360 |
"'test.test_import.data.circular_imports.from_cycle1' " |
| 1361 |
"(most likely due to a circular import)", |
| 1362 |
str(cm.exception), |
| 1363 |
) |
| 1364 |
|
| 1365 |
def test_absolute_circular_submodule(self): |
| 1366 |
with self.assertRaises(AttributeError) as cm: |
| 1367 |
import test.test_import.data.circular_imports.subpkg2.parent |
| 1368 |
self.assertIn( |
| 1369 |
"cannot access submodule 'parent' of module " |
| 1370 |
"'test.test_import.data.circular_imports.subpkg2' " |
| 1371 |
"(most likely due to a circular import)", |
| 1372 |
str(cm.exception), |
| 1373 |
) |
| 1374 |
|
| 1375 |
def test_unwritable_module(self): |
| 1376 |
self.addCleanup(unload, "test.test_import.data.unwritable") |
| 1377 |
self.addCleanup(unload, "test.test_import.data.unwritable.x") |
| 1378 |
|
| 1379 |
import test.test_import.data.unwritable as unwritable |
| 1380 |
with self.assertWarns(ImportWarning): |
| 1381 |
from test.test_import.data.unwritable import x |
| 1382 |
|
| 1383 |
self.assertNotEqual(type(unwritable), ModuleType) |
| 1384 |
self.assertEqual(type(x), ModuleType) |
| 1385 |
with self.assertRaises(AttributeError): |
| 1386 |
unwritable.x = 42 |
| 1387 |
|
| 1388 |
|
| 1389 |
if __name__ == '__main__': |
| 1390 |
|
| 1391 |
unittest.main() |