From c63e2158adffb5eda3dba9ac2191682ded2b71c8 Mon Sep 17 00:00:00 2001 From: Amandeep vishwkarma Date: Sat, 16 May 2026 10:28:55 +0530 Subject: [PATCH] tests: ensure fastapi.responses isolation during monkeypatch --- tests/test_responses_optional_imports.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/test_responses_optional_imports.py b/tests/test_responses_optional_imports.py index f8c7509263..28fa995629 100644 --- a/tests/test_responses_optional_imports.py +++ b/tests/test_responses_optional_imports.py @@ -19,9 +19,13 @@ def test_optional_imports_broken_installation(monkeypatch: pytest.MonkeyPatch) - monkeypatch.setattr(importlib, "import_module", fake_import_module) - # Force a reload to ensure the module initialization runs with our monkeypatch - if "fastapi.responses" in sys.modules: - del sys.modules["fastapi.responses"] + import fastapi.responses - # This should not raise an ImportError - import fastapi.responses # noqa: F401 + # Force a reload to ensure the module initialization runs with our monkeypatch + try: + importlib.reload(fastapi.responses) + finally: + # Revert the monkeypatch manually early so we can restore the module + monkeypatch.undo() + # Restore test isolation by reloading the module cleanly + importlib.reload(fastapi.responses)