conftest.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """共享真实 ASGI 生命周期与隔离库;通过 portal 驱动同一个消费者,避免测试另写简化业务。"""
  2. import os
  3. from pathlib import Path
  4. import tempfile
  5. import sys
  6. import pytest
  7. sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
  8. os.environ['DATA_DIR'] = tempfile.mkdtemp(prefix='agent-audit-test-')
  9. os.environ['DATABASE_URL'] = ''
  10. os.environ['WORKER_ENABLED'] = 'false'
  11. os.environ['SEED_DEMO'] = 'true'
  12. os.environ['DEMO_PASSWORD'] = 'Demo@2026!'
  13. os.environ['RATE_LIMIT_PER_MINUTE'] = '10000'
  14. os.environ['APP_ENV'] = 'development'
  15. os.environ['JWT_SECRET'] = 'test-only-random-independent-secret-32'
  16. for name in ('LLM_BASE_URL', 'VLM_BASE_URL', 'EMBEDDING_BASE_URL', 'RERANK_BASE_URL', 'LLM_MODEL', 'VLM_MODEL'):
  17. os.environ[name] = ''
  18. from fastapi.testclient import TestClient
  19. from main import app
  20. from app.domain.models import Base
  21. from app.infrastructure.database import engine, transaction
  22. from app.application.seed import seed
  23. from app.application.worker import worker
  24. @pytest.fixture(scope='session')
  25. def client():
  26. with TestClient(app) as instance:
  27. yield instance
  28. @pytest.fixture(autouse=True)
  29. def isolated(client):
  30. async def reset():
  31. async with engine.begin() as connection:
  32. await connection.run_sync(Base.metadata.drop_all)
  33. await connection.run_sync(Base.metadata.create_all)
  34. async with transaction() as session:
  35. await seed(session)
  36. client.portal.call(reset)
  37. @pytest.fixture
  38. def headers(client):
  39. result = {}
  40. for name in ('alice', 'bob', 'carol', 'dave', 'erin'):
  41. response = client.post('/api/v1/auth/login', json={'username': name, 'password': 'Demo@2026!'})
  42. assert response.status_code == 200, response.text
  43. result[name] = {'Authorization': 'Bearer ' + response.json()['data']['access_token']}
  44. return result
  45. @pytest.fixture
  46. def drain(client):
  47. def process():
  48. for _ in range(20):
  49. if not client.portal.call(worker.process_one):
  50. return
  51. raise AssertionError('消费者没有在20个事件内收敛')
  52. return process