test_main.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. 后端接口测试入口。
  3. 注意:测试函数使用同步 `def`,由 TestClient 驱动;勿对用例本身使用 `async def`。
  4. 执行示例: `pytest tests/test_main.py` 或 `pytest tests/`
  5. """
  6. import pytest
  7. from fastapi.testclient import TestClient
  8. def test_check_readiness(test_client: TestClient) -> None:
  9. """
  10. 校验 ``/common/health/ready/``:数据库与 Redis(若启用)均可达时返回 200 与 checks 结构。
  11. """
  12. response = test_client.get("/common/health/ready/")
  13. assert response.status_code == 200
  14. body = response.json()
  15. assert body["success"] is True
  16. assert body["data"] is not None
  17. assert "checks" in body["data"]
  18. assert body["data"]["checks"].get("database") is True
  19. def test_check_health(test_client: TestClient) -> None:
  20. """
  21. 校验 `/common/health/` 返回统一成功响应结构。
  22. 参数:
  23. - test_client (TestClient): pytest 注入的客户端。
  24. 返回:
  25. - None
  26. """
  27. response = test_client.get("/common/health/")
  28. assert response.status_code == 200
  29. body = response.json()
  30. assert body["success"] is True
  31. assert body["code"] == 0
  32. assert body["msg"] == "系统健康"
  33. assert body["data"] is True
  34. assert body["status_code"] == 200
  35. # 运行所有测试
  36. if __name__ == "__main__":
  37. pytest.main(["-v", "tests/test_main.py"])