conftest.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from __future__ import annotations
  2. import sys
  3. from pathlib import Path
  4. from typing import Any
  5. REPO_ROOT = Path(__file__).resolve().parents[1]
  6. def prepare_service_import(
  7. service_name: str,
  8. *,
  9. libs: tuple[str, ...],
  10. ) -> None:
  11. for module_name in list(sys.modules):
  12. if module_name == "app" or module_name.startswith("app."):
  13. del sys.modules[module_name]
  14. for lib_name in libs:
  15. lib_path = REPO_ROOT / "libs" / lib_name / "src"
  16. _prepend_sys_path(lib_path)
  17. _prepend_sys_path(REPO_ROOT / "services" / service_name)
  18. def _prepend_sys_path(path: Path) -> None:
  19. path_text = str(path)
  20. if path_text in sys.path:
  21. sys.path.remove(path_text)
  22. sys.path.insert(0, path_text)
  23. def build_fastapi_test_client(app: Any) -> Any:
  24. _patch_httpx_testclient_compatibility()
  25. from fastapi.testclient import TestClient
  26. return TestClient(app)
  27. def _patch_httpx_testclient_compatibility() -> None:
  28. import inspect
  29. import httpx
  30. if "app" in inspect.signature(httpx.Client.__init__).parameters:
  31. return
  32. if getattr(httpx.Client.__init__, "_agent_platform_patched", False):
  33. return
  34. original_init = httpx.Client.__init__
  35. def patched_init(self: httpx.Client, *args: Any, **kwargs: Any) -> None:
  36. kwargs.pop("app", None)
  37. original_init(self, *args, **kwargs)
  38. setattr(patched_init, "_agent_platform_patched", True)
  39. httpx.Client.__init__ = patched_init