223 lines
8.1 KiB
Python
223 lines
8.1 KiB
Python
from copy import deepcopy
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import pytest
|
|
from app.api.v1.compute_intelligence import configuration_admin, get_series, router
|
|
from app.core.security import get_current_user
|
|
from app.db.session import get_db
|
|
from app.models.system_log import AuditLog
|
|
from app.schemas.compute_configuration import ComputeConfiguration
|
|
from app.services.compute_configuration import (
|
|
DEFAULT_CONFIGURATION,
|
|
default_envelope,
|
|
publish_configuration,
|
|
read_configuration,
|
|
)
|
|
from app.services.compute_history import compute_history
|
|
from fastapi import FastAPI, HTTPException, Response
|
|
from httpx import ASGITransport, AsyncClient
|
|
from pydantic import ValidationError
|
|
|
|
|
|
def default_config():
|
|
return DEFAULT_CONFIGURATION.model_dump(mode="json")
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"mutation",
|
|
[
|
|
lambda value: value["observations"][0]["values"].update(CN=101),
|
|
lambda value: value["observations"][0]["values"].update(CN=-1),
|
|
lambda value: value["observations"][0]["values"].update(CN=float("nan")),
|
|
lambda value: value["observations"][0]["values"].update(CN=True),
|
|
lambda value: value["observations"][0]["values"].update(EUROPE=10),
|
|
lambda value: value["observations"][0].update(source_id="unknown"),
|
|
lambda value: value["observations"][0].update(year=2026),
|
|
lambda value: value["observations"].append(value["observations"][0]),
|
|
lambda value: value["sources"].append(value["sources"][0]),
|
|
lambda value: value["innovation"].append(value["innovation"][0]),
|
|
lambda value: value["sources"][0].update(url="javascript:alert(1)"),
|
|
lambda value: value["sources"][0].update(url="https://user:pass@example.com/report"),
|
|
],
|
|
)
|
|
def test_rejects_invalid_or_ambiguous_evidence(mutation):
|
|
payload = default_config()
|
|
mutation(payload)
|
|
with pytest.raises(ValidationError):
|
|
ComputeConfiguration.model_validate(payload)
|
|
|
|
|
|
def test_arbitrary_report_updates_values_sources_and_years_without_code_changes():
|
|
payload = default_config()
|
|
payload["sources"].append(
|
|
{
|
|
"id": "new-report",
|
|
"title": "New report",
|
|
"url": "https://example.com/report",
|
|
"publisher": "Research group",
|
|
"report_year": 2026,
|
|
"locator": "Figure 2",
|
|
}
|
|
)
|
|
payload["observations"].append(
|
|
{
|
|
"year": 2025,
|
|
"metric": "global_share",
|
|
"source_id": "new-report",
|
|
"values": {"CN": 25, "US": 50, "JP": 0},
|
|
}
|
|
)
|
|
config = ComputeConfiguration.model_validate(payload)
|
|
result = compute_history(["CN", "US", "JP", "EUROPE"], config=config)
|
|
row = next(row for row in result["compute"] if row["year"] == 2025)
|
|
assert row["values"] == {"CN": 25, "US": 50, "JP": 0, "EUROPE": None}
|
|
assert result["evidence"][row["evidence_id"]]["title"] == "New report"
|
|
assert DEFAULT_CONFIGURATION.model_dump(mode="json") == default_config()
|
|
|
|
|
|
def test_zero_bilateral_denominator_is_missing_and_empty_override_stays_empty():
|
|
payload = default_config()
|
|
payload["observations"][0]["values"] = {"CN": 0, "US": 0}
|
|
result = compute_history(
|
|
["CN", "US"], "bilateral_share", ComputeConfiguration.model_validate(payload)
|
|
)
|
|
assert result["compute"][0]["values"] == {"CN": None, "US": None}
|
|
payload.update(sources=[], observations=[], innovation=[])
|
|
result = compute_history(["CN"], config=ComputeConfiguration.model_validate(payload))
|
|
assert all(row["values"]["CN"] is None for row in result["compute"])
|
|
assert result["evidence"] == {}
|
|
|
|
|
|
def fake_db(record=None):
|
|
db = AsyncMock()
|
|
db.add = MagicMock()
|
|
result = MagicMock()
|
|
result.scalar_one_or_none.return_value = record
|
|
result.scalar_one.return_value = record
|
|
db.execute.return_value = result
|
|
return db
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fresh_install_uses_defaults_without_writing_database():
|
|
db = fake_db()
|
|
assert await read_configuration(db) == default_envelope()
|
|
db.add.assert_not_called()
|
|
db.commit.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_series_reads_persisted_override_and_disables_http_cache():
|
|
envelope = default_envelope()
|
|
envelope["is_default"] = False
|
|
envelope["revision"] = "custom"
|
|
envelope["config"]["observations"][3]["values"]["CN"] = 30
|
|
response = Response()
|
|
data = await get_series(
|
|
response, "CN,US", "global_share", fake_db(SimpleNamespace(payload=envelope))
|
|
)
|
|
assert data["compute"][3]["values"]["CN"] == 30
|
|
assert data["version"] == "custom"
|
|
assert data["provenance"] == "admin_curated_reports"
|
|
assert response.headers["Cache-Control"] == "no-store"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_publish_and_audit_are_one_transaction_and_conflicts_do_not_overwrite():
|
|
record = SimpleNamespace(payload=default_envelope())
|
|
db = fake_db(record)
|
|
actor = SimpleNamespace(id=1, username="admin")
|
|
old = deepcopy(record.payload)
|
|
result = await publish_configuration(
|
|
db,
|
|
revision=old["revision"],
|
|
config=DEFAULT_CONFIGURATION,
|
|
actor=actor,
|
|
)
|
|
assert result["revision"] != old["revision"]
|
|
audit = db.add.call_args.args[0]
|
|
assert isinstance(audit, AuditLog)
|
|
assert audit.details == {"before": old, "after": result}
|
|
assert audit.actor_id == actor.id
|
|
db.commit.assert_awaited_once()
|
|
with pytest.raises(HTTPException) as failure:
|
|
await publish_configuration(
|
|
db, revision=old["revision"], config=DEFAULT_CONFIGURATION, actor=actor
|
|
)
|
|
assert failure.value.status_code == 409
|
|
assert record.payload == result
|
|
db.rollback.assert_awaited_once()
|
|
db.commit.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_reset_changes_revision_and_restores_bundled_data():
|
|
record = SimpleNamespace(
|
|
payload={**default_envelope(), "revision": "custom", "is_default": False}
|
|
)
|
|
result = await publish_configuration(
|
|
fake_db(record),
|
|
revision="custom",
|
|
config=DEFAULT_CONFIGURATION,
|
|
actor=SimpleNamespace(id=1, username="admin"),
|
|
reset=True,
|
|
)
|
|
assert result["is_default"] is True
|
|
assert result["config"] == default_config()
|
|
assert result["revision"] != "custom"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("role", ["user", "viewer", "operator"])
|
|
async def test_non_admin_cannot_configure(role):
|
|
with pytest.raises(HTTPException) as failure:
|
|
await configuration_admin(SimpleNamespace(role=role))
|
|
assert failure.value.status_code == 403
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_http_configuration_auth_validation_and_public_series():
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
record = SimpleNamespace(payload=default_envelope())
|
|
db = fake_db(record)
|
|
app.dependency_overrides[get_db] = lambda: db
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
assert (await client.get("/configuration")).status_code == 401
|
|
assert (await client.get("/series")).status_code == 200
|
|
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
|
|
id=1,
|
|
username="admin",
|
|
role="admin",
|
|
)
|
|
loaded = (await client.get("/configuration")).json()
|
|
invalid = deepcopy(loaded["config"])
|
|
invalid["observations"][0]["values"]["CN"] = 200
|
|
response = await client.put(
|
|
"/configuration",
|
|
json={
|
|
"revision": loaded["revision"],
|
|
"config": invalid,
|
|
},
|
|
)
|
|
assert response.status_code == 422
|
|
db.commit.assert_not_awaited()
|
|
response = await client.put(
|
|
"/configuration",
|
|
json={
|
|
"revision": loaded["revision"],
|
|
"config": loaded["config"],
|
|
},
|
|
)
|
|
assert response.status_code == 200
|
|
assert response.json()["revision"] != loaded["revision"]
|
|
assert (
|
|
await client.post(
|
|
"/configuration/reset",
|
|
json={
|
|
"revision": loaded["revision"],
|
|
},
|
|
)
|
|
).status_code == 409
|