first
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
"""Pytest fixtures shared across asf-core tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
from asgi_lifespan import LifespanManager
|
||||
from httpx import AsyncClient, ASGITransport
|
||||
|
||||
from app.main import app
|
||||
from app.middleware.correlation import (
|
||||
request_context_var,
|
||||
RequestContext,
|
||||
)
|
||||
|
||||
|
||||
TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
|
||||
USER_ID = uuid.UUID("00000000-0000-0000-0000-000000000002")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tenant_context():
|
||||
"""Bind a dummy authenticated tenant+user context for the duration of a test."""
|
||||
|
||||
ctx = RequestContext(
|
||||
tenant_id=TENANT_ID,
|
||||
user_id=USER_ID,
|
||||
correlation_id="test-corr",
|
||||
roles=["admin"],
|
||||
)
|
||||
token = request_context_var.set(ctx)
|
||||
yield ctx
|
||||
request_context_var.reset(token)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def asf_client(tenant_context): # noqa: ARG001 - side effect
|
||||
"""Async httpx client pointed at the FastAPI app.
|
||||
|
||||
For unit tests in bootstrap mode we skip external infra by NOT starting
|
||||
the full lifespan; we instead instantiate routes with the tenant
|
||||
context bound so requests succeed without Mongo/Rabbit reachable.
|
||||
"""
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with LifespanManager(app, startup_timeout=10):
|
||||
async with AsyncClient(
|
||||
transport=transport,
|
||||
base_url="http://testserver",
|
||||
headers={
|
||||
"X-ASF-Tenant-Id": str(TENANT_ID),
|
||||
"X-ASF-User-Id": str(USER_ID),
|
||||
},
|
||||
) as c:
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def utc_now():
|
||||
return datetime(2026, 9, 7, 12, 0, 0, tzinfo=timezone.utc)
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Unit tests for domain services using stubbed repositories (no DB needed)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from asf_domain import (
|
||||
OrganizationCreate,
|
||||
ProjectCreate,
|
||||
ArtifactCreate,
|
||||
ArtifactType,
|
||||
ArtifactRelationshipCreate,
|
||||
RelationshipType,
|
||||
JobCreate,
|
||||
JobType,
|
||||
JobStatus,
|
||||
)
|
||||
|
||||
from app.services import (
|
||||
OrganizationService,
|
||||
ProjectService,
|
||||
ArtifactService,
|
||||
RelationshipService,
|
||||
JobService,
|
||||
)
|
||||
|
||||
|
||||
NOW = datetime(2026, 9, 7, 12, 0, 0, tzinfo=timezone.utc)
|
||||
TENANT = uuid4()
|
||||
USER = uuid4()
|
||||
|
||||
pytestmark = pytest.mark.anyio
|
||||
|
||||
|
||||
class _StubAudit:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[Any] = []
|
||||
|
||||
async def append(self, tenant_id: UUID, body: Any):
|
||||
self.events.append(body)
|
||||
return body # stub
|
||||
|
||||
|
||||
# ---------- Organizations ----------
|
||||
|
||||
async def test_org_service_create_returns_org():
|
||||
org_repo = AsyncMock()
|
||||
from asf_domain import Organization
|
||||
|
||||
created = Organization(
|
||||
id=uuid4(),
|
||||
name="Contoso",
|
||||
slug="contoso",
|
||||
plan="team",
|
||||
is_active=True,
|
||||
created_at=NOW,
|
||||
updated_at=NOW,
|
||||
)
|
||||
org_repo.create = AsyncMock(return_value=created)
|
||||
svc = OrganizationService(org_repo, _StubAudit(), actor_id=USER)
|
||||
|
||||
result = await svc.create(OrganizationCreate(name="Contoso", slug="contoso", plan="team"))
|
||||
assert result.slug == "contoso"
|
||||
org_repo.create.assert_awaited_once()
|
||||
|
||||
|
||||
# ---------- Projects ----------
|
||||
|
||||
async def test_project_service_create_checks_org_exists():
|
||||
project_repo = AsyncMock()
|
||||
org_repo = AsyncMock()
|
||||
org_repo.get = AsyncMock(return_value=None)
|
||||
|
||||
svc = ProjectService(project_repo, org_repo, _StubAudit(), tenant_id=TENANT, actor_id=USER)
|
||||
from app.repositories import NotFoundError
|
||||
|
||||
with pytest.raises(NotFoundError):
|
||||
await svc.create(ProjectCreate(name="Demo", key="DEMO"))
|
||||
|
||||
|
||||
# ---------- Artifacts ----------
|
||||
|
||||
async def test_artifact_service_create_checks_project():
|
||||
artifact_repo = AsyncMock()
|
||||
project_repo = AsyncMock()
|
||||
project_repo.get = AsyncMock(return_value=None)
|
||||
svc = ArtifactService(
|
||||
artifact_repo, project_repo, _StubAudit(), tenant_id=TENANT, actor_id=USER
|
||||
)
|
||||
from app.repositories import NotFoundError
|
||||
|
||||
with pytest.raises(NotFoundError):
|
||||
await svc.create(
|
||||
ArtifactCreate(
|
||||
project_id=uuid4(),
|
||||
type=ArtifactType.REQUIREMENT,
|
||||
title="Need MFA",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------- Jobs ----------
|
||||
|
||||
async def test_job_service_submit_creates_record():
|
||||
job_repo = AsyncMock()
|
||||
project_repo = AsyncMock()
|
||||
from asf_domain import Job
|
||||
|
||||
project_repo.get = AsyncMock(return_value=object()) # truthy
|
||||
new_job = Job(
|
||||
id=uuid4(),
|
||||
tenant_id=TENANT,
|
||||
project_id=uuid4(),
|
||||
type=JobType.AI_INTERACTIVE,
|
||||
status=JobStatus.QUEUED,
|
||||
payload={"question": "hi"},
|
||||
created_at=NOW,
|
||||
usage={},
|
||||
)
|
||||
job_repo.create = AsyncMock(return_value=new_job)
|
||||
|
||||
svc = JobService(job_repo, project_repo, _StubAudit(), tenant_id=TENANT, actor_id=USER)
|
||||
result = await svc.submit(
|
||||
JobCreate(
|
||||
type=JobType.AI_INTERACTIVE,
|
||||
payload={"question": "hi"},
|
||||
project_id=uuid4(),
|
||||
)
|
||||
)
|
||||
assert result.status == JobStatus.QUEUED
|
||||
job_repo.create.assert_awaited_once()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Smoke tests for health endpoints — do NOT require live Mongo."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.anyio
|
||||
|
||||
|
||||
async def test_root_endpoint_returns_metadata(asf_client):
|
||||
resp = await asf_client.get("/")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["name"] == "asf-core"
|
||||
assert "docs" in body
|
||||
assert body["health"] == "/api/v1/health"
|
||||
|
||||
|
||||
async def test_health_liveness_ok(asf_client):
|
||||
resp = await asf_client.get("/api/v1/health")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["status"] == "ok"
|
||||
assert body["service"] == "asf-core"
|
||||
assert "uptime_seconds" in body
|
||||
assert body["environment"] in {"development", "test", "production"}
|
||||
Reference in New Issue
Block a user