Skip to content

Commit 475342e

Browse files
Update qualtran/testing.py
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent 8d72aae commit 475342e

1 file changed

Lines changed: 19 additions & 15 deletions

File tree

qualtran/testing.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -298,21 +298,25 @@ def execute_notebook(name: str):
298298

299299
# Execute in a temporary directory to avoid writing any files into the source tree.
300300
# This prevents accidental module shadowing.
301-
with tempfile.TemporaryDirectory() as tmpdir:
302-
exec_globals: dict = {"__name__": "__main__", "__file__": str(notebook_path)}
303-
old_cwd = os.getcwd()
304-
old_path = sys.path[:]
305-
os.chdir(tmpdir)
306-
# Add the notebook's directory to sys.path so imports from the same package work
307-
# (matching the Jupyter kernel behavior of setting cwd to the notebook directory).
308-
sys.path.insert(0, str(notebook_path.parent))
309-
try:
310-
exec(
311-
compile(script, str(notebook_path), "exec"), exec_globals
312-
) # pylint: disable=exec-used
313-
finally:
314-
os.chdir(old_cwd)
315-
sys.path[:] = old_path
301+
old_cwd = os.getcwd()
302+
old_path = sys.path[:]
303+
old_modules = sys.modules.copy()
304+
os.chdir(notebook_path.parent)
305+
sys.path.insert(0, str(notebook_path.parent))
306+
exec_globals: dict = {
307+
"__name__": "__main__",
308+
"__file__": str(notebook_path),
309+
"get_ipython": lambda: None, # Mock to avoid NameError on magics
310+
}
311+
try:
312+
exec(compile(script, str(notebook_path), "exec"), exec_globals) # pylint: disable=exec-used
313+
finally:
314+
os.chdir(old_cwd)
315+
sys.path[:] = old_path
316+
# Clean up sys.modules to prevent cross-test pollution
317+
for m in list(sys.modules):
318+
if m not in old_modules:
319+
del sys.modules[m]
316320

317321

318322
class BloqCheckResult(Enum):

0 commit comments

Comments
 (0)