Skip to content

Commit 5fe139c

Browse files
authored
gh-144727: Add test for circular lazy import crash (#144727) (#144838)
Add a regression test ensuring that circular lazy imports raise a proper error (ImportCycleError) instead of crashing with a segfault. The crash was fixed in gh-144733 but no test was added at the time.
1 parent 23c488d commit 5fe139c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Lib/test/test_import/test_lazy_imports.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
import threading
99
import types
1010
import unittest
11+
import tempfile
12+
import os
1113

1214
try:
1315
import _testcapi
@@ -598,6 +600,39 @@ def test_error_during_module_execution_propagates(self):
598600
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
599601
self.assertIn("OK", result.stdout)
600602

603+
def test_circular_lazy_import_does_not_crash_for_gh_144727(self):
604+
with tempfile.TemporaryDirectory() as tmpdir:
605+
a_path = os.path.join(tmpdir, "a.py")
606+
b_path = os.path.join(tmpdir, "b.py")
607+
608+
with open(a_path, "w") as f:
609+
f.write(textwrap.dedent("""\
610+
lazy import b
611+
612+
def something():
613+
b.hello()
614+
615+
something()
616+
"""))
617+
618+
with open(b_path, "w") as f:
619+
f.write(textwrap.dedent("""\
620+
lazy import a
621+
622+
def hello():
623+
print(a)
624+
"""))
625+
626+
result = subprocess.run(
627+
[sys.executable, a_path],
628+
capture_output=True,
629+
text=True,
630+
cwd=tmpdir,
631+
)
632+
# Should get a proper Python error, not a crash
633+
self.assertEqual(result.returncode, 1)
634+
self.assertIn("Error", result.stderr)
635+
601636

602637
class GlobalsAndDictTests(unittest.TestCase):
603638
"""Tests for globals() and __dict__ behavior with lazy imports.

0 commit comments

Comments
 (0)