This commit is contained in:
xuhd committed 2026-05-19 09:40:19 +08:00
commit 070cd07199
372 files changed
+86240 -4969

No files matched your search

@@ -0,0 +1,77 @@
"""Tests for admin (cross-user) deletion of scheduled-task runs.
Regular users may only delete runs they own; admins may delete any run. This
covers the service/store layer that the admin-aware ``DELETE /runs/{id}``
route relies on.
"""
from __future__ import annotations
from datetime import UTC, datetime
import pytest
from deerflow.persistence.scheduled_tasks import MemoryScheduledTaskStore
from deerflow.runtime.scheduler.service import ScheduledTaskService
@pytest.fixture
def store() -> MemoryScheduledTaskStore:
return MemoryScheduledTaskStore()
def _build_service(store: MemoryScheduledTaskStore) -> ScheduledTaskService:
service = ScheduledTaskService(app=None, store=store, poll_interval_seconds=60.0)
service._element_client = None # noqa: SLF001
return service
async def _seed_run(store: MemoryScheduledTaskStore, *, run_id: str, task_id: str, user_id: str) -> None:
await store.create_run_once(
{
"id": run_id,
"task_id": task_id,
"user_id": user_id,
"scheduler_thread_id": f"thread-{user_id}",
"scheduled_for": datetime.now(UTC),
"status": "succeeded",
"started_at": datetime.now(UTC),
}
)
@pytest.mark.asyncio
async def test_admin_delete_run_removes_any_owner_run(store):
await _seed_run(store, run_id="r1", task_id="t1", user_id="alice")
service = _build_service(store)
assert await service.admin_delete_run("r1") is True
assert await store.get_run_any("r1") is None
@pytest.mark.asyncio
async def test_admin_delete_run_missing_returns_false(store):
service = _build_service(store)
assert await service.admin_delete_run("nope") is False
@pytest.mark.asyncio
async def test_owner_delete_run_still_scoped_to_owner(store):
"""A non-owner, non-subscriber deleting another user's run gets False."""
await _seed_run(store, run_id="r1", task_id="t1", user_id="alice")
service = _build_service(store)
assert await service.delete_run("bob", "r1") is False
assert await store.get_run_any("r1") is not None # untouched
# The owner can still delete their own run.
assert await service.delete_run("alice", "r1") is True
assert await store.get_run_any("r1") is None
@pytest.mark.asyncio
async def test_store_delete_run_any_independent_of_owner(store):
await _seed_run(store, run_id="r1", task_id="t1", user_id="alice")
assert await store.delete_run_any("r1") is True
assert await store.delete_run_any("r1") is False
@@ -0,0 +1,116 @@
"""Tests for per-user scheduled-task name uniqueness.
Task names are unique per user (``uq_scheduled_tasks_user_name``). The service
proactively rejects collisions with :class:`DuplicateTaskNameError` so the API
returns a 409 instead of letting a raw DB ``IntegrityError`` surface as a 500.
"""
from __future__ import annotations
from datetime import UTC, datetime
import pytest
from deerflow.persistence.scheduled_tasks import MemoryScheduledTaskStore
from deerflow.runtime.scheduler import DuplicateTaskNameError
from deerflow.runtime.scheduler.service import ScheduledTaskService
@pytest.fixture
def store() -> MemoryScheduledTaskStore:
return MemoryScheduledTaskStore()
def _build_service(store: MemoryScheduledTaskStore) -> ScheduledTaskService:
service = ScheduledTaskService(app=None, store=store, poll_interval_seconds=60.0)
service._element_client = None # noqa: SLF001
return service
def _seed_task(store: MemoryScheduledTaskStore, *, task_id: str, user_id: str, name: str) -> dict:
task = {
"task_id": task_id,
"user_id": user_id,
"scheduler_thread_id": f"thread-{user_id}",
"name": name,
"prompt": "hello",
"schedule_text": "0 9 * * *",
"cron_expr": "0 9 * * *",
"timezone": "UTC",
"enabled": True,
"next_run_at": datetime.now(UTC),
"execution_context": {},
}
store._tasks[task_id] = task # noqa: SLF001
return task
@pytest.mark.asyncio
async def test_create_task_rejects_duplicate_name(store):
"""A second task with the same (user_id, name) is refused before any insert."""
_seed_task(store, task_id="t1", user_id="alice", name="日报")
service = _build_service(store)
with pytest.raises(DuplicateTaskNameError):
await service.create_task(user_id="alice", name="日报", prompt="p", schedule="0 9 * * *")
@pytest.mark.asyncio
async def test_create_task_treats_whitespace_padded_name_as_duplicate(store):
"""The name is trimmed before the uniqueness check, matching what is stored."""
_seed_task(store, task_id="t1", user_id="alice", name="日报")
service = _build_service(store)
with pytest.raises(DuplicateTaskNameError):
await service.create_task(user_id="alice", name=" 日报 ", prompt="p", schedule="0 9 * * *")
@pytest.mark.asyncio
async def test_create_task_allows_same_name_for_different_user(store):
"""The constraint is per user — another user may reuse the name.
The create proceeds past the name check and only fails later because the
test service has no app wired for scheduler-thread setup; the point here is
that no DuplicateTaskNameError is raised.
"""
_seed_task(store, task_id="t1", user_id="alice", name="日报")
service = _build_service(store)
with pytest.raises(Exception) as exc_info:
await service.create_task(user_id="bob", name="日报", prompt="p", schedule="0 9 * * *")
assert not isinstance(exc_info.value, DuplicateTaskNameError)
@pytest.mark.asyncio
async def test_update_task_rejects_rename_to_existing_name(store):
"""Renaming a task onto a sibling's name is refused."""
_seed_task(store, task_id="t1", user_id="alice", name="日报")
_seed_task(store, task_id="t2", user_id="alice", name="周报")
service = _build_service(store)
with pytest.raises(DuplicateTaskNameError):
await service.update_task("alice", "t2", {"name": "日报"})
@pytest.mark.asyncio
async def test_update_task_allows_keeping_own_name(store):
"""Re-saving a task without changing its name is not a self-collision."""
_seed_task(store, task_id="t1", user_id="alice", name="日报")
service = _build_service(store)
updated = await service.update_task("alice", "t1", {"name": "日报", "prompt": "new"})
assert updated is not None
assert updated["name"] == "日报"
assert updated["prompt"] == "new"
@pytest.mark.asyncio
async def test_admin_update_task_rejects_rename_to_existing_name(store):
"""Admin cross-user rename still honours the owner's name uniqueness."""
_seed_task(store, task_id="t1", user_id="alice", name="日报")
_seed_task(store, task_id="t2", user_id="alice", name="周报")
service = _build_service(store)
with pytest.raises(DuplicateTaskNameError):
await service.admin_update_task("t2", {"name": "日报"})
@@ -0,0 +1,80 @@
"""Regression tests for the scheduled-task run lookup helper.
Guards against a recursion bug where ``_load_run`` called itself instead of
delegating to ``service.get_run`` — every ``GET /api/scheduled-tasks/runs/{id}``
blew the stack with ``RecursionError`` and returned 500.
"""
from __future__ import annotations
import pytest
from app.gateway.routers import scheduled_tasks as st
class _FakeService:
"""Records delegation so the test can assert no self-recursion happened."""
def __init__(self, *, owner_run=None, admin_run=None) -> None:
self._owner_run = owner_run
self._admin_run = admin_run
self.get_run_calls: list[tuple[str, str]] = []
self.admin_get_run_calls: list[str] = []
async def get_run(self, user_id: str, run_id: str):
self.get_run_calls.append((user_id, run_id))
return self._owner_run
async def admin_get_run(self, run_id: str):
self.admin_get_run_calls.append(run_id)
return self._admin_run
class _User:
def __init__(self, system_role: str | None) -> None:
self.system_role = system_role
def _patch_user(monkeypatch, user) -> None:
async def _fake(_request):
return user
monkeypatch.setattr(st, "get_optional_user_from_request", _fake)
@pytest.mark.asyncio
async def test_load_run_returns_owner_run_without_recursing(monkeypatch):
"""Owner lookup hits service.get_run exactly once — no self-recursion."""
_patch_user(monkeypatch, _User("user"))
service = _FakeService(owner_run={"id": "r1"})
run = await st._load_run(service, object(), "r1", "alice")
assert run == {"id": "r1"}
assert service.get_run_calls == [("alice", "r1")]
assert service.admin_get_run_calls == [] # admin fallback skipped when found
@pytest.mark.asyncio
async def test_load_run_admin_fallback_when_owner_miss(monkeypatch):
"""An admin who is not the owner falls back to admin_get_run."""
_patch_user(monkeypatch, _User("admin"))
service = _FakeService(owner_run=None, admin_run={"id": "r2"})
run = await st._load_run(service, object(), "r2", "bob")
assert run == {"id": "r2"}
assert service.get_run_calls == [("bob", "r2")]
assert service.admin_get_run_calls == ["r2"]
@pytest.mark.asyncio
async def test_load_run_non_admin_miss_returns_none(monkeypatch):
"""A non-admin who is not the owner gets None (router turns it into 404)."""
_patch_user(monkeypatch, _User("user"))
service = _FakeService(owner_run=None, admin_run={"id": "r3"})
run = await st._load_run(service, object(), "r3", "carol")
assert run is None
assert service.admin_get_run_calls == [] # no admin fallback for non-admins
@@ -17,6 +17,7 @@ import pytest
from app.gateway.routers.skills import (
SkillDetailRequest,
SkillResponse,
_can_view_skill_source,
_skill_to_response,
)
from deerflow.config import paths as paths_module
@@ -160,3 +161,29 @@ def test_skill_to_response_detail_none_without_ownership(isolated_paths) -> None
resp = _skill_to_response(skill, None)
assert resp.detail is None
assert resp.builtin is True
# ---------------------------------------------------------------------------
# SKILL.md source visibility — admin / publisher only
# ---------------------------------------------------------------------------
def test_admin_can_view_any_skill_source() -> None:
# Admin sees a built-in skill's source (no owner).
assert _can_view_skill_source(SkillCategory.PUBLIC, None, "user-a", is_admin=True) is True
# ...and another user's custom skill.
assert _can_view_skill_source(SkillCategory.CUSTOM, "user-b", "user-a", is_admin=True) is True
def test_publisher_can_view_own_custom_skill_source() -> None:
assert _can_view_skill_source(SkillCategory.CUSTOM, "user-a", "user-a", is_admin=False) is True
def test_non_owner_cannot_view_custom_skill_source() -> None:
# A different user — even if the skill is published to them — cannot read source.
assert _can_view_skill_source(SkillCategory.CUSTOM, "user-b", "user-a", is_admin=False) is False
def test_non_admin_cannot_view_builtin_skill_source() -> None:
# Built-in / public skills have no publisher, so non-admins never see source.
assert _can_view_skill_source(SkillCategory.PUBLIC, None, "user-a", is_admin=False) is False