Skip to content
Merged
31 changes: 30 additions & 1 deletion Lib/test/test_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import os
import py_compile
import random
import re
import shutil
import stat
import subprocess
Expand Down Expand Up @@ -812,9 +813,37 @@ def test_frozen_module_from_import_error(self):
from os import this_will_never_exist
self.assertRegex(
str(cm.exception),
r"cannot import name 'this_will_never_exist' from 'os' \(.*Lib[\\/]os\.py\)"
f"cannot import name 'this_will_never_exist' from 'os' \\({re.escape(os.__file__)}\\)"
)


scripts = [
"""
import os
os.__spec__.has_location = False
os.__file__ = 123
from os import this_will_never_exist
""",
"""
import os
os.__spec__.has_location = False
del os.__file__
from os import this_will_never_exist
"""
]
for script in scripts:
with self.subTest(script=script), os_helper.temp_dir() as tmp:
with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
f.write(script)

expected_error = (
b"cannot import name 'this_will_never_exist' "
b"from 'os' \\(unknown location\\)"
)
popen = script_helper.spawn_python(os.path.join(tmp, "main.py"), cwd=tmp)
stdout, stderr = popen.communicate()
self.assertRegex(stdout, expected_error)

def test_script_shadowing_stdlib(self):
script_errors = [
(
Expand Down
Loading