From 285b02cae872734d4c83d7763672955a1c412cb5 Mon Sep 17 00:00:00 2001 From: Jake Stevens-Haas Date: Wed, 6 Jul 2022 17:48:26 -0700 Subject: [PATCH] BUG: Tear down common import names in notebook tests --- test/test_notebooks.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/test/test_notebooks.py b/test/test_notebooks.py index 5e217b70f..0f573658b 100644 --- a/test/test_notebooks.py +++ b/test/test_notebooks.py @@ -43,8 +43,28 @@ def _cwd(directory): os.chdir(cwd) +@pytest.fixture +def purge_notebook_modules(): + """Remove notebook modules from sys.modules after test. + + Because these modules share common names in each notebook and + module names have a system-wide scope, import machinery will not + import new modules for successive notebooks unless old modules of + same name are removed from sys.modules. + + This might be better served by fixing imports in notebooks using + importlib. + """ + SENTINEL = object() + sys.modules.pop("utils", SENTINEL) + sys.modules.pop("mock_data", SENTINEL) + yield + sys.modules.pop("utils", SENTINEL) + sys.modules.pop("mock_data", SENTINEL) + + @pytest.mark.parametrize("directory", notebook_scripts) -def test_notebook_script(directory: Path): +def test_notebook_script(directory: Path, purge_notebook_modules): # Run in native directory with modified sys.path for imports to work with _cwd(notebook_dir / directory): runpy.run_path(str(notebook_dir / directory / "example.py"), run_name="testing")