test_integration.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from uuid import uuid4
  2. import pytest
  3. from httpx import ASGITransport, AsyncClient
  4. from sqlalchemy import insert, text
  5. from sqlalchemy.exc import IntegrityError
  6. from zhifu.app import create_app
  7. from zhifu.modules.identity.models import Store, Tenant
  8. pytestmark = pytest.mark.integration
  9. async def test_application_and_database_constraints():
  10. app = create_app()
  11. async with app.router.lifespan_context(app):
  12. async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
  13. live = await client.get("/health/live")
  14. ready = await client.get("/health/ready")
  15. assert live.status_code == ready.status_code == 200
  16. assert live.headers["X-Request-ID"] != ready.headers["X-Request-ID"]
  17. async with app.state.engine.connect() as connection:
  18. transaction = await connection.begin()
  19. try:
  20. tenant_id = uuid4().bytes
  21. await connection.execute(insert(Tenant).values(id=tenant_id, name="验收商家"))
  22. await connection.execute(
  23. insert(Store).values(id=uuid4().bytes, tenant_id=tenant_id, name="验收店铺")
  24. )
  25. async with connection.begin_nested() as savepoint:
  26. with pytest.raises(IntegrityError):
  27. await connection.execute(
  28. insert(Store).values(
  29. id=uuid4().bytes, tenant_id=uuid4().bytes, name="无所属商家"
  30. )
  31. )
  32. await savepoint.rollback()
  33. assert await connection.scalar(text("SELECT @@session.time_zone")) == "+00:00"
  34. finally:
  35. await transaction.rollback()