Files
FabledScribe/tests/test_services_trash.py
T
bvandeusen 43a860c3ac
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 49s
CI & Build / Build & push image (push) Successful in 1m7s
feat(rules): project-scoped rules (S3)
Rules can now belong to either a rulebook topic OR a single project,
enforced by a CHECK constraint (exactly-one of topic_id/project_id).
Adds the create_project_rule MCP tool + REST endpoint, surfaces
project-scoped rules in get_project/get_task/start_planning under a
new project_rules field, and adds a project Rules tab section with an
inline create form so the operator can author project rules from the
UI without rulebook ceremony.

- migration 0059: rules.project_id (FK projects ON DELETE CASCADE),
  topic_id now nullable, CHECK ck_rule_topic_xor_project, index on
  project_id
- model: Rule gains project_id; to_dict exposes it
- service: create_project_rule with project-ownership guard; list_rules
  with project_id filter UNIONs subscription-derived + project-scoped;
  get_applicable_rules adds a project_rules field; get_rule / update_rule
  / delete_rule fetch via a shared _fetch_owned_rule that handles both
  rulebook and project ownership paths
- trash: project delete cascades to project-scoped rules
- MCP: create_project_rule tool registered; _INSTRUCTIONS mentions both
  create_rule and create_project_rule paths
- REST: POST /api/projects/<id>/rules (statement required, title derived
  if omitted)
- frontend: Rule type gains nullable topic_id + project_id; createProjectRule
  client; ProjectRulesTab.vue gains a "Project rules" section with inline
  create form and per-rule expand/delete
- tests: register count → 18; create_project_rule unit tests (required
  fields, title derivation, explicit-title pass-through); applicable_rules
  shape tests now include project_rules; trash cascade test updated to
  expect 5 executions

S1+S2 (always_on flag + Scribe-first prompt) shipped in 658348f.
S4 (enter_project handshake) follows.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 01:10:18 -04:00

151 lines
5.6 KiB
Python

"""Tests for services/trash.py — mocks async_session (no real DB)."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
def _make_mock_session():
s = AsyncMock()
s.__aenter__ = AsyncMock(return_value=s)
s.__aexit__ = AsyncMock(return_value=False)
s.commit = AsyncMock()
return s
def _exists_result(found=True):
r = MagicMock()
r.first.return_value = (1,) if found else None
return r
@pytest.mark.asyncio
async def test_delete_note_returns_batch_and_commits():
session = _make_mock_session()
# 1 execute for _exists_alive, then 2 for the note cascade (sub-tasks + self)
session.execute = AsyncMock(side_effect=[_exists_result(True), MagicMock(), MagicMock()])
with patch("fabledassistant.services.trash.async_session") as cls:
cls.return_value = session
from fabledassistant.services.trash import delete
batch = await delete(user_id=1, entity_type="note", entity_id=5)
assert isinstance(batch, str) and len(batch) > 0
assert session.commit.called
# exists-check + 2 cascade updates
assert session.execute.await_count == 3
@pytest.mark.asyncio
async def test_delete_returns_none_when_not_found():
session = _make_mock_session()
session.execute = AsyncMock(return_value=_exists_result(False))
with patch("fabledassistant.services.trash.async_session") as cls:
cls.return_value = session
from fabledassistant.services.trash import delete
batch = await delete(user_id=1, entity_type="task", entity_id=999)
assert batch is None
assert not session.commit.called
# only the existence check ran
assert session.execute.await_count == 1
@pytest.mark.asyncio
async def test_delete_project_cascades_to_notes_milestones_and_project_rules():
session = _make_mock_session()
# exists-check + 4 cascade updates (notes, milestones, project-scoped rules, project)
session.execute = AsyncMock(side_effect=[
_exists_result(True), MagicMock(), MagicMock(), MagicMock(), MagicMock(),
])
with patch("fabledassistant.services.trash.async_session") as cls:
cls.return_value = session
from fabledassistant.services.trash import delete
batch = await delete(user_id=1, entity_type="project", entity_id=3)
assert isinstance(batch, str)
assert session.execute.await_count == 5
@pytest.mark.asyncio
async def test_delete_rulebook_cascades_topics_and_rules():
session = _make_mock_session()
topic_ids_result = MagicMock()
topic_ids_result.scalars.return_value.all.return_value = [10, 11]
# exists-check, topic-id select, then 3 updates (rules, topics, rulebook)
session.execute = AsyncMock(side_effect=[
_exists_result(True), topic_ids_result, MagicMock(), MagicMock(), MagicMock(),
])
with patch("fabledassistant.services.trash.async_session") as cls:
cls.return_value = session
from fabledassistant.services.trash import delete
batch = await delete(user_id=7, entity_type="rulebook", entity_id=2)
assert isinstance(batch, str)
assert session.execute.await_count == 5
def _rowcount_result(n):
r = MagicMock()
r.rowcount = n
return r
@pytest.mark.asyncio
async def test_restore_clears_batch_across_all_models():
session = _make_mock_session()
# 7 models, each returns a rowcount
session.execute = AsyncMock(side_effect=[_rowcount_result(i) for i in [2, 0, 1, 1, 0, 0, 0]])
with patch("fabledassistant.services.trash.async_session") as cls:
cls.return_value = session
from fabledassistant.services.trash import restore
n = await restore(user_id=1, batch_id="abc")
assert n == 4
assert session.execute.await_count == 7
assert session.commit.called
@pytest.mark.asyncio
async def test_purge_expired_skips_when_retention_zero():
session = _make_mock_session()
session.execute = AsyncMock()
with patch("fabledassistant.services.trash.async_session") as cls:
cls.return_value = session
from fabledassistant.services.trash import purge_expired
n = await purge_expired(0)
assert n == 0
assert not session.execute.called # never opens a delete
@pytest.mark.asyncio
async def test_purge_expired_deletes_across_models_when_positive():
session = _make_mock_session()
session.execute = AsyncMock(side_effect=[_rowcount_result(1) for _ in range(7)])
with patch("fabledassistant.services.trash.async_session") as cls:
cls.return_value = session
from fabledassistant.services.trash import purge_expired
n = await purge_expired(90)
assert n == 7
assert session.execute.await_count == 7
@pytest.mark.asyncio
async def test_list_trash_groups_by_batch():
session = _make_mock_session()
def _note(id, batch, title):
from datetime import datetime, timezone
n = MagicMock()
n.id = id; n.deleted_batch_id = batch; n.title = title
n.deleted_at = datetime(2026, 5, 28, tzinfo=timezone.utc)
return n
# Note model returns 2 rows in one batch; the other 6 models return none.
note_rows = MagicMock()
note_rows.scalars.return_value.all.return_value = [_note(1, "b1", "Task A"), _note(2, "b1", "Sub")]
empty = MagicMock()
empty.scalars.return_value.all.return_value = []
session.execute = AsyncMock(side_effect=[note_rows] + [empty] * 6)
with patch("fabledassistant.services.trash.async_session") as cls:
cls.return_value = session
from fabledassistant.services.trash import list_trash
out = await list_trash(user_id=1)
assert len(out) == 1
assert out[0]["batch_id"] == "b1"
assert out[0]["count"] == 2
assert out[0]["summary"] == "Task A"