Files
FabledGrimoire/tests/test_mcp_tool_tasks.py
T
bvandeusenandClaude Opus 5.5 094089e374
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 2m23s
CI & Build / integration (push) Successful in 2m25s
CI & Build / Build & push image (push) Successful in 19s
test(8249): area groups, first pass: one file folded in, three readout checks merged, two copies removed
- test_mcp_tool_tasks_kind.py is folded into test_mcp_tool_tasks.py, the
  tool's own file: the two "kind passes through" cases are one table, the two
  list-filter cases one table; the minted_kind refusals move to the service's
  kind tests (test_services_notes_task_kind.py).
- A fresh install reads as empty, not failed: three database tests each ran
  retrieval_summary on an empty install and checked one block
  (usage, judged, system_usage). One test now checks all three.
- test_reply_shapes::test_the_tool_is_registered_as_a_read: everything it
  checked, test_moments::test_the_tools_are_registered_and_classified checks.
- test_shape_ledger::test_classify_and_list_are_mounted_as_mcp_tools: every
  classified tool name must be a registered tool
  (test_mcp_auth::test_every_registered_tool_is_classified_exactly_once).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:45:38 -05:00

321 lines
12 KiB
Python

"""Tests for fable_*_task tools."""
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from grimoire.mcp.tools.tasks import (
list_tasks, get_task, create_task,
update_task, add_task_log,
)
from tests.helpers import fake_note, fake_task
pytestmark = pytest.mark.usefixtures("_bind_user")
@pytest.mark.asyncio
async def test_list_tasks_passes_is_task_true_and_repackages():
rows = [fake_task(id=1, milestone_id=None), fake_task(id=2, milestone_id=None)]
mock = AsyncMock(return_value=(rows, 2))
with patch("grimoire.mcp.tools.tasks.notes_svc.list_notes", mock):
out = await list_tasks()
assert out["total"] == 2
assert len(out["tasks"]) == 2
assert mock.call_args.kwargs["is_task"] is True
@pytest.mark.asyncio
async def test_list_tasks_status_filter():
mock = AsyncMock(return_value=([], 0))
with patch("grimoire.mcp.tools.tasks.notes_svc.list_notes", mock):
await list_tasks(status="in_progress")
assert mock.call_args.kwargs["status"] == "in_progress"
@pytest.mark.asyncio
async def test_list_tasks_empty_status_means_no_filter():
mock = AsyncMock(return_value=([], 0))
with patch("grimoire.mcp.tools.tasks.notes_svc.list_notes", mock):
await list_tasks(status="")
assert mock.call_args.kwargs["status"] is None
@pytest.mark.asyncio
async def test_get_task_with_no_parent_returns_null_parent_title():
fake = fake_task(id=5, title="solo", parent_id=None)
with patch(
"grimoire.mcp.tools.tasks.notes_svc.get_note_for_user",
AsyncMock(return_value=(fake, "owner")),
):
out = await get_task(task_id=5)
assert out["parent_title"] is None
assert out["title"] == "solo"
assert "shared" not in out
@pytest.mark.asyncio
async def test_get_task_enriches_with_parent_title():
"""When parent_id is set, get_task fetches the parent and adds parent_title."""
child = fake_task(id=10, title="child", parent_id=5)
parent = fake_task(id=5, title="parent of 10", parent_id=None)
# fetched twice: once for the child, once for the parent
mock_get = AsyncMock(side_effect=[(child, "owner"), (parent, "owner")])
with patch("grimoire.mcp.tools.tasks.notes_svc.get_note_for_user", mock_get):
out = await get_task(task_id=10)
assert out["parent_title"] == "parent of 10"
assert mock_get.await_count == 2
@pytest.mark.asyncio
async def test_get_task_parent_missing_returns_null():
"""If parent_id is set but the parent is gone (orphaned), parent_title is None."""
child = fake_task(id=10, parent_id=5)
mock_get = AsyncMock(side_effect=[(child, "owner"), None])
with patch("grimoire.mcp.tools.tasks.notes_svc.get_note_for_user", mock_get):
out = await get_task(task_id=10)
assert out["parent_title"] is None
@pytest.mark.asyncio
async def test_get_task_opens_a_shared_task_and_says_whose_it_is():
"""A task in a shared project opens in the web UI, so the agent path must not
answer "not found" for the same id — and must say it isn't the caller's."""
theirs = fake_task(id=5, title="Their task", user_id=9)
with patch(
"grimoire.mcp.tools.tasks.notes_svc.get_note_for_user",
AsyncMock(return_value=(theirs, "viewer")),
), patch(
"grimoire.services.access.describe_provenance",
AsyncMock(return_value={"shared": True, "owner": "alex",
"permission": "viewer"}),
):
out = await get_task(task_id=5)
assert out["shared"] is True
assert out["owner"] == "alex"
@pytest.mark.asyncio
async def test_get_task_raises_when_not_found():
with patch(
"grimoire.mcp.tools.tasks.notes_svc.get_note_for_user",
AsyncMock(return_value=None),
):
with pytest.raises(ValueError, match="task 999 not found"):
await get_task(task_id=999)
@pytest.mark.asyncio
async def test_create_task_passes_status():
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.create_note", mock):
await create_task(title="do x", status="todo")
assert mock.call_args.kwargs["status"] == "todo"
@pytest.mark.asyncio
async def test_create_task_blocked_by_duplicate_gate():
"""A near-duplicate blocks creation and returns the existing id (no insert)."""
from grimoire.services.dedup import DuplicateMatch
dup = DuplicateMatch(id=42, title="Set up CI", similarity=1.0, reason="title")
create_mock = AsyncMock()
with patch("grimoire.mcp.tools.tasks.dedup_svc.find_duplicate_note",
AsyncMock(return_value=dup)), \
patch("grimoire.mcp.tools.tasks.notes_svc.create_note", create_mock):
out = await create_task(title="set up ci")
assert out["duplicate"] is True
assert out["existing_id"] == 42
create_mock.assert_not_called() # nothing was created
@pytest.mark.asyncio
async def test_create_task_force_bypasses_duplicate_gate():
"""force=true skips the gate entirely and creates."""
find_mock = AsyncMock()
with patch("grimoire.mcp.tools.tasks.dedup_svc.find_duplicate_note", find_mock), \
patch("grimoire.mcp.tools.tasks.notes_svc.create_note",
AsyncMock(return_value=fake_task(id=9))):
out = await create_task(title="dup", force=True)
assert out["id"] == 9
find_mock.assert_not_called() # gate not even consulted
@pytest.mark.asyncio
async def test_create_task_rejects_retired_plan_kind():
"""kind=plan is hard-retired — plans are milestones (start_planning)."""
mock = AsyncMock()
with patch("grimoire.mcp.tools.tasks.notes_svc.create_note", mock):
with pytest.raises(ValueError, match="kind=plan is retired"):
await create_task(title="x", kind="plan")
assert not mock.called # never reached the create
@pytest.mark.asyncio
async def test_create_task_priority_empty_becomes_none():
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.create_note", mock):
await create_task(title="x", priority="")
assert mock.call_args.kwargs["priority"] is None
@pytest.mark.asyncio
async def test_create_task_zero_id_sentinels_become_none():
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.create_note", mock):
await create_task(title="x", project_id=0, milestone_id=0, parent_id=0)
assert mock.call_args.kwargs["project_id"] is None
assert mock.call_args.kwargs["milestone_id"] is None
assert mock.call_args.kwargs["parent_id"] is None
@pytest.mark.asyncio
async def test_update_task_only_sends_non_default_fields():
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock):
await update_task(task_id=1, status="done")
args, kwargs = mock.call_args
assert args == (7, 1)
assert kwargs == {"status": "done"}
@pytest.mark.asyncio
async def test_update_task_empty_priority_is_omitted():
"""Priority="" is "leave unchanged" — must not reach service as empty string."""
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock):
await update_task(task_id=1, status="done", priority="")
assert "priority" not in mock.call_args.kwargs
@pytest.mark.asyncio
async def test_update_task_raises_when_not_found():
with patch(
"grimoire.mcp.tools.tasks.notes_svc.update_note",
AsyncMock(return_value=None),
):
with pytest.raises(ValueError, match="task 999 not found"):
await update_task(task_id=999, status="done")
@pytest.mark.asyncio
async def test_update_task_milestone_zero_is_omitted():
"""milestone_id=0 is 'leave unchanged' — must not reach the service."""
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock):
await update_task(task_id=1, milestone_id=0)
assert "milestone_id" not in mock.call_args.kwargs
@pytest.mark.asyncio
async def test_update_task_milestone_positive_is_set():
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock):
await update_task(task_id=1, milestone_id=42)
assert mock.call_args.kwargs["milestone_id"] == 42
@pytest.mark.asyncio
async def test_update_task_milestone_negative_one_clears():
"""milestone_id=-1 clears the milestone (sets the column NULL)."""
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock):
await update_task(task_id=1, milestone_id=-1)
assert mock.call_args.kwargs["milestone_id"] is None
@pytest.mark.asyncio
async def test_update_task_clearing_project_also_clears_milestone():
"""project_id=-1 clears the project and, with it, the milestone."""
fake = fake_task()
mock = AsyncMock(return_value=fake)
with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock):
await update_task(task_id=1, project_id=-1)
assert mock.call_args.kwargs["project_id"] is None
assert mock.call_args.kwargs["milestone_id"] is None
@pytest.mark.asyncio
async def test_add_task_log_returns_log_dict():
log = MagicMock()
log.id = 5
log.task_id = 1
log.content = "checkpoint"
log.created_at = datetime(2026, 5, 26, 12, tzinfo=timezone.utc)
# No to_dict on TaskLog model (per task_logs.py inspection) — fall through to manual dict
del log.to_dict
with patch(
"grimoire.mcp.tools.tasks.task_logs_svc.create_log",
AsyncMock(return_value=log),
):
out = await add_task_log(task_id=1, content="checkpoint")
assert out["id"] == 5
assert out["task_id"] == 1
assert out["content"] == "checkpoint"
assert out["created_at"].startswith("2026-05-26")
@pytest.mark.asyncio
async def test_add_task_log_propagates_value_error_when_task_missing():
"""create_log raises ValueError if the task doesn't exist; we let it through."""
with patch(
"grimoire.mcp.tools.tasks.task_logs_svc.create_log",
AsyncMock(side_effect=ValueError("Task 999 not found")),
):
with pytest.raises(ValueError):
await add_task_log(task_id=999, content="x")
# ── kind: the door passes it through, and "" leaves it alone ─────────────
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", ["issue", "spike"])
async def test_create_task_passes_the_kind_through(kind):
"""`spike` is the kind a failed rule-check asks for: time-boxed, and its
output is knowledge rather than a change, so filing one as `work` makes a
finished investigation look like an abandoned change."""
mock = AsyncMock(return_value=fake_note(task_kind=kind))
with patch("grimoire.mcp.tools.tasks.notes_svc.create_note", mock):
await create_task(title="Can the runner be given a bash shell?", kind=kind)
assert mock.call_args.kwargs["task_kind"] == kind
@pytest.mark.asyncio
@pytest.mark.parametrize("given,sent", [({"kind": "issue"}, "issue"), ({}, None)])
async def test_list_tasks_filters_by_kind_only_when_asked(given, sent):
mock = AsyncMock(return_value=([], 0))
with patch("grimoire.mcp.tools.tasks.notes_svc.list_notes", mock):
await list_tasks(**given)
assert mock.call_args.kwargs["task_kind"] == sent
@pytest.mark.asyncio
async def test_update_task_can_re_file_a_kind():
"""A task's kind must be CORRECTABLE, not write-once.
What a piece of work turns out to be is often clear only once it is under
way. Without a `kind` parameter on `update_task`, and with a REST route that
drops the field the editor sends, the save reports success and reverts on
reload.
"""
mock = AsyncMock(return_value=fake_note(task_kind="spike"))
with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock):
await update_task(task_id=1, kind="spike")
assert mock.call_args.kwargs["task_kind"] == "spike"
@pytest.mark.asyncio
async def test_update_task_leaves_kind_alone_when_not_given():
""""" means leave unchanged, as it does for every other field here."""
mock = AsyncMock(return_value=fake_note())
with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock):
await update_task(task_id=1, title="renamed")
assert "task_kind" not in mock.call_args.kwargs