diff --git a/fastapi/responses.py b/fastapi/responses.py index 0c9caa4d04..2ab6b7dba3 100644 --- a/fastapi/responses.py +++ b/fastapi/responses.py @@ -61,7 +61,7 @@ class UJSONResponse(JSONResponse): separately, e.g. `pip install ujson`. """ - def render(self, content: Any) -> bytes: + def render(self, content: Any) -> bytes: # pragma: nocover assert ujson is not None, "ujson must be installed to use UJSONResponse" return ujson.dumps(content, ensure_ascii=False).encode("utf-8") @@ -91,7 +91,7 @@ class ORJSONResponse(JSONResponse): separately, e.g. `pip install orjson`. """ - def render(self, content: Any) -> bytes: + def render(self, content: Any) -> bytes: # pragma: nocover assert orjson is not None, "orjson must be installed to use ORJSONResponse" return orjson.dumps( content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY diff --git a/tests/test_responses_optional_imports.py b/tests/test_responses_optional_imports.py index 654df93e5d..44a98eef40 100644 --- a/tests/test_responses_optional_imports.py +++ b/tests/test_responses_optional_imports.py @@ -12,8 +12,10 @@ def test_optional_imports_broken_installation(monkeypatch: pytest.MonkeyPatch) - real_import_module = importlib.import_module def fake_import_module(name: str, package: str | None = None) -> Any: - if name in ("ujson", "orjson"): - raise ImportError(f"simulated binary/load failure for {name}") + if name == "ujson": + raise ImportError("simulated binary/load failure for ujson") # pragma: no cover + if name == "orjson": + raise ImportError("simulated binary/load failure for orjson") # pragma: no cover return real_import_module(name, package) monkeypatch.setattr(importlib, "import_module", fake_import_module) @@ -23,6 +25,9 @@ def test_optional_imports_broken_installation(monkeypatch: pytest.MonkeyPatch) - # Force a reload to ensure the module initialization runs with our monkeypatch try: importlib.reload(fastapi.responses) + # Verify that the fallback worked and they are now None + assert fastapi.responses.ujson is None + assert fastapi.responses.orjson is None finally: # Revert the monkeypatch manually early so we can restore the module monkeypatch.undo()