Files
aigc-home/calliope-backend/tests/test_projects.py
T
Benjiyaya f8faa72653 fix(agent): per-session event seq, parsed SSE echo, and vision attachments
Implements the intent of open PRs #48, #49, and part of #47 (all reviewed
against the working tree — none of the three bugs were fixed yet):

- #48 append_event returned cur.lastrowid (global row id) as the event's
  seq, while the INSERT allocates a per-session seq. The two only agree on
  a single-session DB, so ask_user's question_seq never matched
  latest_open_question() on a real install — card clicks never recorded an
  approval. The allocated seq is now read back from the inserted row; the
  atomic single-INSERT allocation is unchanged.

- #49 the agent.message SSE echo carried the raw agent_messages row
  (tool_args_json / tool_result_json strings, no parsed keys), while GET
  /sessions/{id} hands clients the parsed shape. _persist_message now
  returns parsed tool_args / tool_result alongside the raw keys, so the
  ask_user question card renders live instead of after a reload.

- #47 (partial) main.py carried the version as two literals that drifted
  from pyproject twice (1.3.2 reported 1.2.1; 1.4.1 reported 1.4.0). The
  version is now single-sourced in calliope.__version__, consumed by both
  FastAPI and /api/health; pyproject uses hatchling dynamic version. The
  PR's importlib.metadata approach was avoided: the venv's editable
  dist-info still says 0.1.0, which would report a third stale version.

- Vision attachments: user-attached images now project as OpenAI
  image_url content parts (data URLs read from disk), so vision-capable
  models see the actual pixels instead of a path line (derive_chat_rows /
  project_user_content, tested in test_agent_event_log).

Regression tests: per-session seq with a diverging second session, the
full card-answer flow across sessions, and the health version matching
the single-sourced metadata (tests/test_agent_interaction.py,
tests/test_projects.py).
2026-09-08 05:20:23 +08:00

144 lines
4.5 KiB
Python

from __future__ import annotations
import tempfile
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from calliope.config import Settings
from calliope.main import create_app
from calliope.db import migrate_db
@pytest.fixture
def client(monkeypatch):
with tempfile.TemporaryDirectory() as tmpdir:
import calliope.config as config_module
import asyncio
s = config_module.settings
prev = {
"data_dir": s.data_dir,
"assets_dir": s.assets_dir,
"dry_run": s.dry_run,
}
s.data_dir = Path(tmpdir)
s.assets_dir = Path(tmpdir) / "assets"
s.dry_run = True
monkeypatch.setattr(config_module.Settings, "save_config_file", lambda self: None)
asyncio.run(migrate_db(s.db_path))
app = create_app()
try:
with TestClient(app) as c:
yield c
finally:
for k, v in prev.items():
setattr(s, k, v)
def test_health(client):
r = client.get("/api/health")
assert r.status_code == 200
assert r.json()["status"] == "ok"
def test_health_version_matches_package_metadata(client):
"""PR #47: the served version must come from package metadata
(single-sourced via calliope.__version__), never a stale hard-coded
literal — 1.3.2 shipped reporting 1.2.1, 1.4.1 reported 1.4.0."""
import tomllib
from pathlib import Path
pyproject = Path(__file__).resolve().parents[1] / "pyproject.toml"
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
# dynamic = ["version"] means pyproject no longer carries the literal;
# the truth lives in src/calliope/__init__.py.
from calliope import __version__
assert data["project"].get("version") is None, (
"pyproject pins a literal version — single-source it via "
"calliope.__version__ (PR #47)"
)
r = client.get("/api/health")
assert r.json()["version"] == __version__
def test_create_and_list_project(client):
r = client.post("/api/projects", json={"title": "Test", "idea": "idea"})
assert r.status_code == 200
data = r.json()
assert data["title"] == "Test"
assert data["idea"] == "idea"
pid = data["id"]
r = client.get("/api/projects")
assert r.status_code == 200
assert any(p["id"] == pid for p in r.json())
def test_list_projects_includes_stats(client):
r = client.post("/api/projects", json={"title": "ListStats"})
pid = r.json()["id"]
r = client.get("/api/projects")
assert r.status_code == 200
item = next(p for p in r.json() if p["id"] == pid)
assert item["stats"] == {
"scene_count": 0,
"character_count": 0,
"asset_ready_count": 0,
"asset_total_count": 0,
}
def test_get_project_with_stats(client):
r = client.post("/api/projects", json={"title": "Stats"})
pid = r.json()["id"]
r = client.get(f"/api/projects/{pid}")
assert r.status_code == 200
data = r.json()
assert data["stats"]["scene_count"] == 0
def test_update_project(client):
r = client.post("/api/projects", json={"title": "Old"})
pid = r.json()["id"]
r = client.patch(f"/api/projects/{pid}", json={"title": "New"})
assert r.status_code == 200
assert r.json()["title"] == "New"
def test_update_project_cover(client):
r = client.post("/api/projects", json={"title": "Cover"})
pid = r.json()["id"]
assert r.json()["cover_path"] is None
r = client.patch(f"/api/projects/{pid}", json={"cover_path": "/tmp/cover.png"})
assert r.status_code == 200
assert r.json()["cover_path"] == "/tmp/cover.png"
r = client.get(f"/api/projects/{pid}")
assert r.json()["cover_path"] == "/tmp/cover.png"
r = client.get("/api/projects")
assert next(p for p in r.json() if p["id"] == pid)["cover_path"] == "/tmp/cover.png"
# Explicit null clears the cover again.
r = client.patch(f"/api/projects/{pid}", json={"cover_path": None})
assert r.status_code == 200
assert r.json()["cover_path"] is None
# Unrelated patches leave the (cleared) cover untouched.
r = client.patch(f"/api/projects/{pid}", json={"title": "Cover 2"})
assert r.json()["title"] == "Cover 2"
assert r.json()["cover_path"] is None
def test_delete_project(client):
r = client.post("/api/projects", json={"title": "Delete"})
pid = r.json()["id"]
r = client.delete(f"/api/projects/{pid}")
assert r.status_code == 200
r = client.get(f"/api/projects/{pid}")
assert r.status_code == 404