977 lines
39 KiB
Python
977 lines
39 KiB
Python
import pytest
|
|
import pytest_asyncio
|
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
|
from sqlalchemy.pool import NullPool
|
|
from app.core.config import settings
|
|
from app.features.admin.services.module_builder_service import ModuleBuilderService
|
|
from app.features.admin.builder_schema import (
|
|
SaveCategoryRequest,
|
|
SaveDiseaseRequest,
|
|
SaveFullDiseaseRequest,
|
|
SavePatternRequest,
|
|
ModuleBuilderImportRequest,
|
|
)
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def db_session() -> AsyncSession:
|
|
test_engine = create_async_engine(settings.database_url, poolclass=NullPool)
|
|
session_factory = async_sessionmaker(
|
|
bind=test_engine, class_=AsyncSession, expire_on_commit=False
|
|
)
|
|
async with session_factory() as session:
|
|
yield session
|
|
await test_engine.dispose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_module_builder_category_lifecycle(db_session: AsyncSession):
|
|
service = ModuleBuilderService(db_session)
|
|
mod = "m_test_99"
|
|
cat_code = "cat_test_lifecycle"
|
|
|
|
# Clean up before
|
|
await service.delete_category(mod, cat_code)
|
|
|
|
# 1. Create Category
|
|
cat = await service.save_category(
|
|
mod,
|
|
SaveCategoryRequest(
|
|
category_code=cat_code,
|
|
name="Test Category Lifecycle",
|
|
overview="Initial overview for test category",
|
|
sort_order=1,
|
|
),
|
|
)
|
|
assert cat.category_code == cat_code
|
|
assert cat.name == "Test Category Lifecycle"
|
|
|
|
# 2. List Categories
|
|
cats = await service.get_categories(mod)
|
|
assert any(c.category_code == cat_code for c in cats)
|
|
|
|
# 3. Update Category
|
|
updated = await service.save_category(
|
|
mod,
|
|
SaveCategoryRequest(
|
|
category_code=cat_code,
|
|
name="Updated Category Name",
|
|
overview="Updated overview",
|
|
sort_order=2,
|
|
),
|
|
)
|
|
assert updated.name == "Updated Category Name"
|
|
assert updated.sort_order == 2
|
|
|
|
# 4. Clean up
|
|
deleted = await service.delete_category(mod, cat_code)
|
|
assert deleted is True
|
|
|
|
cats_after = await service.get_categories(mod)
|
|
assert not any(c.category_code == cat_code for c in cats_after)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_module_builder_disease_and_patterns_flow(db_session: AsyncSession):
|
|
service = ModuleBuilderService(db_session)
|
|
mod = "m0042_test"
|
|
cat_code = "diseases_after_childbirth_test"
|
|
dis_code = "abdominal_pain_test"
|
|
|
|
# Cleanup
|
|
await service.delete_category(mod, cat_code)
|
|
|
|
# 1. Create Category
|
|
await service.save_category(
|
|
mod,
|
|
SaveCategoryRequest(
|
|
category_code=cat_code,
|
|
name="Diseases after Childbirth Test",
|
|
overview="Overview of postpartum conditions",
|
|
sort_order=0,
|
|
),
|
|
)
|
|
|
|
# 2. Save Full Disease with Patterns
|
|
full_disease = await service.save_full_disease(
|
|
mod,
|
|
SaveFullDiseaseRequest(
|
|
category_code=cat_code,
|
|
disease_code=dis_code,
|
|
name="Abdominal Pain after Childbirth Test",
|
|
overview="Pathology characterized by deficiency or excess",
|
|
patterns=[
|
|
SavePatternRequest(
|
|
category_code=cat_code,
|
|
disease_code=dis_code,
|
|
pattern_code="blood_deficiency_test",
|
|
name="Blood deficiency",
|
|
description="Dull abdominal pain relieved by pressure",
|
|
clinical_data={
|
|
"clinical_manifestations": [
|
|
"Dull abdominal pain after childbirth",
|
|
"Dizziness",
|
|
"Tiredness",
|
|
],
|
|
"tongue": "Pale and Thin.",
|
|
"pulse": "Choppy.",
|
|
"treatment_principle": "Tonify Qi, nourish Blood, stop pain.",
|
|
"acupuncture": {
|
|
"points": "RN-6, RN-4, ST-36, SP-6, LR-8",
|
|
"method": "All with reinforcing method, moxa is applicable.",
|
|
},
|
|
"explanation": [
|
|
"RN-6 tonifies Qi in general.",
|
|
"RN-4 nourishes Blood.",
|
|
],
|
|
},
|
|
sort_order=0,
|
|
),
|
|
SavePatternRequest(
|
|
category_code=cat_code,
|
|
disease_code=dis_code,
|
|
pattern_code="blood_stasis_test",
|
|
name="Blood Stasis",
|
|
description="Severe fixed stabbing pain",
|
|
clinical_data={
|
|
"clinical_manifestations": [
|
|
"Abdominal pain worse with pressure",
|
|
"Discharge of dark lochia",
|
|
],
|
|
"tongue": "Purple.",
|
|
"pulse": "Deep and Wiry.",
|
|
"treatment_principle": "Invigorate Blood, eliminate stasis.",
|
|
"acupuncture": {
|
|
"points": "SP-4, PC-6, ST-30",
|
|
"method": "Reducing or even method.",
|
|
},
|
|
"explanation": [
|
|
"SP-4 and PC-6 regulate the Penetrating Vessel.",
|
|
],
|
|
},
|
|
sort_order=1,
|
|
),
|
|
],
|
|
),
|
|
)
|
|
|
|
assert full_disease.disease_code == dis_code
|
|
assert len(full_disease.patterns) == 2
|
|
assert full_disease.patterns[0].name == "Blood deficiency"
|
|
assert full_disease.patterns[0].clinical_data["pulse"] == "Choppy."
|
|
assert len(full_disease.patterns[0].clinical_data["clinical_manifestations"]) == 3
|
|
|
|
# 3. Export to JSON
|
|
export_data = await service.export_module_json(mod)
|
|
assert len(export_data.contents) >= 1
|
|
target_cat = next((c for c in export_data.contents if c.code == cat_code), None)
|
|
assert target_cat is not None
|
|
assert target_cat.name == "Diseases after Childbirth Test"
|
|
assert len(target_cat.diseases) == 1
|
|
assert target_cat.diseases[0].code == dis_code
|
|
assert len(target_cat.diseases[0].patterns) == 2
|
|
|
|
# Verify exact structure matches module_builder.json
|
|
pat0 = target_cat.diseases[0].patterns[0]
|
|
assert pat0.code == "blood_deficiency_test"
|
|
assert pat0.acupuncture["points"] == "RN-6, RN-4, ST-36, SP-6, LR-8"
|
|
assert "Dizziness" in pat0.clinical_manifestations
|
|
|
|
# 4. Clean up
|
|
await service.delete_category(mod, cat_code)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_module_builder_api_endpoints(db_session: AsyncSession, admin_headers: dict[str, str], sample_admin):
|
|
from app.main import app
|
|
from app.db.session import get_db_session
|
|
from app.features.admin.deps import get_current_admin
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
async def override_get_db():
|
|
yield db_session
|
|
|
|
app.dependency_overrides[get_db_session] = override_get_db
|
|
app.dependency_overrides[get_current_admin] = lambda: sample_admin
|
|
|
|
try:
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
mod = "m0042_api_test"
|
|
cat_code = "cat_api_test"
|
|
dis_code = "dis_api_test"
|
|
|
|
# 1. Create Category via API
|
|
cat_resp = await client.post(
|
|
f"/api/admin/module-builder/{mod}/categories",
|
|
headers=admin_headers,
|
|
json={
|
|
"category_code": cat_code,
|
|
"name": "API Category Test",
|
|
"overview": "Created via admin API",
|
|
"sort_order": 0,
|
|
},
|
|
)
|
|
assert cat_resp.status_code == 200, cat_resp.text
|
|
assert cat_resp.json()["category_code"] == cat_code
|
|
|
|
# 2. List Categories via API
|
|
list_resp = await client.get(
|
|
f"/api/admin/module-builder/{mod}/categories",
|
|
headers=admin_headers,
|
|
)
|
|
assert list_resp.status_code == 200
|
|
cats = list_resp.json()
|
|
assert any(c["category_code"] == cat_code for c in cats)
|
|
|
|
# 3. Save Full Disease via API
|
|
full_resp = await client.post(
|
|
f"/api/admin/module-builder/{mod}/save-full",
|
|
headers=admin_headers,
|
|
json={
|
|
"category_code": cat_code,
|
|
"disease_code": dis_code,
|
|
"name": "API Disease Test",
|
|
"overview": "Disease saved via API",
|
|
"patterns": [
|
|
{
|
|
"category_code": cat_code,
|
|
"disease_code": dis_code,
|
|
"pattern_code": "api_pat_1",
|
|
"name": "API Pattern 1",
|
|
"description": "Desc 1",
|
|
"clinical_data": {
|
|
"clinical_manifestations": ["Symptom A", "Symptom B"],
|
|
"tongue": "Pale",
|
|
"pulse": "Wiry",
|
|
"treatment_principle": "Tonify Qi",
|
|
"acupuncture": {"points": "RN-6, ST-36", "method": "Reinforcing"},
|
|
"explanation": ["RN-6 tonifies Qi."],
|
|
},
|
|
"sort_order": 0,
|
|
}
|
|
],
|
|
},
|
|
)
|
|
assert full_resp.status_code == 200, full_resp.text
|
|
full_data = full_resp.json()
|
|
assert full_data["disease_code"] == dis_code
|
|
assert len(full_data["patterns"]) == 1
|
|
|
|
# 4. Export JSON via API
|
|
export_resp = await client.get(
|
|
f"/api/admin/module-builder/{mod}/export-json",
|
|
headers=admin_headers,
|
|
)
|
|
assert export_resp.status_code == 200
|
|
exp = export_resp.json()
|
|
assert "contents" in exp
|
|
assert len(exp["contents"]) >= 1
|
|
|
|
# 5. Clean up Category via API
|
|
del_resp = await client.delete(
|
|
f"/api/admin/module-builder/{mod}/categories/{cat_code}",
|
|
headers=admin_headers,
|
|
)
|
|
assert del_resp.status_code == 200
|
|
finally:
|
|
app.dependency_overrides.pop(get_db_session, None)
|
|
app.dependency_overrides.pop(get_current_admin, None)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_module_builder_validations(db_session: AsyncSession):
|
|
from fastapi import HTTPException
|
|
service = ModuleBuilderService(db_session)
|
|
mod = "m_val_test"
|
|
|
|
# 1. Empty category name
|
|
with pytest.raises(HTTPException) as exc1:
|
|
await service.save_category(
|
|
mod,
|
|
SaveCategoryRequest(category_code="valid_code", name=" ")
|
|
)
|
|
assert exc1.value.status_code == 400
|
|
assert "Category name cannot be empty" in exc1.value.detail
|
|
|
|
# 2. Disease under nonexistent category
|
|
with pytest.raises(HTTPException) as exc2:
|
|
await service.save_disease(
|
|
mod,
|
|
SaveDiseaseRequest(category_code="non_existent_cat", disease_code="dis_code", name="Dis Name")
|
|
)
|
|
assert exc2.value.status_code == 404
|
|
assert "does not exist" in exc2.value.detail
|
|
|
|
# 3. Full disease with no patterns
|
|
with pytest.raises(HTTPException) as exc3:
|
|
await service.save_full_disease(
|
|
mod,
|
|
SaveFullDiseaseRequest(
|
|
category_code="cat",
|
|
disease_code="dis",
|
|
name="Dis",
|
|
patterns=[],
|
|
)
|
|
)
|
|
assert exc3.value.status_code == 400
|
|
assert "at least one clinical pattern" in exc3.value.detail
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_builder_modules_api_flow(db_session: AsyncSession, admin_headers: dict[str, str], sample_admin):
|
|
from app.main import app
|
|
from app.db.session import get_db_session
|
|
from app.features.admin.deps import get_current_admin
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
async def override_get_db():
|
|
yield db_session
|
|
|
|
app.dependency_overrides[get_db_session] = override_get_db
|
|
app.dependency_overrides[get_current_admin] = lambda: sample_admin
|
|
|
|
try:
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
# 1. List modules - should include at least m0042
|
|
list_res = await client.get("/api/admin/module-builder/modules", headers=admin_headers)
|
|
assert list_res.status_code == 200, list_res.text
|
|
modules = list_res.json()
|
|
codes = [m["code"] for m in modules]
|
|
assert "m0042" in codes
|
|
|
|
# 2. Create a new module (m0091 Pediatrics Test)
|
|
create_res = await client.post(
|
|
"/api/admin/module-builder/modules",
|
|
headers=admin_headers,
|
|
json={
|
|
"name": "Pediatrics Test",
|
|
"code": "m0091",
|
|
"short_description": "Pediatric disorders test module",
|
|
"description": "Comprehensive TCM pediatrics.",
|
|
"kind": "therapeutic",
|
|
"sort_order": 91000,
|
|
},
|
|
)
|
|
assert create_res.status_code == 201, create_res.text
|
|
created_mod = create_res.json()
|
|
assert created_mod["code"] == "m0091"
|
|
assert created_mod["slug"] == "pediatrics-test"
|
|
assert created_mod["category_count"] == 0
|
|
|
|
# 3. Duplicate code returns 409 Conflict
|
|
dup_res = await client.post(
|
|
"/api/admin/module-builder/modules",
|
|
headers=admin_headers,
|
|
json={"name": "Duplicate Pediatrics", "code": "m0091"},
|
|
)
|
|
assert dup_res.status_code == 409
|
|
assert "already exists" in dup_res.json()["detail"]
|
|
|
|
# 4. Invalid code format returns 422
|
|
inv_res = await client.post(
|
|
"/api/admin/module-builder/modules",
|
|
headers=admin_headers,
|
|
json={"name": "Bad Code Module", "code": "invalid_code_123"},
|
|
)
|
|
assert inv_res.status_code == 422
|
|
|
|
# 5. Get created module
|
|
get_res = await client.get("/api/admin/module-builder/modules/m0091", headers=admin_headers)
|
|
assert get_res.status_code == 200
|
|
assert get_res.json()["name"] == "Pediatrics Test"
|
|
|
|
# 6. Update module
|
|
patch_res = await client.patch(
|
|
"/api/admin/module-builder/modules/m0091",
|
|
headers=admin_headers,
|
|
json={"name": "Pediatric Disorders Updated", "short_description": "Updated short desc"},
|
|
)
|
|
assert patch_res.status_code == 200
|
|
assert patch_res.json()["name"] == "Pediatric Disorders Updated"
|
|
|
|
# 7. Delete created module
|
|
del_res = await client.delete("/api/admin/module-builder/modules/m0091", headers=admin_headers)
|
|
assert del_res.status_code == 200
|
|
assert del_res.json()["status"] == "deleted"
|
|
|
|
# 8. Verify 404 after deletion
|
|
not_found_res = await client.get("/api/admin/module-builder/modules/m0091", headers=admin_headers)
|
|
assert not_found_res.status_code == 404
|
|
finally:
|
|
app.dependency_overrides.pop(get_db_session, None)
|
|
app.dependency_overrides.pop(get_current_admin, None)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_module_content_compiler_full_pipeline(db_session: AsyncSession):
|
|
import json
|
|
import zipfile
|
|
import io
|
|
from app.features.admin.builder_schema import (
|
|
CreateBuilderModuleRequest,
|
|
SaveCategoryRequest,
|
|
SaveFullDiseaseRequest,
|
|
SavePatternRequest,
|
|
)
|
|
from app.features.admin.services.module_builder_service import ModuleBuilderService
|
|
from app.bootstrap.seed_content.validators import (
|
|
validate_definition_document,
|
|
validate_presentation_contracts,
|
|
validate_content_document,
|
|
)
|
|
|
|
service = ModuleBuilderService(db_session)
|
|
mod_code = "m0088"
|
|
|
|
try:
|
|
# 1. Create Module
|
|
await service.create_module(
|
|
CreateBuilderModuleRequest(
|
|
name="Compiler Test Pediatrics",
|
|
code=mod_code,
|
|
short_description="Testing full compiler pipeline",
|
|
kind="therapeutic",
|
|
sort_order=88000,
|
|
)
|
|
)
|
|
|
|
# 2. Add Category
|
|
cat_code = "infant_digestion"
|
|
await service.save_category(
|
|
mod_code,
|
|
SaveCategoryRequest(category_code=cat_code, name="Infant Digestion", sort_order=0),
|
|
)
|
|
|
|
# 3. Add Disease + Patterns
|
|
dis_code = "infantile_colic"
|
|
await service.save_full_disease(
|
|
mod_code,
|
|
SaveFullDiseaseRequest(
|
|
category_code=cat_code,
|
|
disease_code=dis_code,
|
|
name="Infantile Colic",
|
|
overview="Colic symptoms in newborn infants.",
|
|
patterns=[
|
|
SavePatternRequest(
|
|
category_code=cat_code,
|
|
disease_code=dis_code,
|
|
pattern_code="food_stagnation",
|
|
name="Food Stagnation Colic",
|
|
clinical_data={
|
|
"clinical_manifestations": ["Inconsolable crying", "Abdominal distension"],
|
|
"tongue": "Thick white coating",
|
|
"pulse": "Slippery",
|
|
"treatment_principle": "Resolve Food Stagnation, Harmonize Middle Burner",
|
|
"acupuncture": {"points": "ST-36, SP-4, CV-12", "method": "Even method"},
|
|
"explanation": ["ST-36 harmonizes the stomach and relieves spasms."],
|
|
},
|
|
sort_order=0,
|
|
)
|
|
],
|
|
),
|
|
)
|
|
|
|
# 4. Compile Module
|
|
module_obj, compiled_files = await service.compiler.compile_module(mod_code)
|
|
assert module_obj.code == mod_code
|
|
assert "module.json" in compiled_files
|
|
assert "search_facets.json" in compiled_files
|
|
assert "data/list.json" in compiled_files
|
|
assert f"data/{cat_code}/list.json" in compiled_files
|
|
assert f"data/{cat_code}/{dis_code}/list.json" in compiled_files
|
|
assert f"data/{cat_code}/{dis_code}/data.json" in compiled_files
|
|
assert "data/detail_patterns.json" in compiled_files
|
|
|
|
# 5. Validate Root & Category Templates with Seeder Validators
|
|
root_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0001.json"])
|
|
validate_definition_document(root_tpl)
|
|
validate_presentation_contracts(root_tpl)
|
|
|
|
cat_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0002.json"])
|
|
validate_definition_document(cat_tpl)
|
|
validate_presentation_contracts(cat_tpl)
|
|
|
|
dis_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0011.json"])
|
|
validate_definition_document(dis_tpl)
|
|
validate_presentation_contracts(dis_tpl)
|
|
|
|
det_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0005.json"])
|
|
validate_definition_document(det_tpl)
|
|
validate_presentation_contracts(det_tpl)
|
|
det_def_codes = {d["code"] for d in det_tpl["attribute_defs"]}
|
|
det_pres_keys = [
|
|
a["attribute_key"]
|
|
for c in det_tpl["presentation_contracts"]
|
|
for a in c["attributes"]
|
|
]
|
|
assert f"{mod_code}_ct0005.pattern_name" in det_pres_keys
|
|
assert f"{mod_code}_ct0005.name" not in det_pres_keys
|
|
for key in det_pres_keys:
|
|
root_code = key.split(".", 2)[1]
|
|
assert root_code in det_def_codes, f"{key} missing from detail attribute_defs"
|
|
|
|
# 6. Validate Data Documents with Seeder Validators
|
|
validate_content_document(json.loads(compiled_files["data/list.json"]))
|
|
validate_content_document(json.loads(compiled_files[f"data/{cat_code}/list.json"]))
|
|
validate_content_document(json.loads(compiled_files[f"data/{cat_code}/{dis_code}/list.json"]))
|
|
validate_content_document(json.loads(compiled_files["data/detail_patterns.json"]))
|
|
|
|
# 7. Test In-Memory ZIP Generation
|
|
zip_name, zip_bytes = await service.export_bundle_zip(mod_code)
|
|
assert zip_name.endswith(".zip")
|
|
assert len(zip_bytes) > 0
|
|
|
|
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
|
|
namelist = zf.namelist()
|
|
assert f"{mod_code}-compiler-test-pediatrics/module.json" in namelist
|
|
assert f"{mod_code}-compiler-test-pediatrics/data/list.json" in namelist
|
|
assert f"{mod_code}-compiler-test-pediatrics/data/detail_patterns.json" in namelist
|
|
finally:
|
|
try:
|
|
await service.delete_module(mod_code)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_compiler_api_endpoints(db_session: AsyncSession, admin_headers: dict[str, str], sample_admin):
|
|
import io
|
|
import zipfile
|
|
from app.main import app
|
|
from app.db.session import get_db_session
|
|
from app.features.admin.deps import get_current_admin
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
async def override_get_db():
|
|
yield db_session
|
|
|
|
app.dependency_overrides[get_db_session] = override_get_db
|
|
app.dependency_overrides[get_current_admin] = lambda: sample_admin
|
|
|
|
try:
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
mod = "m0089"
|
|
|
|
# 1. Create module
|
|
await client.post(
|
|
"/api/admin/module-builder/modules",
|
|
headers=admin_headers,
|
|
json={"name": "API Export Test", "code": mod},
|
|
)
|
|
|
|
# 2. Add Category
|
|
await client.post(
|
|
f"/api/admin/module-builder/{mod}/categories",
|
|
headers=admin_headers,
|
|
json={"category_code": "cat_export", "name": "Category Export"},
|
|
)
|
|
|
|
# 3. Add Disease with Pattern
|
|
await client.post(
|
|
f"/api/admin/module-builder/{mod}/save-full",
|
|
headers=admin_headers,
|
|
json={
|
|
"category_code": "cat_export",
|
|
"disease_code": "dis_export",
|
|
"name": "Disease Export",
|
|
"patterns": [
|
|
{
|
|
"category_code": "cat_export",
|
|
"disease_code": "dis_export",
|
|
"pattern_code": "pat_export",
|
|
"name": "Pattern Export",
|
|
"clinical_data": {
|
|
"clinical_manifestations": ["Test symptom"],
|
|
"tongue": "Red",
|
|
"pulse": "Rapid",
|
|
"treatment_principle": "Clear heat",
|
|
"acupuncture": {"points": "LI-11", "method": "Reducing"},
|
|
"explanation": ["LI-11 clears heat"],
|
|
},
|
|
}
|
|
],
|
|
},
|
|
)
|
|
|
|
# 4. Export ZIP Bundle
|
|
bundle_res = await client.get(
|
|
f"/api/admin/module-builder/{mod}/export-bundle",
|
|
headers=admin_headers,
|
|
)
|
|
assert bundle_res.status_code == 200
|
|
assert bundle_res.headers["content-type"] == "application/zip"
|
|
assert "attachment; filename=" in bundle_res.headers["content-disposition"]
|
|
|
|
# Inspect zip contents
|
|
with zipfile.ZipFile(io.BytesIO(bundle_res.content)) as zf:
|
|
files = zf.namelist()
|
|
assert any("module.json" in f for f in files)
|
|
assert any("detail_patterns.json" in f for f in files)
|
|
|
|
# Clean up
|
|
await client.delete(f"/api/admin/module-builder/modules/{mod}", headers=admin_headers)
|
|
finally:
|
|
app.dependency_overrides.pop(get_db_session, None)
|
|
app.dependency_overrides.pop(get_current_admin, None)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_compiler_sync_content_repo(db_session: AsyncSession, tmp_path):
|
|
import json
|
|
from pathlib import Path
|
|
from app.features.admin.builder_schema import (
|
|
CreateBuilderModuleRequest,
|
|
SaveCategoryRequest,
|
|
SaveFullDiseaseRequest,
|
|
SavePatternRequest,
|
|
)
|
|
from app.features.admin.services.module_builder_service import ModuleBuilderService
|
|
|
|
service = ModuleBuilderService(db_session)
|
|
mod = "m0087"
|
|
|
|
# Setup mock repo root with config.json
|
|
mock_config = {
|
|
"modules": [
|
|
{
|
|
"name": "Acupuncture Points",
|
|
"code": "m0001",
|
|
"path": "m0001-acupuncture-points",
|
|
"status": "active",
|
|
"sort_order": "10001",
|
|
}
|
|
]
|
|
}
|
|
config_file = tmp_path / "config.json"
|
|
config_file.write_text(json.dumps(mock_config, indent=4), encoding="utf-8")
|
|
|
|
try:
|
|
# Create module
|
|
await service.create_module(
|
|
CreateBuilderModuleRequest(
|
|
name="Repo Sync Test",
|
|
code=mod,
|
|
sort_order=87000,
|
|
)
|
|
)
|
|
await service.save_category(
|
|
mod,
|
|
SaveCategoryRequest(category_code="cat_sync", name="Category Sync"),
|
|
)
|
|
await service.save_full_disease(
|
|
mod,
|
|
SaveFullDiseaseRequest(
|
|
category_code="cat_sync",
|
|
disease_code="dis_sync",
|
|
name="Disease Sync",
|
|
patterns=[
|
|
SavePatternRequest(
|
|
category_code="cat_sync",
|
|
disease_code="dis_sync",
|
|
pattern_code="pat_sync",
|
|
name="Pattern Sync",
|
|
clinical_data={
|
|
"clinical_manifestations": ["Sync test symptom"],
|
|
"tongue": "Pale",
|
|
"pulse": "Weak",
|
|
"treatment_principle": "Sync principle",
|
|
"acupuncture": {"points": "ST-36", "method": "Even"},
|
|
},
|
|
)
|
|
],
|
|
),
|
|
)
|
|
|
|
# Execute sync to tmp repo root
|
|
result = await service.sync_content_repo(mod, repo_root=tmp_path)
|
|
assert result["status"] == "synced"
|
|
assert result["files_written"] > 0
|
|
assert result["config_updated"] is True
|
|
|
|
# Verify files on disk
|
|
target_dir = tmp_path / f"{mod}-repo-sync-test"
|
|
assert (target_dir / "module.json").exists()
|
|
assert (target_dir / "templates" / f"{mod}_ct0001.json").exists()
|
|
assert (target_dir / "templates" / f"{mod}_ct0005.json").exists()
|
|
assert (target_dir / "data" / "list.json").exists()
|
|
assert (target_dir / "data" / "detail_patterns.json").exists()
|
|
|
|
# Verify config.json has updated entry
|
|
updated_cfg = json.loads(config_file.read_text(encoding="utf-8"))
|
|
codes = [m["code"] for m in updated_cfg["modules"]]
|
|
assert mod in codes
|
|
finally:
|
|
try:
|
|
await service.delete_module(mod)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_therapeutic_module_builder_lifecycle_and_safety_api(
|
|
db_session: AsyncSession, admin_headers: dict[str, str], sample_admin
|
|
):
|
|
"""Thoroughly tests the multi-module lifecycle via FastAPI HTTP endpoints:
|
|
|
|
1. Enforcing 'therapeutic' kind and 'module_builder' ownership.
|
|
2. Preventing modification or creation of non-therapeutic or legacy core modules.
|
|
3. Creating, updating, adding clinical content, exporting, and deleting a test module.
|
|
"""
|
|
from app.main import app
|
|
from app.db.session import get_db_session
|
|
from app.features.admin.deps import get_current_admin
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
async def override_get_db():
|
|
yield db_session
|
|
|
|
app.dependency_overrides[get_db_session] = override_get_db
|
|
app.dependency_overrides[get_current_admin] = lambda: sample_admin
|
|
|
|
test_mod_code = "m0049"
|
|
|
|
try:
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
# -------------------------------------------------------------
|
|
# 1. SAFETY CHECKS: Legacy Protection
|
|
# -------------------------------------------------------------
|
|
# A. Attempting to add a category to legacy points module (m0001) -> 403
|
|
resp = await client.post(
|
|
"/api/admin/module-builder/m0001/categories",
|
|
headers=admin_headers,
|
|
json={"category_code": "illegal_cat", "name": "Illegal Points Category"},
|
|
)
|
|
assert resp.status_code == 403, resp.text
|
|
assert "legacy 'point' module and cannot be modified" in resp.json()["detail"]
|
|
|
|
# B. Attempting to save disease to legacy nutrition module (m0031) -> 403
|
|
resp = await client.post(
|
|
"/api/admin/module-builder/m0031/save-full",
|
|
headers=admin_headers,
|
|
json={
|
|
"category_code": "nut_cat",
|
|
"disease_code": "nut_dis",
|
|
"name": "Illegal Nutrition Disease",
|
|
"patterns": [
|
|
{
|
|
"category_code": "nut_cat",
|
|
"disease_code": "nut_dis",
|
|
"pattern_code": "nut_pat",
|
|
"name": "Nut Pattern",
|
|
}
|
|
],
|
|
},
|
|
)
|
|
assert resp.status_code == 403, resp.text
|
|
assert "legacy 'nutrition' module and cannot be modified" in resp.json()["detail"]
|
|
|
|
# C. Attempting to update legacy diagnostics module (m0011) -> 403
|
|
resp = await client.patch(
|
|
"/api/admin/module-builder/modules/m0011",
|
|
headers=admin_headers,
|
|
json={"name": "Hacked Eight Principles"},
|
|
)
|
|
assert resp.status_code == 403, resp.text
|
|
|
|
# D. Attempting to create a non-therapeutic module -> 400
|
|
resp = await client.post(
|
|
"/api/admin/module-builder/modules",
|
|
headers=admin_headers,
|
|
json={
|
|
"name": "Invalid Kind Module",
|
|
"kind": "point",
|
|
},
|
|
)
|
|
assert resp.status_code == 400, resp.text
|
|
assert "therapeutic" in resp.json()["detail"]
|
|
|
|
# E. Attempting to hijack existing legacy code m0001 -> 409
|
|
resp = await client.post(
|
|
"/api/admin/module-builder/modules",
|
|
headers=admin_headers,
|
|
json={
|
|
"name": "Points Override",
|
|
"code": "m0001",
|
|
"kind": "therapeutic",
|
|
},
|
|
)
|
|
assert resp.status_code == 409, resp.text
|
|
assert "conflicts with an existing core Acupedia module" in resp.json()["detail"]
|
|
|
|
# -------------------------------------------------------------
|
|
# 2. CREATE NEW THERAPEUTIC TEST MODULE (m0049)
|
|
# -------------------------------------------------------------
|
|
# Clean up if existing from a previous interrupted run
|
|
await client.delete(
|
|
f"/api/admin/module-builder/modules/{test_mod_code}",
|
|
headers=admin_headers,
|
|
)
|
|
|
|
create_resp = await client.post(
|
|
"/api/admin/module-builder/modules",
|
|
headers=admin_headers,
|
|
json={
|
|
"name": "Pediatric Therapeutics Test",
|
|
"code": test_mod_code,
|
|
"description": "Comprehensive TCM pediatrics and infantile massage therapeutics.",
|
|
"short_description": "Pediatric acupuncture and therapeutics.",
|
|
},
|
|
)
|
|
assert create_resp.status_code == 201, create_resp.text
|
|
mod_data = create_resp.json()
|
|
assert mod_data["code"] == test_mod_code
|
|
assert mod_data["name"] == "Pediatric Therapeutics Test"
|
|
assert mod_data["kind"] == "therapeutic"
|
|
assert mod_data["managed_by"] == "module_builder"
|
|
assert mod_data["slug"] == "pediatric-therapeutics-test"
|
|
assert mod_data["sort_order"] > 40000
|
|
|
|
# -------------------------------------------------------------
|
|
# 3. GET & LIST MODULES
|
|
# -------------------------------------------------------------
|
|
list_resp = await client.get(
|
|
"/api/admin/module-builder/modules",
|
|
headers=admin_headers,
|
|
)
|
|
assert list_resp.status_code == 200
|
|
modules = list_resp.json()
|
|
assert any(m["code"] == test_mod_code for m in modules)
|
|
for m in modules:
|
|
assert m["kind"] == "therapeutic"
|
|
assert m["managed_by"] == "module_builder"
|
|
|
|
get_resp = await client.get(
|
|
f"/api/admin/module-builder/modules/{test_mod_code}",
|
|
headers=admin_headers,
|
|
)
|
|
assert get_resp.status_code == 200
|
|
assert get_resp.json()["code"] == test_mod_code
|
|
|
|
# -------------------------------------------------------------
|
|
# 4. UPDATE MODULE METADATA
|
|
# -------------------------------------------------------------
|
|
patch_resp = await client.patch(
|
|
f"/api/admin/module-builder/modules/{test_mod_code}",
|
|
headers=admin_headers,
|
|
json={
|
|
"name": "Pediatric TCM Clinical Therapeutics",
|
|
"short_description": "Updated short description",
|
|
},
|
|
)
|
|
assert patch_resp.status_code == 200
|
|
updated_mod = patch_resp.json()
|
|
assert updated_mod["name"] == "Pediatric TCM Clinical Therapeutics"
|
|
assert updated_mod["short_description"] == "Updated short description"
|
|
|
|
# -------------------------------------------------------------
|
|
# 5. ADD CATEGORY, DISEASE & PATTERNS TO NEW MODULE
|
|
# -------------------------------------------------------------
|
|
cat_resp = await client.post(
|
|
f"/api/admin/module-builder/{test_mod_code}/categories",
|
|
headers=admin_headers,
|
|
json={
|
|
"category_code": "respiratory_disorders",
|
|
"name": "Respiratory Disorders",
|
|
"overview": "Pediatric respiratory complaints including cough and asthma.",
|
|
"sort_order": 1,
|
|
},
|
|
)
|
|
assert cat_resp.status_code == 200, cat_resp.text
|
|
assert cat_resp.json()["category_code"] == "respiratory_disorders"
|
|
|
|
full_dis_resp = await client.post(
|
|
f"/api/admin/module-builder/{test_mod_code}/save-full",
|
|
headers=admin_headers,
|
|
json={
|
|
"category_code": "respiratory_disorders",
|
|
"disease_code": "pediatric_cough",
|
|
"name": "Pediatric Cough",
|
|
"overview": "Overview of pediatric cough and bronchial irritation.",
|
|
"patterns": [
|
|
{
|
|
"category_code": "respiratory_disorders",
|
|
"disease_code": "pediatric_cough",
|
|
"pattern_code": "wind_heat_cough",
|
|
"name": "Wind-Heat Cough",
|
|
"description": "Acute pediatric cough with yellow phlegm and mild fever.",
|
|
"clinical_data": {
|
|
"clinical_manifestations": ["Barking cough", "Thick yellow sputum", "Thirst"],
|
|
"tongue": "Red with thin yellow coating",
|
|
"pulse": "Floating and rapid",
|
|
"treatment_principle": "Dispel Wind, clear Heat, diffuse Lung Qi.",
|
|
"acupuncture": {
|
|
"points": "LU-7, LI-4, LU-5, BL-13",
|
|
"method": "Reducing or gentle stimulation for pediatric cases",
|
|
},
|
|
"explanation": ["LU-7 and LI-4 release the exterior and expel wind."],
|
|
},
|
|
"sort_order": 0,
|
|
}
|
|
],
|
|
},
|
|
)
|
|
assert full_dis_resp.status_code == 200, full_dis_resp.text
|
|
dis_data = full_dis_resp.json()
|
|
assert dis_data["disease_code"] == "pediatric_cough"
|
|
assert len(dis_data["patterns"]) == 1
|
|
assert dis_data["patterns"][0]["name"] == "Wind-Heat Cough"
|
|
|
|
# Verify counts in module summary
|
|
verify_resp = await client.get(
|
|
f"/api/admin/module-builder/modules/{test_mod_code}",
|
|
headers=admin_headers,
|
|
)
|
|
assert verify_resp.status_code == 200
|
|
summary = verify_resp.json()
|
|
assert summary["category_count"] == 1
|
|
assert summary["disease_count"] == 1
|
|
assert summary["pattern_count"] == 1
|
|
|
|
# -------------------------------------------------------------
|
|
# 6. EXPORT ARTIFACTS
|
|
# -------------------------------------------------------------
|
|
exp_json_resp = await client.get(
|
|
f"/api/admin/module-builder/{test_mod_code}/export-json",
|
|
headers=admin_headers,
|
|
)
|
|
assert exp_json_resp.status_code == 200
|
|
exp_doc = exp_json_resp.json()
|
|
assert len(exp_doc["contents"]) == 1
|
|
assert exp_doc["contents"][0]["code"] == "respiratory_disorders"
|
|
|
|
exp_bundle_resp = await client.get(
|
|
f"/api/admin/module-builder/{test_mod_code}/export-bundle",
|
|
headers=admin_headers,
|
|
)
|
|
assert exp_bundle_resp.status_code == 200
|
|
assert exp_bundle_resp.headers["content-type"] == "application/zip"
|
|
assert len(exp_bundle_resp.content) > 500
|
|
|
|
# -------------------------------------------------------------
|
|
# 7. DELETE TEST MODULE
|
|
# -------------------------------------------------------------
|
|
del_resp = await client.delete(
|
|
f"/api/admin/module-builder/modules/{test_mod_code}",
|
|
headers=admin_headers,
|
|
)
|
|
assert del_resp.status_code == 200
|
|
assert del_resp.json()["status"] == "deleted"
|
|
|
|
# Verify 404 after deletion
|
|
get_deleted = await client.get(
|
|
f"/api/admin/module-builder/modules/{test_mod_code}",
|
|
headers=admin_headers,
|
|
)
|
|
assert get_deleted.status_code == 404
|
|
finally:
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
|
|
|
|
|