Browse Source

tests: fix coverage and isolation for optional import fallback

pull/15537/head
Amandeep vishwkarma 2 months ago
parent
commit
545b9cbdc7
  1. 4
      fastapi/responses.py
  2. 9
      tests/test_responses_optional_imports.py

4
fastapi/responses.py

@ -61,7 +61,7 @@ class UJSONResponse(JSONResponse):
separately, e.g. `pip install ujson`. 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" assert ujson is not None, "ujson must be installed to use UJSONResponse"
return ujson.dumps(content, ensure_ascii=False).encode("utf-8") return ujson.dumps(content, ensure_ascii=False).encode("utf-8")
@ -91,7 +91,7 @@ class ORJSONResponse(JSONResponse):
separately, e.g. `pip install orjson`. 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" assert orjson is not None, "orjson must be installed to use ORJSONResponse"
return orjson.dumps( return orjson.dumps(
content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY

9
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 real_import_module = importlib.import_module
def fake_import_module(name: str, package: str | None = None) -> Any: def fake_import_module(name: str, package: str | None = None) -> Any:
if name in ("ujson", "orjson"): if name == "ujson":
raise ImportError(f"simulated binary/load failure for {name}") 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) return real_import_module(name, package)
monkeypatch.setattr(importlib, "import_module", fake_import_module) 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 # Force a reload to ensure the module initialization runs with our monkeypatch
try: try:
importlib.reload(fastapi.responses) 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: finally:
# Revert the monkeypatch manually early so we can restore the module # Revert the monkeypatch manually early so we can restore the module
monkeypatch.undo() monkeypatch.undo()

Loading…
Cancel
Save