test_int_api_gateway.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import pytest
  2. from clean_python import ctx
  3. from clean_python import DoesNotExist
  4. from clean_python import Json
  5. from clean_python import Tenant
  6. from clean_python.api_client import ApiGateway
  7. from clean_python.api_client import ApiProvider
  8. class BooksGateway(ApiGateway, path="v1/books/{id}"):
  9. pass
  10. async def fake_token():
  11. return {"Authorization": "Bearer token"}
  12. @pytest.fixture
  13. def provider(fastapi_example_app) -> ApiProvider:
  14. ctx.tenant = Tenant(id=2, name="")
  15. yield ApiProvider(fastapi_example_app + "/", fake_token)
  16. ctx.tenant = None
  17. @pytest.fixture
  18. def gateway(provider) -> ApiGateway:
  19. return BooksGateway(provider)
  20. @pytest.fixture
  21. async def book(gateway: ApiGateway):
  22. return await gateway.add({"title": "fixture", "author": {"name": "foo"}})
  23. async def test_add(gateway: ApiGateway):
  24. response = await gateway.add({"title": "test_add", "author": {"name": "foo"}})
  25. assert isinstance(response["id"], int)
  26. assert response["title"] == "test_add"
  27. assert response["author"] == {"name": "foo"}
  28. assert response["created_at"] == response["updated_at"]
  29. async def test_get(gateway: ApiGateway, book: Json):
  30. response = await gateway.get(book["id"])
  31. assert response == book
  32. async def test_remove_and_404(gateway: ApiGateway, book: Json):
  33. assert await gateway.remove(book["id"]) is True
  34. assert await gateway.get(book["id"]) is None
  35. assert await gateway.remove(book["id"]) is False
  36. async def test_update(gateway: ApiGateway, book: Json):
  37. response = await gateway.update({"id": book["id"], "title": "test_update"})
  38. assert response["id"] == book["id"]
  39. assert response["title"] == "test_update"
  40. assert response["author"] == {"name": "foo"}
  41. assert response["created_at"] != response["updated_at"]
  42. async def test_update_404(gateway: ApiGateway):
  43. with pytest.raises(DoesNotExist):
  44. await gateway.update({"id": 123456, "title": "test_update_404"})