test_service_context.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from http import HTTPStatus
  2. from uuid import UUID
  3. from uuid import uuid4
  4. import pytest
  5. from fastapi.testclient import TestClient
  6. from clean_python import ctx
  7. from clean_python import InMemoryGateway
  8. from clean_python.fastapi import get
  9. from clean_python.fastapi import Resource
  10. from clean_python.fastapi import Service
  11. from clean_python.fastapi import v
  12. class FooResource(Resource, version=v(1), name="testing"):
  13. @get("/context")
  14. def context(self):
  15. return {
  16. "path": str(ctx.path),
  17. "user": ctx.user,
  18. "tenant": ctx.tenant,
  19. "correlation_id": str(ctx.correlation_id),
  20. }
  21. @pytest.fixture
  22. def app():
  23. return Service(FooResource()).create_app(
  24. title="test",
  25. description="testing",
  26. hostname="testserver",
  27. access_logger_gateway=InMemoryGateway([]),
  28. )
  29. @pytest.fixture
  30. def client(app):
  31. return TestClient(app)
  32. def test_default_context(app, client: TestClient):
  33. response = client.get(app.url_path_for("v1/context"))
  34. assert response.status_code == HTTPStatus.OK
  35. body = response.json()
  36. assert body["path"] == "http://testserver/v1/context"
  37. assert body["user"] == {"id": "DEV", "name": "dev"}
  38. assert body["tenant"] is None
  39. UUID(body["correlation_id"]) # randomly generated uuid
  40. assert ctx.correlation_id is None
  41. def test_x_correlation_id_header(app, client: TestClient):
  42. uid = str(uuid4())
  43. response = client.get(
  44. app.url_path_for("v1/context"),
  45. headers={"X-Correlation-Id": uid},
  46. )
  47. assert response.status_code == HTTPStatus.OK
  48. body = response.json()
  49. assert body["correlation_id"] == uid
  50. assert ctx.correlation_id is None