This commit is contained in:
新新 committed 2026-04-27 17:03:56 +08:00
commit fe636432d0
154 files changed
+30381

No files matched your search

+114
View File
@@ -0,0 +1,114 @@
from __future__ import annotations
import os
import shutil
import sys
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
os.environ["DATABASE_URL"] = "sqlite:///./test_document_cleaning.db"
os.environ["DATA_ROOT"] = "./test_data"
os.environ["PUBLIC_BASE_URL"] = "http://testserver"
os.environ["INTEGRATION_API_KEY"] = "integration-secret"
os.environ["INTEGRATION_DOWNLOAD_SECRET"] = "integration-download-secret"
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.config import get_settings # noqa: E402
from app.database import Base, get_db # noqa: E402
from app.main import app # noqa: E402
from app.models import Department, SystemSetting, User # noqa: E402
from app.security import hash_password # noqa: E402
TEST_DB = Path("./test_document_cleaning.db")
TEST_DATA_ROOT = Path("./test_data")
if TEST_DB.exists():
TEST_DB.unlink()
if TEST_DATA_ROOT.exists():
shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True)
TEST_DATA_ROOT.mkdir(parents=True, exist_ok=True)
engine = create_engine("sqlite:///./test_document_cleaning.db", connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
@pytest.fixture
def initialized_db():
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True)
get_settings().ensure_data_dirs()
db = TestingSessionLocal()
db.add(
Department(
id=1,
name="测试部门",
description="测试部门",
)
)
db.add(
SystemSetting(
id=1,
dify_permission="all_team_members",
indexing_technique="high_quality",
search_method="hybrid_search",
doc_form="text_model",
top_k=5,
score_threshold_enabled=True,
score_threshold="0.35",
)
)
db.add(
User(
username="admin",
full_name="System Admin",
password_hash=hash_password("admin123456"),
role="super_admin",
is_active=True,
primary_department_id=1,
)
)
db.add(
User(
username="adam",
full_name="Adam",
password_hash=hash_password("admin123456"),
role="admin",
is_active=True,
primary_department_id=1,
)
)
db.commit()
db.close()
yield
shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True)
@pytest.fixture
def client(initialized_db):
with TestClient(app) as test_client:
yield test_client
@pytest.fixture
def db_session(initialized_db):
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
+119
View File
@@ -0,0 +1,119 @@
from __future__ import annotations
import uuid
from pathlib import Path
from app.database import SessionLocal
from app.models import Department, Document, DocumentVersion, Group, User, UserDepartmentAccess
from app.security import hash_password
def _token(client, username: str, password: str):
response = client.post("/api/auth/login", json={"username": username, "password": password})
return response.json()["access_token"]
def _headers(client, username: str, password: str):
return {"Authorization": f"Bearer {_token(client, username, password)}"}
def _seed_access_fixture() -> tuple[int, int]:
db = SessionLocal()
try:
super_admin = db.query(User).filter(User.username == "admin").first()
assert super_admin is not None
blocked_department = Department(name=f"blocked-dept-{uuid.uuid4().hex[:6]}", description="blocked")
db.add(blocked_department)
db.commit()
db.refresh(blocked_department)
scoped_user = User(
username="scoped-user",
full_name="Scoped User",
password_hash=hash_password("scoped123"),
role="user",
is_active=True,
primary_department_id=1,
)
db.add(scoped_user)
db.commit()
db.refresh(scoped_user)
allowed_group = Group(name=f"allowed-{uuid.uuid4().hex[:8]}", created_by_id=super_admin.id, department_id=1)
blocked_group = Group(
name=f"blocked-{uuid.uuid4().hex[:8]}",
created_by_id=super_admin.id,
department_id=blocked_department.id,
)
db.add_all([allowed_group, blocked_group])
db.commit()
db.refresh(allowed_group)
db.refresh(blocked_group)
db.add(UserDepartmentAccess(user_id=scoped_user.id, department_id=1))
db.commit()
allowed_document = Document(group_id=allowed_group.id, title="allowed-doc", created_by_id=super_admin.id, is_deleted=False)
blocked_document = Document(group_id=blocked_group.id, title="blocked-doc", created_by_id=super_admin.id, is_deleted=False)
db.add_all([allowed_document, blocked_document])
db.commit()
db.refresh(allowed_document)
db.refresh(blocked_document)
db.add_all(
[
DocumentVersion(
document_id=allowed_document.id,
version_no=1,
is_current=True,
source_filename="allowed.docx",
source_ext=".docx",
source_path=str(Path("allowed.docx")),
source_sha256=uuid.uuid4().hex,
file_size=12,
uploader_id=super_admin.id,
convert_status="success",
sync_status="unsynced",
),
DocumentVersion(
document_id=blocked_document.id,
version_no=1,
is_current=True,
source_filename="blocked.docx",
source_ext=".docx",
source_path=str(Path("blocked.docx")),
source_sha256=uuid.uuid4().hex,
file_size=12,
uploader_id=super_admin.id,
convert_status="success",
sync_status="unsynced",
),
]
)
db.commit()
return allowed_group.id, blocked_group.id
finally:
db.close()
def test_groups_and_files_are_scoped_by_user_access(client):
allowed_group_id, blocked_group_id = _seed_access_fixture()
headers = _headers(client, "scoped-user", "scoped123")
groups_response = client.get("/api/groups", headers=headers)
assert groups_response.status_code == 200
groups = groups_response.json()["data"]
assert len(groups) == 1
assert groups[0]["id"] == allowed_group_id
summary_response = client.get("/api/groups/summary", headers=headers)
assert summary_response.status_code == 200
assert summary_response.json()["knowledge_base_count"] == 1
assert summary_response.json()["file_count"] == 1
allowed_files = client.get(f"/api/groups/{allowed_group_id}/files", headers=headers)
blocked_files = client.get(f"/api/groups/{blocked_group_id}/files", headers=headers)
assert allowed_files.status_code == 200
assert len(allowed_files.json()["data"]) == 1
assert blocked_files.status_code == 403
+699
View File
@@ -0,0 +1,699 @@
from __future__ import annotations
import json
import uuid
from datetime import timedelta
from app.config import get_settings
from app.database import SessionLocal
from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, User, UserDepartmentAccess
from app.security import hash_password
from app.services.bootstrap_service import ensure_defaults
from app.time_utils import utc_now
def _token(client, username: str = "admin", password: str = "admin123456"):
response = client.post("/api/auth/login", json={"username": username, "password": password})
return response.json()["access_token"]
def _headers(client, username: str = "admin", password: str = "admin123456"):
return {"Authorization": f"Bearer {_token(client, username=username, password=password)}"}
def _create_user(*, username: str, password: str, role: str = "user", full_name: str = "User") -> int:
db = SessionLocal()
try:
user = User(
username=username,
full_name=full_name,
password_hash=hash_password(password),
role=role,
is_active=True,
primary_department_id=1,
)
db.add(user)
db.commit()
db.refresh(user)
return user.id
finally:
db.close()
def _create_group(*, name: str) -> int:
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=name, created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
return group.id
finally:
db.close()
def _create_department(*, name: str, description: str = "test department") -> int:
db = SessionLocal()
try:
department = Department(name=name, description=description)
db.add(department)
db.commit()
db.refresh(department)
return department.id
finally:
db.close()
def _create_stale_syncing_document() -> tuple[int, str]:
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
group = Group(name=f"health-group-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="stale-health", created_by_id=admin_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="stale.docx",
source_ext=".docx",
source_path="/tmp/stale.docx",
source_sha256=uuid.uuid4().hex,
file_size=128,
uploader_id=admin_id,
convert_status="success",
sync_status="syncing",
)
db.add(version)
db.commit()
db.refresh(version)
old_time = utc_now() - timedelta(minutes=20)
job = Job(
id=str(uuid.uuid4()),
job_type="sync",
status="running",
group_id=group.id,
document_id=document.id,
version_id=version.id,
created_by_id=admin_id,
created_at=old_time,
started_at=old_time,
)
db.add(job)
db.commit()
record = DifySyncRecord(
version_id=version.id,
dataset_id="dataset-health",
remote_document_id="remote-health",
batch="batch-health",
status="syncing",
created_at=old_time,
updated_at=old_time,
)
db.add(record)
db.commit()
return version.id, job.id
finally:
db.close()
def _create_stale_convert_document() -> tuple[int, str]:
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
group = Group(name=f"convert-health-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="convert-stale-health", created_by_id=admin_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
old_time = utc_now() - timedelta(minutes=20)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="convert-stale.docx",
source_ext=".docx",
source_path="/tmp/convert-stale.docx",
source_sha256=uuid.uuid4().hex,
file_size=128,
uploader_id=admin_id,
convert_status="queued",
sync_status="unsynced",
uploaded_at=old_time,
)
db.add(version)
db.commit()
db.refresh(version)
job = Job(
id=str(uuid.uuid4()),
job_type="convert",
status="queued",
queue_job_id="missing-convert-job",
group_id=group.id,
document_id=document.id,
version_id=version.id,
created_by_id=admin_id,
created_at=old_time,
)
db.add(job)
db.commit()
return version.id, job.id
finally:
db.close()
def test_admin_can_create_and_update_users(client):
group_id = _create_group(name=f"access-{uuid.uuid4().hex[:8]}")
create_response = client.post(
"/api/admin/users",
json={
"username": "operator",
"password": "operator123",
"full_name": "Ops User",
"role": "user",
"primary_department_id": 1,
"accessible_department_ids": [1],
},
headers=_headers(client),
)
assert create_response.status_code == 200
assert create_response.json()["username"] == "operator"
assert create_response.json()["accessible_department_ids"] == [1]
db = SessionLocal()
try:
user = db.query(User).filter(User.username == "operator").first()
assert user is not None
user_id = user.id
finally:
db.close()
update_response = client.patch(
f"/api/admin/users/{user_id}",
json={
"full_name": "Operations User",
"role": "admin",
"is_active": False,
"primary_department_id": 1,
"accessible_department_ids": [1],
},
headers=_headers(client),
)
assert update_response.status_code == 200
body = update_response.json()
assert body["full_name"] == "Operations User"
assert body["role"] == "admin"
assert body["is_active"] is False
assert body["accessible_department_ids"] == [1]
def test_admin_can_delete_user_and_clear_created_by_references(client):
user_id = _create_user(username=f"delete-user-{uuid.uuid4().hex[:8]}", password="delete123", role="user", full_name="Delete User")
db = SessionLocal()
try:
user = db.query(User).filter(User.id == user_id).first()
admin = db.query(User).filter(User.username == "admin").first()
assert user is not None
assert admin is not None
group = Group(name=f"delete-user-group-{uuid.uuid4().hex[:8]}", created_by_id=user_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title=f"delete-user-doc-{uuid.uuid4().hex[:8]}", created_by_id=user_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="delete-user.docx",
source_ext=".docx",
source_path="/tmp/delete-user.docx",
source_sha256=uuid.uuid4().hex,
file_size=128,
uploader_id=user_id,
convert_status="success",
sync_status="unsynced",
)
db.add(version)
db.add(Job(id=str(uuid.uuid4()), job_type="convert", status="success", created_by_id=user_id, document_id=document.id, version_id=version.id))
db.commit()
group_id = group.id
document_id = document.id
version_id = version.id
finally:
db.close()
response = client.delete(f"/api/admin/users/{user_id}", headers=_headers(client))
assert response.status_code == 200
assert response.json()["deleted_user_id"] == user_id
db = SessionLocal()
try:
assert db.query(User).filter(User.id == user_id).first() is None
group = db.query(Group).filter(Group.id == group_id).first()
document = db.query(Document).filter(Document.id == document_id).first()
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.document_id == document_id).first()
assert group is not None and group.created_by_id is None
assert document is not None and document.created_by_id is None
assert version is not None and version.uploader_id is None
assert job is not None and job.created_by_id is None
finally:
db.close()
def test_admin_delete_protects_primary_super_admin_and_self(client):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
finally:
db.close()
delete_admin = client.delete(f"/api/admin/users/{admin_id}", headers=_headers(client))
assert delete_admin.status_code == 400
assert "cannot be deleted" in delete_admin.json()["detail"]
username = f"self-delete-{uuid.uuid4().hex[:8]}"
user_id = _create_user(username=username, password="self123", role="admin", full_name="Self Delete")
self_delete = client.delete(
f"/api/admin/users/{user_id}",
headers=_headers(client, username=username, password="self123"),
)
assert self_delete.status_code == 400
assert "cannot delete your own account" in self_delete.json()["detail"].lower()
def test_only_admin_can_hold_super_admin_role(client):
create_response = client.post(
"/api/admin/users",
json={
"username": "other-super",
"password": "operator123",
"full_name": "Other Super",
"role": "super_admin",
"primary_department_id": 1,
"accessible_department_ids": [],
},
headers=_headers(client),
)
assert create_response.status_code == 400
assert "Only admin can be a super admin" in create_response.json()["detail"]
db = SessionLocal()
try:
admin_user = db.query(User).filter(User.username == "admin").first()
operator = User(
username="operator-promote",
full_name="Operator Promote",
password_hash=hash_password("operator123"),
role="admin",
is_active=True,
primary_department_id=1,
)
db.add(operator)
db.commit()
db.refresh(operator)
assert admin_user is not None
operator_id = operator.id
admin_id = admin_user.id
finally:
db.close()
promote_response = client.patch(
f"/api/admin/users/{operator_id}",
json={"role": "super_admin"},
headers=_headers(client),
)
assert promote_response.status_code == 400
assert "Only admin can be a super admin" in promote_response.json()["detail"]
demote_admin = client.patch(
f"/api/admin/users/{admin_id}",
json={"role": "admin"},
headers=_headers(client),
)
assert demote_admin.status_code == 400
assert "admin must remain a super admin" in demote_admin.json()["detail"]
def test_bootstrap_keeps_admin_as_unique_super_admin():
db = SessionLocal()
try:
rogue = User(
username="legacy-super",
full_name="Legacy Super",
password_hash=hash_password("legacy123"),
role="super_admin",
is_active=True,
primary_department_id=None,
)
db.add(rogue)
db.commit()
ensure_defaults(db)
admin = db.query(User).filter(User.username == "admin").first()
legacy = db.query(User).filter(User.username == "legacy-super").first()
adam = db.query(User).filter(User.username == "adam").first()
assert admin is not None
assert admin.role == "super_admin"
assert legacy is not None
assert legacy.role == "admin"
assert legacy.primary_department_id is None
assert adam is not None
assert adam.role == "admin"
finally:
db.close()
def test_admin_can_read_and_update_settings(client):
initial = client.get("/api/admin/settings", headers=_headers(client))
assert initial.status_code == 200
assert initial.json()["search_method"] == "hybrid_search"
updated = client.patch(
"/api/admin/settings",
json={
"search_method": "semantic_search",
"top_k": 8,
"score_threshold_enabled": False,
"score_threshold": 0.4,
"embedding_model_provider": "langgenius/siliconflow/siliconflow",
"embedding_model": "Qwen/Qwen3-Embedding-8B",
"reranking_model_provider": "langgenius/siliconflow/siliconflow",
"reranking_model": "Qwen/Qwen3-Reranker-8B",
},
headers=_headers(client),
)
assert updated.status_code == 200
body = updated.json()
assert body["search_method"] == "semantic_search"
assert body["top_k"] == 8
assert body["score_threshold_enabled"] is False
assert body["score_threshold"] == 0.4
assert body["embedding_model_provider"] == "langgenius/siliconflow/siliconflow"
assert body["embedding_model"] == "Qwen/Qwen3-Embedding-8B"
assert body["reranking_model_provider"] == "langgenius/siliconflow/siliconflow"
assert body["reranking_model"] == "Qwen/Qwen3-Reranker-8B"
def test_empty_department_can_be_deleted(client):
department_id = _create_department(name=f"empty-dept-{uuid.uuid4().hex[:8]}")
response = client.request(
"DELETE",
f"/api/admin/departments/{department_id}",
headers=_headers(client),
json={"target_department_id": None},
)
assert response.status_code == 200
assert response.json()["deleted_department_id"] == department_id
db = SessionLocal()
try:
assert db.query(Department).filter(Department.id == department_id).first() is None
finally:
db.close()
def test_department_delete_requires_migration_when_department_is_in_use(client):
source_department_id = _create_department(name=f"source-dept-{uuid.uuid4().hex[:8]}")
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"in-use-group-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=source_department_id)
db.add(group)
db.commit()
finally:
db.close()
response = client.request(
"DELETE",
f"/api/admin/departments/{source_department_id}",
headers=_headers(client),
json={"target_department_id": None},
)
assert response.status_code == 400
assert "Choose another department to migrate first" in response.json()["detail"]
def test_department_delete_can_migrate_knowledge_bases_and_user_access(client):
source_department_id = _create_department(name=f"source-migrate-{uuid.uuid4().hex[:8]}")
target_department_id = _create_department(name=f"target-migrate-{uuid.uuid4().hex[:8]}")
operator_id = _create_user(username=f"dept-user-{uuid.uuid4().hex[:8]}", password="operator123", role="user", full_name="Dept User")
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
operator = db.query(User).filter(User.id == operator_id).first()
assert admin is not None
assert operator is not None
admin.primary_department_id = target_department_id
operator.primary_department_id = source_department_id
db.add(UserDepartmentAccess(user_id=admin.id, department_id=source_department_id))
group = Group(name=f"migrate-group-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=source_department_id)
db.add(group)
db.commit()
db.refresh(group)
group_id = group.id
admin_id = admin.id
finally:
db.close()
response = client.request(
"DELETE",
f"/api/admin/departments/{source_department_id}",
headers=_headers(client),
json={"target_department_id": target_department_id},
)
assert response.status_code == 200
payload = response.json()
assert payload["migrated_to_department_id"] == target_department_id
assert payload["knowledge_base_count"] == 1
assert payload["primary_user_count"] == 1
assert payload["extra_user_count"] == 1
db = SessionLocal()
try:
assert db.query(Department).filter(Department.id == source_department_id).first() is None
group = db.query(Group).filter(Group.id == group_id).first()
operator = db.query(User).filter(User.id == operator_id).first()
admin = db.query(User).filter(User.id == admin_id).first()
assert group is not None
assert operator is not None
assert admin is not None
assert group.department_id == target_department_id
assert operator.primary_department_id == target_department_id
assert db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id, UserDepartmentAccess.department_id == source_department_id).first() is None
assert db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id, UserDepartmentAccess.department_id == target_department_id).first() is None
finally:
db.close()
def test_admin_can_read_available_dify_models(client, monkeypatch):
class FakeDifyService:
def list_available_embedding_models(self):
return [
type("Model", (), {"provider": "provider-a", "model": "embed-a", "label": "Provider A / embed-a"})()
]
def list_available_rerank_models(self):
return [
type("Model", (), {"provider": "provider-b", "model": "rerank-b", "label": "Provider B / rerank-b"})()
]
def resolve_embedding_model_choice(self, *, provider=None, model=None):
return ("provider-a", "embed-a")
def resolve_rerank_model_choice(self, *, provider=None, model=None):
return ("provider-b", "rerank-b")
monkeypatch.setattr("app.api.admin.DifyService", FakeDifyService)
response = client.get("/api/admin/dify-models", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["embedding_models"][0]["model"] == "embed-a"
assert payload["rerank_models"][0]["model"] == "rerank-b"
assert payload["automatic_defaults"] == {
"embedding_model_provider": "provider-a",
"embedding_model": "embed-a",
"reranking_model_provider": "provider-b",
"reranking_model": "rerank-b",
}
def test_admin_endpoints_require_admin_and_job_list_scopes_by_user(client):
user_id = _create_user(username="viewer", password="viewer123", role="user", full_name="Viewer")
admin_id = _create_user(username="ops-admin", password="ops123456", role="admin", full_name="Ops Admin")
admin_headers = _headers(client)
user_headers = _headers(client, username="viewer", password="viewer123")
ops_headers = _headers(client, username="ops-admin", password="ops123456")
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"ops-scope-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
db.add(UserDepartmentAccess(user_id=admin_id, department_id=1))
db.add_all(
[
Job(
id=str(uuid.uuid4()),
job_type="convert",
status="success",
created_by_id=admin.id,
group_id=group.id,
payload={"owner": "admin"},
),
Job(
id=str(uuid.uuid4()),
job_type="sync",
status="queued",
created_by_id=user_id,
payload={"owner": "viewer"},
),
Job(
id=str(uuid.uuid4()),
job_type="sync",
status="queued",
created_by_id=admin_id,
group_id=group.id,
payload={"owner": "ops-admin"},
),
]
)
db.commit()
finally:
db.close()
forbidden_users = client.get("/api/admin/users", headers=user_headers)
forbidden_settings = client.get("/api/admin/settings", headers=user_headers)
allowed_user_admin = client.get("/api/admin/users", headers=ops_headers)
allowed_health_admin = client.get("/api/admin/dify-health", headers=ops_headers)
assert forbidden_users.status_code == 403
assert forbidden_settings.status_code == 403
assert allowed_user_admin.status_code == 200
assert allowed_health_admin.status_code == 200
admin_jobs = client.get("/api/jobs", headers=admin_headers)
assert admin_jobs.status_code == 200
assert len(admin_jobs.json()["data"]) == 3
user_jobs = client.get("/api/jobs", headers=user_headers)
assert user_jobs.status_code == 200
assert len(user_jobs.json()["data"]) == 1
assert user_jobs.json()["data"][0]["payload"] == {"owner": "viewer"}
ops_jobs = client.get("/api/jobs", headers=ops_headers)
assert ops_jobs.status_code == 200
assert len(ops_jobs.json()["data"]) == 2
def test_admin_dify_health_reads_snapshot_and_local_summary(client):
path = get_settings().data_root / "watchdog" / "dify-health.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(
{
"status": "ok",
"queue_lengths": {"priority_dataset": 1},
"worker": {"concurrency": 2},
}
),
encoding="utf-8",
)
_create_stale_syncing_document()
response = client.get("/api/admin/dify-health", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["watchdog_snapshot"]["worker"]["concurrency"] == 2
assert payload["local_convert_health"]["pending_versions"] == 0
assert payload["local_sync_health"]["stale_candidates"] == 1
assert payload["dify_api_configured"] is False
def test_admin_can_recover_stale_syncs(client):
version_id, job_id = _create_stale_syncing_document()
response = client.post("/api/admin/recover-stale-syncs", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["recovered_versions"] == 1
assert payload["recovered_jobs"] == 1
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.sync_status == "sync_failed"
assert job.status == "failed"
finally:
db.close()
def test_admin_can_recover_stale_converts(client, monkeypatch):
version_id, job_id = _create_stale_convert_document()
monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set())
response = client.post("/api/admin/recover-stale-converts", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["recovered_versions"] == 1
assert payload["recovered_jobs"] == 1
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.convert_status == "failed"
assert job.status == "failed"
finally:
db.close()
+24
View File
@@ -0,0 +1,24 @@
from app.config import Settings
def test_settings_default_to_sqlite_when_no_database_url_override():
settings = Settings(database_url="", database_backend="sqlite")
assert settings.database_url == "sqlite:///./document_cleaning.db"
def test_settings_select_postgres_url_from_backend_choice():
settings = Settings(
database_url="",
database_backend="postgres",
postgres_database_url="postgresql://postgres:difyai123456@localhost:5432/doccleaning_db",
)
assert settings.database_url == "postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db"
def test_settings_keep_database_url_override_highest_priority():
settings = Settings(
database_backend="sqlite",
database_url="postgresql://postgres:difyai123456@localhost:5432/doccleaning_db",
sqlite_database_url="sqlite:///./other.db",
)
assert settings.database_url == "postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db"
+238
View File
@@ -0,0 +1,238 @@
from __future__ import annotations
import uuid
from pathlib import Path
from types import SimpleNamespace
from app.config import get_settings
from app.database import SessionLocal
from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User
from app.services.storage_service import version_dir
def _token(client, username: str = "admin", password: str = "admin123456"):
response = client.post("/api/auth/login", json={"username": username, "password": password})
return response.json()["access_token"]
def _headers(client, username: str = "admin", password: str = "admin123456"):
return {"Authorization": f"Bearer {_token(client, username=username, password=password)}"}
def _seed_document_for_delete(*, with_remote_sync: bool) -> tuple[int, Path, Path, Path]:
settings = get_settings()
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"delete-{uuid.uuid4().hex[:8]}", description="Delete coverage", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="manual", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
source_root = version_dir("original", group.id, document.id, 1)
markdown_root = version_dir("markdown", group.id, document.id, 1)
assets_root = version_dir("assets", group.id, document.id, 1)
source_root.mkdir(parents=True, exist_ok=True)
markdown_root.mkdir(parents=True, exist_ok=True)
assets_root.mkdir(parents=True, exist_ok=True)
source_path = source_root / "manual.docx"
markdown_path = markdown_root / "document.md"
asset_path = assets_root / "img_001.png"
source_path.write_bytes(b"source")
markdown_path.write_text("# Manual", encoding="utf-8")
asset_path.write_bytes(b"png")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="manual.docx",
source_ext=".docx",
source_path=str(source_path),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
md_public_url="http://testserver/storage/markdown/document.md",
asset_dir=str(assets_root.relative_to(settings.data_root)),
file_size=source_path.stat().st_size,
uploader_id=admin.id,
convert_status="success",
sync_status="synced" if with_remote_sync else "unsynced",
)
db.add(version)
db.commit()
db.refresh(version)
if with_remote_sync:
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-001",
remote_document_id="remote-001",
status="synced",
)
)
db.commit()
return document.id, source_root, markdown_root, assets_root
finally:
db.close()
def test_delete_file_marks_document_deleted_and_enqueues_cleanup(client, monkeypatch):
document_id, source_root, markdown_root, assets_root = _seed_document_for_delete(with_remote_sync=False)
enqueue_calls: list[tuple[str, tuple[object, ...]]] = []
class FakeQueue:
def enqueue(self, task_name: str, *args, **kwargs):
enqueue_calls.append((task_name, args))
return SimpleNamespace(id="queued-delete-job")
monkeypatch.setattr("app.api.files.get_queue", lambda: FakeQueue())
response = client.delete(f"/api/files/{document_id}?delete_dify=false", headers=_headers(client))
assert response.status_code == 200
assert response.json() == {"deleted": True}
db = SessionLocal()
try:
document = db.query(Document).filter(Document.id == document_id).first()
job = db.query(Job).filter(Job.document_id == document_id, Job.job_type == "delete").first()
assert document is not None
assert job is not None
assert document.is_deleted is True
assert "__deleted__" in document.title
finally:
db.close()
assert enqueue_calls
assert enqueue_calls[0][0] == "app.tasks.run_delete_document_job"
assert enqueue_calls[0][1][1] == document_id
assert source_root.exists()
assert markdown_root.exists()
assert assets_root.exists()
def test_batch_markdown_download_returns_zip_file(client):
document_id, source_root, markdown_root, assets_root = _seed_document_for_delete(with_remote_sync=False)
response = client.post(
"/api/files/download-batch",
json={"document_ids": [document_id], "kind": "md"},
headers=_headers(client),
)
assert response.status_code == 200
assert "zip" in response.headers["content-type"]
assert len(response.content) > 0
def test_sync_endpoint_rejects_already_synced_current_version(client):
settings = get_settings()
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"sync-{uuid.uuid4().hex[:8]}", description="Sync coverage", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="already-synced", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
markdown_root = version_dir("markdown", group.id, document.id, 1)
markdown_root.mkdir(parents=True, exist_ok=True)
markdown_path = markdown_root / "document.md"
markdown_path.write_text("# Synced", encoding="utf-8")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="already-synced.docx",
source_ext=".docx",
source_path=str(settings.data_root / "tmp" / "already-synced.docx"),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add(version)
db.commit()
db.refresh(version)
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-001",
remote_document_id="remote-001",
status="synced",
)
)
db.commit()
file_id = document.id
finally:
db.close()
response = client.post(f"/api/files/{file_id}/sync-dify", headers=_headers(client))
assert response.status_code == 409
assert response.json()["detail"] == "Current version is already synced to Dify."
def test_sync_endpoint_rejects_current_version_already_syncing(client):
settings = get_settings()
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"syncing-{uuid.uuid4().hex[:8]}", description="Sync coverage", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="already-syncing", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
markdown_root = version_dir("markdown", group.id, document.id, 1)
markdown_root.mkdir(parents=True, exist_ok=True)
markdown_path = markdown_root / "document.md"
markdown_path.write_text("# Syncing", encoding="utf-8")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="already-syncing.docx",
source_ext=".docx",
source_path=str(settings.data_root / "tmp" / "already-syncing.docx"),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="syncing",
)
db.add(version)
db.commit()
db.refresh(version)
file_id = document.id
finally:
db.close()
response = client.post(f"/api/files/{file_id}/sync-dify", headers=_headers(client))
assert response.status_code == 409
assert response.json()["detail"] == "Current version is already syncing to Dify."
+266
View File
@@ -0,0 +1,266 @@
from __future__ import annotations
import uuid
from app.config import get_settings
from app.database import Base, SessionLocal
from app.models import DifySyncRecord, Document, DocumentVersion, Group, User
from app.services.storage_service import version_dir
def _integration_headers() -> dict[str, str]:
return {"X-Integration-Key": "integration-secret"}
def _seed_integration_document() -> tuple[int, int]:
settings = get_settings()
db = SessionLocal()
try:
Base.metadata.create_all(bind=db.get_bind())
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(
name=f"integration-group-{uuid.uuid4().hex[:8]}",
description="Integration coverage",
created_by_id=admin.id,
department_id=1,
dify_dataset_id="dataset-integration",
)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="integration-file", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
source_root = version_dir("original", group.id, document.id, 1)
markdown_root = version_dir("markdown", group.id, document.id, 1)
assets_root = version_dir("assets", group.id, document.id, 1)
source_root.mkdir(parents=True, exist_ok=True)
markdown_root.mkdir(parents=True, exist_ok=True)
assets_root.mkdir(parents=True, exist_ok=True)
source_path = source_root / "integration-file.docx"
markdown_path = markdown_root / "document.md"
source_path.write_bytes(b"source")
markdown_path.write_text("# Integration", encoding="utf-8")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="integration-file.docx",
source_ext=".docx",
source_path=str(source_path),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
md_public_url=f"{settings.public_base_url}/storage/{markdown_path.relative_to(settings.data_root).as_posix()}",
asset_dir=str(assets_root.relative_to(settings.data_root)),
file_size=source_path.stat().st_size,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add(version)
db.commit()
db.refresh(version)
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-integration",
remote_document_id="remote-integration",
status="synced",
)
)
db.commit()
return group.id, document.id
finally:
db.close()
def test_integration_api_requires_service_key(client):
response = client.get("/api/integration/knowledge-bases")
assert response.status_code == 401
def test_integration_api_requires_download_secret(client):
settings = get_settings()
previous_key = settings.integration_api_key
previous_secret = settings.integration_download_secret
settings.integration_api_key = "integration-secret"
settings.integration_download_secret = ""
try:
_seed_integration_document()
response = client.get("/api/integration/files/1", headers=_integration_headers())
assert response.status_code == 503
assert response.json()["detail"] == "Integration download secret is not configured."
finally:
settings.integration_api_key = previous_key
settings.integration_download_secret = previous_secret
def test_integration_api_lists_knowledge_bases_and_files(client, monkeypatch):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
group_id, document_id = _seed_integration_document()
knowledge_bases = client.get("/api/integration/knowledge-bases", headers=_integration_headers())
assert knowledge_bases.status_code == 200
kb_payload = knowledge_bases.json()["data"]
assert len(kb_payload) == 1
assert kb_payload[0]["id"] == group_id
assert kb_payload[0]["dify_dataset_id"] == "dataset-integration"
files = client.get(f"/api/integration/knowledge-bases/{group_id}/files", headers=_integration_headers())
assert files.status_code == 200
file_payload = files.json()["data"]
assert len(file_payload) == 1
assert file_payload[0]["document_id"] == document_id
assert file_payload[0]["source_filename"] == "integration-file.docx"
assert "/api/integration/download?version_id=" in file_payload[0]["source_download_url"]
assert file_payload[0]["markdown_download_url"] is not None
assert file_payload[0]["queried_at"] is not None
assert file_payload[0]["download_url_expires_at"] is not None
detail = client.get(f"/api/integration/files/{document_id}", headers=_integration_headers())
assert detail.status_code == 200
detail_payload = detail.json()
assert detail_payload["knowledge_base"]["id"] == group_id
assert detail_payload["dify"]["remote_document_id"] == "remote-integration"
finally:
settings.integration_api_key = previous_key
def test_integration_api_downloads_source_and_markdown(client):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
_, document_id = _seed_integration_document()
detail = client.get(f"/api/integration/files/{document_id}", headers=_integration_headers())
assert detail.status_code == 200
payload = detail.json()
source_download = client.get(payload["source_download_url"].replace("http://testserver", ""))
assert source_download.status_code == 200
assert "integration-file.docx" in source_download.headers["content-disposition"]
markdown_download = client.get(payload["markdown_download_url"].replace("http://testserver", ""))
assert markdown_download.status_code == 200
assert "integration-file.md" in markdown_download.headers["content-disposition"]
finally:
settings.integration_api_key = previous_key
def test_integration_api_can_lookup_local_file_by_dify_ids(client):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
group_id, document_id = _seed_integration_document()
response = client.get(
"/api/integration/dify-file?dataset_id=dataset-integration&remote_document_id=remote-integration",
headers=_integration_headers(),
)
assert response.status_code == 200
payload = response.json()
assert payload["document_id"] == document_id
assert payload["knowledge_base"]["id"] == group_id
assert payload["dify"]["dataset_id"] == "dataset-integration"
assert payload["dify"]["remote_document_id"] == "remote-integration"
assert "version_id=" in payload["source_download_url"]
finally:
settings.integration_api_key = previous_key
def test_integration_api_lookup_by_dify_ids_uses_matched_version_not_unsynced_current_version(client):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
_, document_id = _seed_integration_document()
db = SessionLocal()
try:
document = db.query(Document).filter(Document.id == document_id).first()
assert document is not None
current_version = document.versions[0]
current_version.is_current = False
new_root = version_dir("original", document.group_id, document.id, 2)
new_root.mkdir(parents=True, exist_ok=True)
new_source = new_root / "integration-file-v2.docx"
new_source.write_bytes(b"new-source")
new_version = DocumentVersion(
document_id=document.id,
version_no=2,
is_current=True,
source_filename="integration-file-v2.docx",
source_ext=".docx",
source_path=str(new_source),
source_sha256=uuid.uuid4().hex,
file_size=new_source.stat().st_size,
uploader_id=document.created_by_id,
convert_status="success",
sync_status="unsynced",
)
db.add(new_version)
db.commit()
finally:
db.close()
response = client.get(
"/api/integration/dify-file?dataset_id=dataset-integration&remote_document_id=remote-integration",
headers=_integration_headers(),
)
assert response.status_code == 200
payload = response.json()
assert payload["source_filename"] == "integration-file.docx"
assert payload["dify"]["remote_document_id"] == "remote-integration"
assert "version_id=1" in payload["source_download_url"]
finally:
settings.integration_api_key = previous_key
def test_integration_api_can_batch_resolve_by_dify_ids(client):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
_, document_id = _seed_integration_document()
response = client.post(
"/api/integration/dify-files/resolve",
headers=_integration_headers(),
json={
"items": [
{"dataset_id": "dataset-integration", "remote_document_id": "remote-integration"},
{"dataset_id": "dataset-integration", "remote_document_id": "remote-missing"},
{"remote_document_id": "remote-integration"},
]
},
)
assert response.status_code == 200
payload = response.json()["data"]
assert len(payload) == 3
assert payload[0]["request"]["remote_document_id"] == "remote-integration"
assert payload[0]["found"] is True
assert payload[0]["document"]["document_id"] == document_id
assert payload[1]["request"]["remote_document_id"] == "remote-missing"
assert payload[1]["found"] is False
assert payload[1]["document"] is None
assert payload[2]["request"]["dataset_id"] is None
assert payload[2]["found"] is True
assert payload[2]["document"]["dify"]["remote_document_id"] == "remote-integration"
finally:
settings.integration_api_key = previous_key
+937
View File
@@ -0,0 +1,937 @@
from __future__ import annotations
import base64
import uuid
from pathlib import Path
from types import SimpleNamespace
import pytest
import app.tasks as task_module
from app.config import get_settings
from app.database import SessionLocal
from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User
from app.services.dify_service import DifyError
from app.services.storage_service import version_dir
def _seed_document_version(
*,
source_filename: str = "policy.docx",
title: str = "policy",
convert_status: str = "queued",
sync_status: str = "unsynced",
markdown_text: str | None = None,
) -> tuple[int, int, int, int]:
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"group-{uuid.uuid4().hex[:8]}", description="Task coverage", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title=title, created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
source_root = version_dir("original", group.id, document.id, 1)
source_root.mkdir(parents=True, exist_ok=True)
source_path = source_root / source_filename
source_path.write_bytes(b"source document")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename=source_filename,
source_ext=Path(source_filename).suffix.lower(),
source_path=str(source_path),
source_sha256=uuid.uuid4().hex,
file_size=source_path.stat().st_size,
uploader_id=admin.id,
convert_status=convert_status,
sync_status=sync_status,
)
db.add(version)
db.commit()
db.refresh(version)
if markdown_text is not None:
markdown_root = version_dir("markdown", group.id, document.id, version.version_no)
markdown_root.mkdir(parents=True, exist_ok=True)
markdown_path = markdown_root / "document.md"
markdown_path.write_text(markdown_text, encoding="utf-8")
version.md_path = str(markdown_path)
db.commit()
return group.id, document.id, version.id, admin.id
finally:
db.close()
def _seed_job(
*,
job_type: str,
group_id: int,
document_id: int,
version_id: int,
created_by_id: int,
) -> str:
db = SessionLocal()
try:
job = Job(
id=str(uuid.uuid4()),
job_type=job_type,
status="queued",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=created_by_id,
payload={},
)
db.add(job)
db.commit()
return job.id
finally:
db.close()
def _seed_document_for_delete(*, with_remote_sync: bool) -> tuple[int, int, int, int, Path, Path, Path]:
settings = get_settings()
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(
name=f"delete-{uuid.uuid4().hex[:8]}",
description="Delete coverage",
created_by_id=admin.id,
department_id=1,
)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="manual", created_by_id=admin.id, is_deleted=True)
db.add(document)
db.commit()
db.refresh(document)
source_root = version_dir("original", group.id, document.id, 1)
markdown_root = version_dir("markdown", group.id, document.id, 1)
assets_root = version_dir("assets", group.id, document.id, 1)
source_root.mkdir(parents=True, exist_ok=True)
markdown_root.mkdir(parents=True, exist_ok=True)
assets_root.mkdir(parents=True, exist_ok=True)
source_path = source_root / "manual.docx"
markdown_path = markdown_root / "document.md"
asset_path = assets_root / "img_001.png"
source_path.write_bytes(b"source")
markdown_path.write_text("# Manual", encoding="utf-8")
asset_path.write_bytes(b"png")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="manual.docx",
source_ext=".docx",
source_path=str(source_path),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
md_public_url="http://testserver/storage/markdown/document.md",
asset_dir=str(assets_root.relative_to(settings.data_root)),
file_size=source_path.stat().st_size,
uploader_id=admin.id,
convert_status="success",
sync_status="synced" if with_remote_sync else "unsynced",
)
db.add(version)
db.commit()
db.refresh(version)
if with_remote_sync:
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-001",
remote_document_id="remote-001",
status="synced",
)
)
db.commit()
return group.id, document.id, version.id, admin.id, source_root, markdown_root, assets_root
finally:
db.close()
def test_convert_job_success_updates_version_and_job(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version()
job_id = _seed_job(
job_type="convert",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
def fake_build_knowledge(source_path, output_dir, config, cache_dir):
generated_dir = output_dir / "generated"
generated_dir.mkdir(parents=True, exist_ok=True)
(generated_dir / "document.md").write_text("# Policy\n\nConverted content", encoding="utf-8")
return [{"status": "success"}]
monkeypatch.setattr(task_module, "build_knowledge", fake_build_knowledge)
task_module.run_convert_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.convert_status == "success"
assert version.sync_status == "unsynced"
assert version.md_path is not None
assert Path(version.md_path).exists()
assert Path(version.md_path).read_text(encoding="utf-8") == "# Policy\n\nConverted content"
assert version.word_count == 4
assert version.warnings_json == [{"message": "embedded_images=0"}]
assert job.status == "success"
assert job.message == "Conversion completed"
assert job.result == {
"md_path": version.md_path,
"md_public_url": version.md_public_url,
"image_count": 0,
}
finally:
db.close()
def test_convert_job_success_rewrites_embedded_images_to_local_asset_urls(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version()
job_id = _seed_job(
job_type="convert",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
def fake_build_knowledge(source_path, output_dir, config, cache_dir):
generated_dir = output_dir / "generated"
generated_dir.mkdir(parents=True, exist_ok=True)
image_bytes = base64.b64encode(b"fake-image").decode("ascii")
markdown = f"# Policy\n\n![image-1](data:image/png;base64,{image_bytes})"
(generated_dir / "document.md").write_text(markdown, encoding="utf-8")
return [{"status": "success"}]
monkeypatch.setattr(task_module, "build_knowledge", fake_build_knowledge)
task_module.run_convert_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
assert version is not None
assert version.asset_dir is not None
assert version.md_path is not None
markdown = Path(version.md_path).read_text(encoding="utf-8")
assert "http://testserver/storage/assets/" in markdown
assert "data:image" not in markdown
finally:
db.close()
def test_convert_job_failure_marks_job_and_version_failed(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version()
job_id = _seed_job(
job_type="convert",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
monkeypatch.setattr(
task_module,
"build_knowledge",
lambda source_path, output_dir, config, cache_dir: [{"status": "failed", "error": "converter exploded"}],
)
with pytest.raises(RuntimeError, match="converter exploded"):
task_module.run_convert_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.convert_status == "failed"
assert version.failed_reason == "converter exploded"
assert job.status == "failed"
assert job.message == "Conversion failed"
assert job.error == "converter exploded"
finally:
db.close()
def test_sync_job_success_creates_sync_record_and_marks_document_synced(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
assert dataset_id == "dataset-001"
assert name == "policy"
assert "Ready for sync" in text
assert indexing_technique == "high_quality"
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
raise AssertionError("update_document_by_text should not be called for a first sync")
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
assert dataset_id == "dataset-001"
assert batch == "batch-001"
return {"indexing_status": "completed"}
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
raise AssertionError("get_document_detail should not be called when batch exists")
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
group = db.query(Group).filter(Group.id == group_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
assert version is not None
assert group is not None
assert job is not None
assert group.dify_dataset_id == "dataset-001"
assert version.sync_status == "synced"
assert len(records) == 1
assert records[0].remote_document_id == "remote-001"
assert records[0].status == "synced"
assert records[0].last_indexing_status == "completed"
assert job.status == "success"
assert job.message == "Dify sync completed"
assert job.result == {
"dataset_id": "dataset-001",
"remote_document_id": "remote-001",
"batch": "batch-001",
"indexing_status": "completed",
}
finally:
db.close()
def test_sync_job_success_without_batch_waits_for_document_completion(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
assert dataset_id == "dataset-001"
assert name == "policy"
return {"document": {"id": "remote-001"}}
def wait_for_document_indexing(self, *, dataset_id: str, document_id: str, timeout_seconds: int = 300) -> dict:
assert dataset_id == "dataset-001"
assert document_id == "remote-001"
return {"indexing_status": "completed"}
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
raise AssertionError("get_document_detail should not be called directly in no-batch mode")
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
record = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).first()
assert version is not None
assert job is not None
assert record is not None
assert version.sync_status == "synced"
assert record.status == "synced"
assert record.batch is None
assert record.last_indexing_status == "completed"
assert job.status == "success"
finally:
db.close()
def test_sync_job_reuses_existing_no_batch_sync_record_and_waits_for_completion(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="syncing",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
db = SessionLocal()
try:
db.add(
DifySyncRecord(
version_id=version_id,
dataset_id="dataset-001",
remote_document_id="remote-existing",
batch=None,
status="syncing",
)
)
db.commit()
finally:
db.close()
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(self, **kwargs) -> dict:
raise AssertionError("create_document_by_text should not be called when an in-flight sync record exists")
def wait_for_document_indexing(self, *, dataset_id: str, document_id: str, timeout_seconds: int = 300) -> dict:
assert dataset_id == "dataset-001"
assert document_id == "remote-existing"
return {"indexing_status": "completed_with_warning"}
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
record = (
db.query(DifySyncRecord)
.filter(DifySyncRecord.version_id == version_id)
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
.first()
)
assert version is not None
assert job is not None
assert record is not None
assert version.sync_status == "synced"
assert record.status == "synced"
assert record.last_indexing_status == "completed_with_warning"
assert job.status == "success"
assert job.result["remote_document_id"] == "remote-existing"
finally:
db.close()
def test_delete_document_job_removes_local_storage_and_remote_dify_document(db_session, monkeypatch):
group_id, document_id, version_id, admin_id, source_root, markdown_root, assets_root = _seed_document_for_delete(
with_remote_sync=True
)
job_id = _seed_job(
job_type="delete",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
db = SessionLocal()
try:
job = db.query(Job).filter(Job.id == job_id).first()
assert job is not None
job.payload = {"delete_dify": True}
db.commit()
finally:
db.close()
delete_calls: list[tuple[str, str]] = []
class FakeDifyService:
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
delete_calls.append((dataset_id, document_id))
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_delete_document_job(job_id, document_id)
db = SessionLocal()
try:
job = db.query(Job).filter(Job.id == job_id).first()
assert job is not None
assert job.status == "success"
assert job.message == "Document delete completed"
assert job.result == {"deleted": True, "delete_dify": True, "remote_document_count": 1}
finally:
db.close()
assert delete_calls == [("dataset-001", "remote-001")]
assert not source_root.exists()
assert not markdown_root.exists()
assert not assets_root.exists()
def test_sync_job_failure_marks_existing_sync_record_failed(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
raise AssertionError("update_document_by_text should not be called for a first sync")
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
raise DifyError("Indexing failed with status=failed")
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
assert dataset_id == "dataset-001"
assert batch == "batch-001"
return [{"indexing_status": "failed", "display_status": "error"}]
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
raise AssertionError("get_document_detail should not be called when batch exists")
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
with pytest.raises(DifyError, match="status=failed"):
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
assert version is not None
assert job is not None
assert version.sync_status == "sync_failed"
assert job.status == "failed"
assert job.message == "Dify sync failed"
assert "status=failed" in job.error
assert len(records) == 1
assert records[0].status == "sync_failed"
assert "status=failed" in records[0].error
assert records[0].last_indexing_status == "failed"
finally:
db.close()
def test_sync_job_keeps_local_asset_urls_when_syncing_to_dify(db_session, monkeypatch):
local_asset_url = (
f"http://testserver/storage/assets/group_{1:04d}/document_{1:06d}/v001/img_001_deadbeef.jpg"
)
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text=f"# Policy\n\n![image-1]({local_asset_url})",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(self, *, dataset_id, name, text, doc_form, indexing_technique):
assert local_asset_url in text
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def wait_for_indexing(self, *, dataset_id, batch, timeout_seconds=300):
return {"indexing_status": "completed"}
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_sync_job(job_id, version_id)
def test_sync_job_recreates_remote_document_when_previous_sync_record_exists(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="sync_failed",
markdown_text="# Policy\n\nReady for resync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
db = SessionLocal()
try:
db.add(
DifySyncRecord(
version_id=version_id,
dataset_id="dataset-001",
remote_document_id="remote-old",
status="sync_failed",
)
)
db.commit()
finally:
db.close()
class FakeDifyService:
def __init__(self):
self.deleted: list[tuple[str, str]] = []
def ensure_dataset(self, **kwargs):
return "dataset-001"
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
self.deleted.append((dataset_id, document_id))
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
assert dataset_id == "dataset-001"
assert name == "policy"
assert "Ready for resync" in text
return {"document": {"id": "remote-new"}, "batch": "batch-new"}
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
raise AssertionError("update_document_by_text should not be called during resync")
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
assert dataset_id == "dataset-001"
assert batch == "batch-new"
return {"indexing_status": "completed"}
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
raise AssertionError("get_document_detail should not be called when batch exists")
service = FakeDifyService()
monkeypatch.setattr(task_module, "DifyService", lambda: service)
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).order_by(DifySyncRecord.id).all()
assert version is not None
assert job is not None
assert version.sync_status == "synced"
assert service.deleted == [("dataset-001", "remote-old")]
assert len(records) == 2
assert records[-1].remote_document_id == "remote-new"
assert records[-1].status == "synced"
assert job.status == "success"
assert job.result == {
"dataset_id": "dataset-001",
"remote_document_id": "remote-new",
"batch": "batch-new",
"indexing_status": "completed",
}
finally:
db.close()
def test_sync_job_retryable_dify_error_requeues_instead_of_failing(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class SettingsStub:
task_execution_mode = "rq"
dify_sync_max_retries = 4
dify_sync_cooldown_seconds = 20
@staticmethod
def dify_sync_retry_delays():
return [15, 30, 60]
class FakeQueue:
def __init__(self):
self.calls: list[tuple[int, str, tuple]] = []
def enqueue_in(self, delay, task_name, *args, **kwargs):
self.calls.append((int(delay.total_seconds()), task_name, args))
return SimpleNamespace(id="rq-retry-1")
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
raise DifyError("FATAL: sorry, too many clients already")
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
return [{"indexing_status": "waiting", "display_status": "queuing"}]
queue = FakeQueue()
cooldowns: list[tuple[str, int]] = []
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
monkeypatch.setattr(task_module, "get_queue", lambda: queue)
monkeypatch.setattr(task_module, "get_settings", lambda: SettingsStub())
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 0)
monkeypatch.setattr(task_module, "set_delay_gate", lambda name, ttl: cooldowns.append((name, ttl)))
task_module.run_sync_job(job_id, version_id)
assert queue.calls == [(15, "app.tasks.run_sync_job", (job_id, version_id))]
assert cooldowns == [(task_module.DIFY_SYNC_COOLDOWN_GATE, 20)]
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
assert version is not None
assert job is not None
assert version.sync_status == "syncing"
assert job.status == "queued"
assert job.queue_job_id == "rq-retry-1"
assert job.payload["sync_retry_count"] == 1
assert job.payload["sync_retry_after_seconds"] == 15
assert "too many clients already" in job.payload["sync_last_error"]
assert job.message == "Dify busy, retrying in 15s (attempt 1/4)."
assert job.error is None
assert len(records) == 1
assert records[0].status == "syncing"
assert "too many clients already" in records[0].error
finally:
db.close()
def test_sync_job_retryable_dify_error_fails_cleanly_in_sync_mode(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class SettingsStub:
task_execution_mode = "sync"
dify_sync_max_retries = 4
dify_sync_cooldown_seconds = 20
@staticmethod
def dify_sync_retry_delays():
return [15, 30, 60]
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
raise DifyError("FATAL: sorry, too many clients already")
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
return [{"indexing_status": "waiting", "display_status": "queuing"}]
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
monkeypatch.setattr(task_module, "get_settings", lambda: SettingsStub())
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 0)
with pytest.raises(DifyError, match="too many clients already"):
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
assert version is not None
assert job is not None
assert version.sync_status == "sync_failed"
assert job.status == "failed"
assert job.queue_job_id is None
assert job.error is not None and "too many clients already" in job.error
assert len(records) == 1
assert records[0].status == "sync_failed"
finally:
db.close()
def test_sync_job_defers_during_dify_cooldown_without_calling_dify(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="syncing",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeQueue:
def __init__(self):
self.calls: list[tuple[int, str, tuple]] = []
def enqueue_in(self, delay, task_name, *args, **kwargs):
self.calls.append((int(delay.total_seconds()), task_name, args))
return SimpleNamespace(id="rq-retry-2")
invoked = {"count": 0}
class FakeDifyService:
def __init__(self):
invoked["count"] += 1
queue = FakeQueue()
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
monkeypatch.setattr(task_module, "get_queue", lambda: queue)
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 45)
task_module.run_sync_job(job_id, version_id)
assert invoked["count"] == 0
assert queue.calls == [(45, "app.tasks.run_sync_job", (job_id, version_id))]
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.sync_status == "syncing"
assert job.status == "queued"
assert job.queue_job_id == "rq-retry-2"
assert job.message == "Dify cooldown active, retrying in 45s."
finally:
db.close()
+660
View File
@@ -0,0 +1,660 @@
from __future__ import annotations
from datetime import date, timedelta
from app.database import SessionLocal
from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, User, UserDepartmentAccess
def _token(client):
response = client.post("/api/auth/login", json={"username": "admin", "password": "admin123456"})
return response.json()["access_token"]
def _headers(client):
return {"Authorization": f"Bearer {_token(client)}"}
def test_duplicate_upload_is_detected(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "quality", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
first = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
assert len(first.json()["created"]) == 1
second = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
assert len(second.json()["duplicates"]) == 1
def test_upload_rejects_more_than_500_files(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "bulk-limit", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", (f"sample-{index}.pdf", b"pdf", "application/pdf")) for index in range(501)]
response = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
assert response.status_code == 400
assert response.json()["detail"] == "Batch upload accepts at most 500 files at a time."
def test_same_title_creates_new_version(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "risk", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
first_file = [("files", ("policy.docx", b"abc", "application/octet-stream"))]
second_file = [("files", ("policy.docx", b"abcd", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=first_file, headers=_headers(client))
client.post("/api/files/upload", data=payload, files=second_file, headers=_headers(client))
db = SessionLocal()
try:
document = db.query(Document).filter(Document.group_id == 1, Document.title == "policy").first()
assert document is not None
versions = db.query(DocumentVersion).filter(DocumentVersion.document_id == document.id).all()
assert len(versions) == 2
finally:
db.close()
def test_group_rename_endpoint(client):
client.post("/api/groups", json={"name": "safety", "description": "", "department_id": 1}, headers=_headers(client))
response = client.patch("/api/groups/1", json={"name": "EHS", "rename_dify": False}, headers=_headers(client))
assert response.status_code == 200
assert response.json()["name"] == "EHS"
def test_group_name_can_repeat_in_different_departments(client):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
department = Department(name="second-dept", description="secondary")
db.add(department)
db.commit()
db.refresh(department)
db.add(UserDepartmentAccess(user_id=admin.id, department_id=department.id))
db.commit()
finally:
db.close()
first = client.post(
"/api/groups",
json={"name": "shared-name", "description": "", "department_id": 1},
headers=_headers(client),
)
assert first.status_code == 200
second = client.post(
"/api/groups",
json={"name": "shared-name", "description": "", "department_id": 2},
headers=_headers(client),
)
assert second.status_code == 200
assert second.json()["department_id"] == 2
def test_group_rename_returns_conflict_within_same_department(client):
first = client.post("/api/groups", json={"name": "dept-a", "description": "", "department_id": 1}, headers=_headers(client))
second = client.post("/api/groups", json={"name": "dept-b", "description": "", "department_id": 1}, headers=_headers(client))
assert first.status_code == 200
assert second.status_code == 200
response = client.patch("/api/groups/2", json={"name": "dept-a", "rename_dify": False}, headers=_headers(client))
assert response.status_code == 409
assert response.json()["detail"] == "Group already exists."
def test_group_delete_endpoint(client):
client.post("/api/groups", json={"name": "archive", "description": "", "department_id": 1}, headers=_headers(client))
response = client.delete("/api/groups/1", headers=_headers(client))
assert response.status_code == 200
listed = client.get("/api/groups", headers=_headers(client))
assert listed.status_code == 200
assert listed.json()["data"] == []
def test_group_delete_with_documents_and_dify(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
deleted = {}
def fake_delete_dataset(self, *, dataset_id: str):
deleted["dataset_id"] = dataset_id
monkeypatch.setattr("app.api.groups.DifyService.delete_dataset", fake_delete_dataset)
client.post("/api/groups", json={"name": "cleanup", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
db = SessionLocal()
try:
group = db.query(Document).filter(Document.group_id == 1).first().group
group.dify_dataset_id = "dataset-123"
job = db.query(Job).filter(Job.group_id == 1).first()
job.status = "success"
db.commit()
finally:
db.close()
response = client.delete("/api/groups/1?delete_dify=true", headers=_headers(client))
assert response.status_code == 200
assert deleted["dataset_id"] == "dataset-123"
db = SessionLocal()
try:
assert db.query(Document).count() == 0
finally:
db.close()
def test_group_delete_rejects_running_jobs(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "active", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
response = client.delete("/api/groups/1", headers=_headers(client))
assert response.status_code == 409
def test_group_list_includes_document_count(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "filled", "description": "", "department_id": 1}, headers=_headers(client))
client.post("/api/groups", json={"name": "empty", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
response = client.get("/api/groups", headers=_headers(client))
assert response.status_code == 200
counts = {item["name"]: item["document_count"] for item in response.json()["data"]}
assert counts["filled"] == 1
assert counts["empty"] == 0
def test_group_dify_diff_reports_local_remote_and_attention(client, monkeypatch):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name="diff-group", description="Compare me", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-123")
db.add(group)
db.commit()
db.refresh(group)
local_only = Document(group_id=group.id, title="local only", created_by_id=admin.id, is_deleted=False)
attention = Document(group_id=group.id, title="attention", created_by_id=admin.id, is_deleted=False)
synced = Document(group_id=group.id, title="matched", created_by_id=admin.id, is_deleted=False)
db.add_all([local_only, attention, synced])
db.commit()
db.refresh(local_only)
db.refresh(attention)
db.refresh(synced)
local_only_version = DocumentVersion(
document_id=local_only.id,
version_no=1,
is_current=True,
source_filename="local only.docx",
source_ext=".docx",
source_path="local-only.docx",
source_sha256="hash-local",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="unsynced",
)
attention_version = DocumentVersion(
document_id=attention.id,
version_no=1,
is_current=True,
source_filename="attention.docx",
source_ext=".docx",
source_path="attention.docx",
source_sha256="hash-attention",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="sync_failed",
)
synced_version = DocumentVersion(
document_id=synced.id,
version_no=1,
is_current=True,
source_filename="matched.docx",
source_ext=".docx",
source_path="matched.docx",
source_sha256="hash-matched",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add_all([local_only_version, attention_version, synced_version])
db.commit()
db.refresh(attention_version)
db.refresh(synced_version)
db.add_all(
[
DifySyncRecord(
version_id=attention_version.id,
dataset_id="dataset-123",
remote_document_id="remote-attention",
status="sync_failed",
),
DifySyncRecord(
version_id=synced_version.id,
dataset_id="dataset-123",
remote_document_id="remote-matched",
status="synced",
),
]
)
db.commit()
finally:
db.close()
class FakeRemote:
def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True):
self.id = document_id
self.name = name
self.indexing_status = indexing_status
self.display_status = display_status
self.enabled = enabled
class FakeDifyService:
def list_documents(self, *, dataset_id: str, limit: int = 100):
assert dataset_id == "dataset-123"
assert limit == 100
return [
FakeRemote("remote-attention", "attention", "indexing"),
FakeRemote("remote-matched", "matched", "completed"),
FakeRemote("remote-only", "remote only", "completed"),
]
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
response = client.get("/api/groups/1/dify-diff", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["summary"] == {"matched": 1, "local_only": 1, "dify_only": 1, "attention": 1}
rows = {row["display_name"]: row for row in payload["rows"]}
assert rows["local only"]["status"] == "local_only"
assert rows["remote only"]["status"] == "dify_only"
assert rows["attention"]["status"] == "attention"
assert rows["matched"]["status"] == "matched"
def test_group_dify_diff_keeps_multiple_remote_documents_with_same_stem(client, monkeypatch):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name="duplicate-stem", description="Compare me", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-stem")
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="policy", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="policy.docx",
source_ext=".docx",
source_path="policy.docx",
source_sha256="hash-policy",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add(version)
db.commit()
db.refresh(version)
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-stem",
remote_document_id="remote-policy-docx",
status="synced",
)
)
db.commit()
finally:
db.close()
class FakeRemote:
def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True):
self.id = document_id
self.name = name
self.indexing_status = indexing_status
self.display_status = display_status
self.enabled = enabled
class FakeDifyService:
def list_documents(self, *, dataset_id: str, limit: int = 100):
assert dataset_id == "dataset-stem"
return [
FakeRemote("remote-policy-docx", "policy.docx", "completed"),
FakeRemote("remote-policy-pdf", "policy.pdf", "completed"),
]
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
response = client.get("/api/groups/1/dify-diff", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["summary"] == {"matched": 1, "local_only": 0, "dify_only": 1, "attention": 0}
assert len(payload["rows"]) == 2
rows = {(row["display_name"], row["status"]) for row in payload["rows"]}
assert ("policy", "matched") in rows
assert ("policy.pdf", "dify_only") in rows
def test_global_dashboard_summary_and_dify_diff(client, monkeypatch):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
blocked_department = Department(name="blocked-global", description="hidden")
db.add(blocked_department)
db.commit()
db.refresh(blocked_department)
linked_group = Group(name="kb-linked", description="", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-linked")
local_only_group = Group(name="kb-local", description="", created_by_id=admin.id, department_id=1)
hidden_group = Group(
name="kb-hidden",
description="",
created_by_id=admin.id,
department_id=blocked_department.id,
dify_dataset_id="dataset-hidden",
)
db.add_all([linked_group, local_only_group, hidden_group])
db.commit()
db.refresh(linked_group)
db.refresh(local_only_group)
db.refresh(hidden_group)
linked_document = Document(group_id=linked_group.id, title="alpha", created_by_id=admin.id, is_deleted=False)
running_document = Document(group_id=local_only_group.id, title="beta", created_by_id=admin.id, is_deleted=False)
hidden_document = Document(group_id=hidden_group.id, title="secret", created_by_id=admin.id, is_deleted=False)
db.add_all([linked_document, running_document, hidden_document])
db.commit()
db.refresh(linked_document)
db.refresh(running_document)
db.refresh(hidden_document)
linked_version = DocumentVersion(
document_id=linked_document.id,
version_no=1,
is_current=True,
source_filename="alpha.docx",
source_ext=".docx",
source_path="alpha.docx",
source_sha256="hash-alpha",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
running_version = DocumentVersion(
document_id=running_document.id,
version_no=1,
is_current=True,
source_filename="beta.docx",
source_ext=".docx",
source_path="beta.docx",
source_sha256="hash-beta",
file_size=1,
uploader_id=admin.id,
convert_status="running",
sync_status="unsynced",
)
hidden_version = DocumentVersion(
document_id=hidden_document.id,
version_no=1,
is_current=True,
source_filename="secret.docx",
source_ext=".docx",
source_path="secret.docx",
source_sha256="hash-secret",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add_all([linked_version, running_version, hidden_version])
db.commit()
db.refresh(linked_version)
db.refresh(hidden_version)
db.add_all(
[
DifySyncRecord(
version_id=linked_version.id,
dataset_id="dataset-linked",
remote_document_id="remote-alpha",
status="synced",
),
DifySyncRecord(
version_id=hidden_version.id,
dataset_id="dataset-hidden",
remote_document_id="remote-secret",
status="synced",
),
]
)
db.commit()
finally:
db.close()
class FakeDataset:
def __init__(self, dataset_id: str, name: str):
self.id = dataset_id
self.name = name
class FakeRemote:
def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True):
self.id = document_id
self.name = name
self.indexing_status = indexing_status
self.display_status = display_status
self.enabled = enabled
class FakeDifyService:
def list_datasets(self):
return [
FakeDataset("dataset-linked", "kb-linked"),
FakeDataset("dataset-hidden", "kb-hidden"),
FakeDataset("dataset-remote", "kb-remote"),
]
def list_documents(self, *, dataset_id: str, limit: int = 100):
if dataset_id == "dataset-linked":
return [FakeRemote("remote-alpha", "alpha", "completed")]
if dataset_id == "dataset-hidden":
return [FakeRemote("remote-secret", "secret", "completed")]
if dataset_id == "dataset-remote":
return [FakeRemote("remote-gamma", "gamma", "completed")]
return []
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
summary_response = client.get("/api/groups/summary", headers=_headers(client))
assert summary_response.status_code == 200
assert summary_response.json() == {
"knowledge_base_count": 2,
"file_count": 2,
"running_count": 1,
}
diff_response = client.get("/api/groups/dify-diff-global", headers=_headers(client))
assert diff_response.status_code == 200
payload = diff_response.json()
assert payload["summary"] == {"matched": 1, "local_only": 1, "dify_only": 0, "attention": 0}
rows = {(row["knowledge_base"]["name"], row["display_name"]): row for row in payload["rows"]}
assert rows[("kb-linked", "alpha")]["status"] == "matched"
assert rows[("kb-local", "beta")]["status"] == "local_only"
assert ("kb-remote", "gamma") not in rows
assert ("kb-hidden", "secret") not in rows
def test_import_dify_document_into_existing_group(client, monkeypatch):
client.post("/api/groups", json={"name": "imports", "description": "", "department_id": 1}, headers=_headers(client))
class FakeSegment:
def __init__(self, content: str, position: int):
self.content = content
self.position = position
class FakeDifyService:
def get_document_detail(self, *, dataset_id: str, document_id: str):
assert dataset_id == "dataset-import"
assert document_id == "remote-1"
return {"name": "policy.docx", "indexing_status": "completed"}
def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100):
assert limit == 100
return [FakeSegment("hello world", 1), FakeSegment("from dify", 2)]
def get_upload_file(self, *, dataset_id: str, document_id: str):
return None
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
response = client.post(
"/api/groups/import-dify-document",
json={
"group_id": 1,
"dataset_id": "dataset-import",
"remote_document_id": "remote-1",
"knowledge_base_name": "imports",
},
headers=_headers(client),
)
assert response.status_code == 200
payload = response.json()
assert payload["group_id"] == 1
assert payload["document"]["title"] == "policy"
assert payload["document"]["current_version"]["sync_status"] == "synced"
assert payload["document"]["current_version"]["convert_status"] == "success"
assert payload["document"]["current_version"]["source_ext"] == ".md"
db = SessionLocal()
try:
group = db.query(Group).filter(Group.id == 1).first()
assert group is not None
assert group.dify_dataset_id == "dataset-import"
sync_record = db.query(DifySyncRecord).first()
assert sync_record is not None
assert sync_record.remote_document_id == "remote-1"
assert sync_record.status == "synced"
finally:
db.close()
def test_import_dify_document_creates_group_for_remote_only_dataset(client, monkeypatch):
class FakeSegment:
def __init__(self, content: str, position: int):
self.content = content
self.position = position
class FakeDifyService:
def get_document_detail(self, *, dataset_id: str, document_id: str):
assert dataset_id == "dataset-remote-only"
return {"name": "remote-only.md", "indexing_status": "completed"}
def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100):
return [FakeSegment("# Remote\n\nbody", 1)]
def get_upload_file(self, *, dataset_id: str, document_id: str):
return None
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
response = client.post(
"/api/groups/import-dify-document",
json={
"dataset_id": "dataset-remote-only",
"remote_document_id": "remote-doc",
"knowledge_base_name": "remote-only-kb",
},
headers=_headers(client),
)
assert response.status_code == 200
payload = response.json()
assert payload["group_name"] == "remote-only-kb"
assert payload["document"]["title"] == "remote-only"
db = SessionLocal()
try:
group = db.query(Group).filter(Group.name == "remote-only-kb").first()
assert group is not None
document = db.query(Document).filter(Document.group_id == group.id, Document.title == "remote-only").first()
assert document is not None
finally:
db.close()
def test_import_dify_document_requires_department_when_admin_has_no_primary_department(client):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin.primary_department_id = None
db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id).delete()
db.commit()
finally:
db.close()
response = client.post(
"/api/groups/import-dify-document",
json={
"dataset_id": "dataset-remote-only",
"remote_document_id": "remote-doc",
"knowledge_base_name": "remote-only-kb",
},
headers=_headers(client),
)
assert response.status_code == 400
assert response.json()["detail"] == "Department is required for Dify import."
def test_group_files_include_uploader_and_date_filter(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "ops", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
baseline = client.get("/api/groups/1/files", headers=_headers(client))
assert baseline.status_code == 200
uploaded_at = baseline.json()["data"][0]["current_version"]["uploaded_at"]
actual_date = uploaded_at.split("T")[0]
tomorrow = (date.fromisoformat(actual_date) + timedelta(days=1)).isoformat()
listed = client.get(
f"/api/groups/1/files?uploaded_from={actual_date}&uploaded_to={actual_date}&file_type=.docx",
headers=_headers(client),
)
assert listed.status_code == 200
row = listed.json()["data"][0]
assert row["current_version"]["uploaded_by"]["username"] == "admin"
future = client.get(f"/api/groups/1/files?uploaded_from={tomorrow}", headers=_headers(client))
assert future.status_code == 200
assert future.json()["data"] == []
+254
View File
@@ -0,0 +1,254 @@
from __future__ import annotations
import json
import uuid
from datetime import timedelta
from app.config import get_settings
from app.database import SessionLocal
from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User
from app.services.watchdog_service import (
local_convert_health_summary,
local_sync_health_summary,
read_watchdog_snapshot,
recover_stale_converts,
recover_stale_syncs,
)
from app.time_utils import utc_now
def _seed_stale_sync_version():
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
group = Group(name=f"watchdog-group-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="watchdog-policy", created_by_id=admin_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="watchdog.docx",
source_ext=".docx",
source_path="/tmp/watchdog.docx",
source_sha256=uuid.uuid4().hex,
file_size=2048,
uploader_id=admin_id,
convert_status="success",
sync_status="syncing",
)
db.add(version)
db.commit()
db.refresh(version)
old_time = utc_now() - timedelta(minutes=20)
job = Job(
id=str(uuid.uuid4()),
job_type="sync",
status="running",
group_id=group.id,
document_id=document.id,
version_id=version.id,
created_by_id=admin_id,
created_at=old_time,
started_at=old_time,
message="Syncing document to Dify",
)
db.add(job)
db.commit()
record = DifySyncRecord(
version_id=version.id,
dataset_id="dataset-watchdog",
remote_document_id="remote-watchdog",
batch="batch-watchdog",
status="syncing",
created_at=old_time,
updated_at=old_time,
)
db.add(record)
db.commit()
return version.id, job.id, record.id
finally:
db.close()
def _seed_stale_convert_version(*, queue_job_id: str | None = "rq-convert-stale", status: str = "queued"):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
group = Group(name=f"convert-watchdog-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="convert-watchdog", created_by_id=admin_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
old_time = utc_now() - timedelta(minutes=20)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="convert-watchdog.docx",
source_ext=".docx",
source_path="/tmp/convert-watchdog.docx",
source_sha256=uuid.uuid4().hex,
file_size=1024,
uploader_id=admin_id,
convert_status=status,
sync_status="unsynced",
uploaded_at=old_time,
)
db.add(version)
db.commit()
db.refresh(version)
job = Job(
id=str(uuid.uuid4()),
job_type="convert",
status=status,
queue_job_id=queue_job_id,
group_id=group.id,
document_id=document.id,
version_id=version.id,
created_by_id=admin_id,
created_at=old_time,
started_at=old_time if status == "running" else None,
message="Converting source document",
)
db.add(job)
db.commit()
return version.id, job.id
finally:
db.close()
def test_recover_stale_syncs_marks_versions_jobs_and_records_failed(db_session):
version_id, job_id, record_id = _seed_stale_sync_version()
db = SessionLocal()
try:
result = recover_stale_syncs(db, timeout_seconds=900)
assert result["recovered_versions"] == 1
assert result["recovered_jobs"] == 1
assert result["recovered_records"] == 1
finally:
db.close()
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
record = db.query(DifySyncRecord).filter(DifySyncRecord.id == record_id).first()
assert version is not None
assert job is not None
assert record is not None
assert version.sync_status == "sync_failed"
assert job.status == "failed"
assert "watchdog timeout" in (job.error or "")
assert record.status == "sync_failed"
assert "watchdog timeout" in (record.error or "")
finally:
db.close()
def test_local_sync_health_summary_reports_stale_candidates(db_session):
_seed_stale_sync_version()
db = SessionLocal()
try:
payload = local_sync_health_summary(db, timeout_seconds=900)
assert payload["syncing_versions"] == 1
assert payload["active_sync_jobs"] == 1
assert payload["stale_candidates"] == 1
assert payload["stale_versions"][0]["remote_document_id"] == "remote-watchdog"
finally:
db.close()
def test_recover_stale_converts_marks_versions_and_jobs_failed_when_queue_job_is_missing(db_session, monkeypatch):
version_id, job_id = _seed_stale_convert_version()
monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set())
db = SessionLocal()
try:
result = recover_stale_converts(db, timeout_seconds=900, orphan_grace_seconds=120)
assert result["recovered_versions"] == 1
assert result["recovered_jobs"] == 1
finally:
db.close()
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.convert_status == "failed"
assert "watchdog" in (version.failed_reason or "")
assert job.status == "failed"
assert "missing from Redis queue" in (job.error or "")
finally:
db.close()
def test_local_convert_health_summary_reports_stale_candidates(db_session, monkeypatch):
_seed_stale_convert_version()
monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set())
db = SessionLocal()
try:
payload = local_convert_health_summary(db, timeout_seconds=900, orphan_grace_seconds=120)
assert payload["pending_versions"] == 1
assert payload["active_convert_jobs"] == 1
assert payload["stale_candidates"] == 1
assert payload["stale_versions"][0]["reason"].startswith("Convert job is missing")
finally:
db.close()
def test_local_convert_health_summary_keeps_live_queue_jobs_out_of_stale_candidates(db_session, monkeypatch):
_seed_stale_convert_version(queue_job_id="rq-convert-live")
monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: {"rq-convert-live"})
db = SessionLocal()
try:
payload = local_convert_health_summary(db, timeout_seconds=900, orphan_grace_seconds=120)
assert payload["pending_versions"] == 1
assert payload["stale_candidates"] == 0
finally:
db.close()
def test_read_watchdog_snapshot_reads_json_from_data_root(db_session):
path = get_settings().data_root / "watchdog" / "dify-health.json"
path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"status": "ok",
"worker": {"concurrency": 2},
"queue_lengths": {"priority_dataset": 0},
}
path.write_text(json.dumps(payload), encoding="utf-8")
loaded = read_watchdog_snapshot()
assert loaded is not None
assert loaded["available"] is True
assert loaded["worker"]["concurrency"] == 2