conftest.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import pytest
  2. from fastapi.testclient import TestClient
  3. from app.db.client import db_manager, get_db
  4. from app.main import app as fastapi_app
  5. @pytest.fixture(autouse=True)
  6. def helloagents_test_config(monkeypatch):
  7. """Give directly constructed HelloAgents agents an inert test configuration."""
  8. monkeypatch.setenv("API_KEY", "test-key")
  9. monkeypatch.setenv("MODEL_NAME", "test-model")
  10. monkeypatch.setenv("BASE_URL", "https://example.test/v1/")
  11. @pytest.fixture(scope="function")
  12. def test_database(tmp_path):
  13. """Point the global database manager at an isolated database per test."""
  14. original_state = {
  15. "url": db_manager.url,
  16. "is_remote": db_manager.is_remote,
  17. "is_postgres": db_manager.is_postgres,
  18. "auth_token": db_manager.auth_token,
  19. }
  20. database_path = (tmp_path / "madf.db").resolve().as_posix()
  21. db_manager.url = f"file:{database_path}"
  22. db_manager.is_remote = False
  23. db_manager.is_postgres = False
  24. db_manager.auth_token = None
  25. db_manager.init_db()
  26. yield
  27. for name, value in original_state.items():
  28. setattr(db_manager, name, value)
  29. @pytest.fixture(scope="function")
  30. def db(test_database):
  31. connection = db_manager.get_connection()
  32. try:
  33. yield connection
  34. finally:
  35. connection.close()
  36. @pytest.fixture(scope="function")
  37. def client(test_database):
  38. def override_get_db():
  39. connection = db_manager.get_connection()
  40. try:
  41. yield connection
  42. finally:
  43. connection.close()
  44. fastapi_app.dependency_overrides[get_db] = override_get_db
  45. try:
  46. with TestClient(fastapi_app, raise_server_exceptions=False) as test_client:
  47. yield test_client
  48. finally:
  49. fastapi_app.dependency_overrides.clear()