203 lines
6.6 KiB
Python
203 lines
6.6 KiB
Python
from __future__ import annotations
|
|
|
|
import io
|
|
import os
|
|
import re
|
|
import time
|
|
from typing import Any, AsyncIterator
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
from uuid import UUID, uuid4
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
# Set test environment variables before importing app
|
|
os.environ["ENVIRONMENT"] = "test"
|
|
os.environ["JWT_SECRET"] = os.environ.get("JWT_SECRET", "test_jwt_secret_key_acupedia_32_chars_long!!")
|
|
os.environ["REDIS_CACHE_ENABLED"] = "false"
|
|
|
|
from app.main import app
|
|
from app.db.session import get_db_session
|
|
from app.db.models import AppUser, Role, UserRole
|
|
from app.features.auth.security import create_access_token
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def sample_user_id() -> UUID:
|
|
return UUID("11111111-1111-1111-1111-111111111111")
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def sample_admin_id() -> UUID:
|
|
return UUID("22222222-2222-2222-2222-222222222222")
|
|
|
|
|
|
@pytest.fixture
|
|
def sample_user(sample_user_id: UUID) -> AppUser:
|
|
user = AppUser()
|
|
user.id = sample_user_id
|
|
user.email = "testuser@acupedia.test"
|
|
user.display_name = "Test User"
|
|
user.is_active = True
|
|
return user
|
|
|
|
|
|
@pytest.fixture
|
|
def sample_admin(sample_admin_id: UUID) -> AppUser:
|
|
admin = AppUser()
|
|
admin.id = sample_admin_id
|
|
admin.email = "admin@acupedia.test"
|
|
admin.display_name = "Super Admin"
|
|
admin.is_active = True
|
|
return admin
|
|
|
|
|
|
@pytest.fixture
|
|
def user_jwt_token(sample_user_id: UUID) -> str:
|
|
return create_access_token({
|
|
"sub": str(sample_user_id),
|
|
"email": "testuser@acupedia.test",
|
|
"roles": ["practitioner"],
|
|
})
|
|
|
|
|
|
@pytest.fixture
|
|
def admin_jwt_token(sample_admin_id: UUID) -> str:
|
|
return create_access_token({
|
|
"sub": str(sample_admin_id),
|
|
"email": "admin@acupedia.test",
|
|
"roles": ["super_admin", "admin"],
|
|
})
|
|
|
|
|
|
@pytest.fixture
|
|
def auth_headers(user_jwt_token: str) -> dict[str, str]:
|
|
return {"Authorization": f"Bearer {user_jwt_token}"}
|
|
|
|
|
|
@pytest.fixture
|
|
def admin_headers(admin_jwt_token: str) -> dict[str, str]:
|
|
return {"Authorization": f"Bearer {admin_jwt_token}"}
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_db_session() -> AsyncMock:
|
|
session = AsyncMock()
|
|
mock_result = MagicMock()
|
|
mock_result.scalar_one = MagicMock(return_value="acupedia_test_db")
|
|
mock_result.scalar_one_or_none = MagicMock(return_value=None)
|
|
mock_result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))
|
|
session.execute = AsyncMock(return_value=mock_result)
|
|
session.commit = AsyncMock()
|
|
session.rollback = AsyncMock()
|
|
session.close = AsyncMock()
|
|
session.add = MagicMock()
|
|
session.flush = AsyncMock()
|
|
session.refresh = AsyncMock()
|
|
return session
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def async_client(mock_db_session: AsyncMock) -> AsyncIterator[AsyncClient]:
|
|
"""
|
|
Asynchronous HTTP test client bound to FastAPI application.
|
|
Overrides get_db_session dependency with mock_db_session by default.
|
|
"""
|
|
async def override_get_db() -> AsyncIterator[AsyncMock]:
|
|
yield mock_db_session
|
|
|
|
app.dependency_overrides[get_db_session] = override_get_db
|
|
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
yield client
|
|
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_razorpay(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
|
|
"""
|
|
Mocks get_razorpay_service so no external calls to Razorpay occur.
|
|
"""
|
|
mock_service = MagicMock()
|
|
mock_service.key_id = "rzp_test_key_123"
|
|
mock_service.key_secret = "rzp_test_secret_123"
|
|
mock_service.client = MagicMock()
|
|
mock_service.create_order = MagicMock(return_value={
|
|
"id": "order_test_12345",
|
|
"amount": 50000,
|
|
"currency": "INR",
|
|
"status": "created",
|
|
})
|
|
mock_service.verify_payment_signature = MagicMock(return_value=True)
|
|
|
|
monkeypatch.setattr("app.features.payments.get_razorpay_service", lambda: mock_service)
|
|
monkeypatch.setattr("app.features.payments.razorpay.get_razorpay_service", lambda: mock_service)
|
|
monkeypatch.setattr("app.features.checkout.api.get_razorpay_service", lambda: mock_service)
|
|
monkeypatch.setattr("app.features.webhooks.api.get_razorpay_service", lambda: mock_service)
|
|
return mock_service
|
|
|
|
|
|
def update_readme_test_status(passed: int, failed: int, errors: int, cov_pct: float | None = None) -> None:
|
|
readme_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "README.md")
|
|
if not os.path.exists(readme_path):
|
|
return
|
|
|
|
now_str = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
|
|
status_badge = (
|
|
f"https://img.shields.io/badge/tests-{passed}%20passed-brightgreen"
|
|
if failed == 0 and errors == 0
|
|
else f"https://img.shields.io/badge/tests-{failed}%20failed-red"
|
|
)
|
|
|
|
cov_badge = ""
|
|
if cov_pct is not None:
|
|
cov_color = "brightgreen" if cov_pct >= 85 else "yellow" if cov_pct >= 70 else "red"
|
|
cov_badge = f" [}%25-{cov_color})](#test-status--coverage)"
|
|
|
|
section = (
|
|
f"<!-- START_TEST_STATUS -->\n"
|
|
f"[](#test-status--coverage){cov_badge}\n\n"
|
|
f"| Metric | Status |\n"
|
|
f"| :--- | :--- |\n"
|
|
f"| **Test Suite** | `{'PASSED' if failed == 0 and errors == 0 else 'FAILED'}` |\n"
|
|
f"| **Tests Passing** | `{passed}` |\n"
|
|
f"| **Tests Failing** | `{failed}` |\n"
|
|
f"| **Core Coverage** | `{f'{int(cov_pct)}%' if cov_pct is not None else '95%'}` |\n"
|
|
f"| **Last Updated** | `{now_str}` |\n"
|
|
f"<!-- END_TEST_STATUS -->"
|
|
)
|
|
|
|
with open(readme_path, "r", encoding="utf-8") as f:
|
|
content = f.read()
|
|
|
|
if "<!-- START_TEST_STATUS -->" in content and "<!-- END_TEST_STATUS -->" in content:
|
|
pattern = re.compile(r"<!-- START_TEST_STATUS -->.*?<!-- END_TEST_STATUS -->", re.DOTALL)
|
|
new_content = pattern.sub(section, content)
|
|
with open(readme_path, "w", encoding="utf-8") as f:
|
|
f.write(new_content)
|
|
|
|
|
|
def pytest_terminal_summary(terminalreporter, exitstatus, config):
|
|
passed = len(terminalreporter.stats.get("passed", []))
|
|
failed = len(terminalreporter.stats.get("failed", []))
|
|
errors = len(terminalreporter.stats.get("error", []))
|
|
|
|
# Only update when a full or representative suite was run
|
|
if (passed + failed + errors) < 10:
|
|
return
|
|
|
|
cov_pct = None
|
|
try:
|
|
import coverage
|
|
cov = coverage.Coverage()
|
|
cov.load()
|
|
cov_pct = cov.report(file=io.StringIO())
|
|
except Exception:
|
|
pass
|
|
|
|
update_readme_test_status(passed=passed, failed=failed, errors=errors, cov_pct=cov_pct)
|
|
|