import json import unittest from fastapi import HTTPException from fastapi.testclient import TestClient from app.api.templates import get_audit_log_service, get_template_service, require_current_user from app.main import app class StubAuditLogService: def __init__(self): self.events = [] def record_event(self, **kwargs): self.events.append(kwargs) return kwargs class StubTemplateService: @staticmethod def _parse_variables(variables_json): return json.loads(variables_json) if variables_json else [] def list_templates(self, current_user, page, page_size, contract_type, document_type_code=None, template_category=None, industry_category=None): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") return { "items": [ { "id": "tpl-123", "name": "Employment Template", "contract_type": contract_type or "labor", "document_type_code": document_type_code or "labor_contract", "template_code": "TPL-LABOR-CONTRACT-001", "template_category": template_category or "employment-hr", "industry_category": industry_category or "general-enterprise", "description": "Standard employment template", "content": "Clause one", "variables": [{"name": "employee_name", "label": "Employee Name"}], "enabled": True, "published_at": None, "published_by": None, "latest_governance_asset_id": None, "current_version_label": "v1.2", "latest_change_summary": "Add probation clause", "latest_version_created_at": "2026-04-17T00:00:00+00:00", "version_count": 3, "created_by": "user-admin", "updated_by": "user-admin", "created_at": "2026-04-16T00:00:00+00:00", "updated_at": "2026-04-16T00:00:00+00:00", } ], "page": page, "page_size": page_size, "total": 1, } def get_template_versions(self, current_user, template_id): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") return { "template_id": template_id, "current_version_label": "v1.2", "version_count": 3, "items": [ { "id": "tplver-003", "template_id": template_id, "version_label": "v1.2", "change_summary": "Add probation clause", "name": "Employment Template", "contract_type": "labor", "document_type_code": "labor_contract", "template_code": "TPL-LABOR-CONTRACT-001", "template_category": "employment-hr", "industry_category": "general-enterprise", "description": "Standard employment template", "content": "Clause one", "variables": [{"name": "employee_name", "label": "Employee Name"}], "is_current": True, "created_by": "user-admin", "created_by_name": "Admin", "created_at": "2026-04-17T00:00:00+00:00", } ], } def create_template( self, current_user, name, contract_type, description, content, variables_json, enabled, change_summary, template_code=None, document_type_code=None, template_category=None, industry_category=None, ): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") return { "id": "tpl-123", "name": name, "contract_type": contract_type, "document_type_code": document_type_code or "procurement_goods", "template_code": template_code or "TPL-PROCUREMENT-DEMO-001", "template_category": template_category or "general-business", "industry_category": industry_category or "general-enterprise", "description": description, "content": content, "variables": self._parse_variables(variables_json), "enabled": enabled, "published_at": None, "published_by": None, "latest_governance_asset_id": None, "current_version_label": "v1.0", "latest_change_summary": change_summary or "Initial template version", "latest_version_created_at": "2026-04-16T00:00:00+00:00", "version_count": 1, "created_by": current_user["id"], "updated_by": current_user["id"], "created_at": "2026-04-16T00:00:00+00:00", "updated_at": "2026-04-16T00:00:00+00:00", } def update_template( self, current_user, template_id, name, contract_type, description, content, variables_json, enabled, change_summary, template_code=None, document_type_code=None, template_category=None, industry_category=None, ): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") return { "id": template_id, "name": name, "contract_type": contract_type, "document_type_code": document_type_code or "procurement_goods", "template_code": template_code or "TPL-PROCUREMENT-DEMO-001", "template_category": template_category or "general-business", "industry_category": industry_category or "general-enterprise", "description": description, "content": content, "variables": self._parse_variables(variables_json), "enabled": enabled, "published_at": None, "published_by": None, "latest_governance_asset_id": None, "current_version_label": "v1.1", "latest_change_summary": change_summary or "v1.1 template update", "latest_version_created_at": "2026-04-16T00:00:00+00:00", "version_count": 2, "created_by": current_user["id"], "updated_by": current_user["id"], "created_at": "2026-04-16T00:00:00+00:00", "updated_at": "2026-04-16T00:00:00+00:00", } def seed_default_templates(self, current_user): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") return { "created": [], "existing": [], "created_count": 3, "existing_count": 0, "total": 3, "template_names": [], } def publish_template(self, current_user, template_id): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") return { "id": template_id, "name": "Employment Template", "contract_type": "labor", "document_type_code": "labor_contract", "template_code": "TPL-LABOR-CONTRACT-001", "template_category": "employment-hr", "industry_category": "general-enterprise", "description": "Standard employment template", "content": "Clause one", "variables": [{"name": "employee_name", "label": "Employee Name"}], "enabled": True, "published_at": "2026-05-13T08:00:00+00:00", "published_by": current_user["id"], "latest_governance_asset_id": "govast-tpl-labor-contract-001", "current_version_label": "v1.2", "latest_change_summary": "Add probation clause", "latest_version_created_at": "2026-04-17T00:00:00+00:00", "version_count": 3, "created_by": "user-admin", "updated_by": current_user["id"], "created_at": "2026-04-16T00:00:00+00:00", "updated_at": "2026-05-13T08:00:00+00:00", } def unpublish_template(self, current_user, template_id): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") result = self.publish_template(current_user, template_id) result["enabled"] = False result["published_at"] = None result["published_by"] = None result["latest_governance_asset_id"] = None return result def rollback_template(self, current_user, template_id, target_version_label, change_summary=None): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") result = self.unpublish_template(current_user, template_id) result["current_version_label"] = "v1.3" result["latest_change_summary"] = change_summary or f"Rollback to {target_version_label}" return result def delete_template(self, current_user, template_id): if current_user["role"] != "admin": raise HTTPException(status_code=403, detail="forbidden") return { "id": template_id, "name": "Employment Template", "contract_type": "labor", "enabled": True, "variables": [], } class TemplatesApiTestCase(unittest.TestCase): def setUp(self): self.audit_log_service = StubAuditLogService() app.dependency_overrides[get_template_service] = lambda: StubTemplateService() app.dependency_overrides[get_audit_log_service] = lambda: self.audit_log_service self.client = TestClient(app) def tearDown(self): app.dependency_overrides.clear() def test_admin_can_list_templates(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.get("/api/v1/templates", params={"contract_type": "labor"}) self.assertEqual(response.status_code, 200) payload = response.json()["data"]["items"][0] self.assertEqual(payload["name"], "Employment Template") self.assertEqual(payload["contract_type"], "labor") self.assertEqual(payload["document_type_code"], "labor_contract") self.assertEqual(payload["template_code"], "TPL-LABOR-CONTRACT-001") self.assertEqual(payload["template_category"], "employment-hr") self.assertEqual(payload["industry_category"], "general-enterprise") self.assertEqual(payload["current_version_label"], "v1.2") def test_admin_can_filter_templates_by_template_category(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.get("/api/v1/templates", params={"template_category": "employment-hr"}) self.assertEqual(response.status_code, 200) payload = response.json()["data"]["items"][0] self.assertEqual(payload["template_category"], "employment-hr") def test_admin_can_filter_templates_by_document_type_code(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.get("/api/v1/templates", params={"document_type_code": "labor_contract"}) self.assertEqual(response.status_code, 200) payload = response.json()["data"]["items"][0] self.assertEqual(payload["document_type_code"], "labor_contract") def test_admin_can_list_template_versions(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.get("/api/v1/templates/tpl-123/versions") self.assertEqual(response.status_code, 200) body = response.json()["data"] self.assertEqual(body["current_version_label"], "v1.2") self.assertEqual(body["version_count"], 3) self.assertEqual(body["items"][0]["version_label"], "v1.2") def test_admin_can_create_template(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.post( "/api/v1/templates", data={ "name": "Procurement Template", "contract_type": "procurement", "document_type_code": "procurement_goods", "template_category": "procurement-supply", "industry_category": "general-enterprise", "description": "Standard procurement template", "content": "Procurement scope", "variables_json": '[{"name":"supplier_name"}]', "enabled": "true", "change_summary": "Initial version", }, ) self.assertEqual(response.status_code, 200) body = response.json()["data"] self.assertEqual(body["name"], "Procurement Template") self.assertEqual(body["template_category"], "procurement-supply") self.assertEqual(body["industry_category"], "general-enterprise") self.assertEqual(body["current_version_label"], "v1.0") self.assertEqual(self.audit_log_service.events[0]["action"], "create_template") self.assertEqual( self.audit_log_service.events[0]["detail_json"], { "name": "Procurement Template", "template_code": "TPL-PROCUREMENT-DEMO-001", "contract_type": "procurement", "document_type_code": "procurement_goods", "template_category": "procurement-supply", "industry_category": "general-enterprise", "enabled": True, "variable_count": 1, "current_version_label": "v1.0", "latest_change_summary": "Initial version", }, ) def test_admin_can_update_template(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.put( "/api/v1/templates/tpl-123", data={ "name": "Procurement Template Updated", "contract_type": "procurement", "document_type_code": "procurement_goods", "template_category": "procurement-supply", "industry_category": "general-enterprise", "description": "Updated description", "content": "Payment arrangement", "variables_json": '[{"name":"supplier_name"}]', "enabled": "false", "change_summary": "Add payment clause", }, ) self.assertEqual(response.status_code, 200) body = response.json()["data"] self.assertEqual(body["id"], "tpl-123") self.assertFalse(body["enabled"]) self.assertEqual(body["template_category"], "procurement-supply") self.assertEqual(body["industry_category"], "general-enterprise") self.assertEqual(body["current_version_label"], "v1.1") self.assertEqual(self.audit_log_service.events[0]["action"], "update_template") self.assertEqual( self.audit_log_service.events[0]["detail_json"], { "name": "Procurement Template Updated", "template_code": "TPL-PROCUREMENT-DEMO-001", "contract_type": "procurement", "document_type_code": "procurement_goods", "template_category": "procurement-supply", "industry_category": "general-enterprise", "enabled": False, "variable_count": 1, "current_version_label": "v1.1", "latest_change_summary": "Add payment clause", }, ) def test_admin_can_submit_multiple_variables(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.put( "/api/v1/templates/tpl-123", data={ "name": "Procurement Template Updated", "contract_type": "procurement", "template_category": "procurement-supply", "industry_category": "general-enterprise", "description": "Updated description", "content": "Payment arrangement", "variables_json": '[{"name":"supplier_name","label":"Supplier Name"},{"name":"contract_amount","label":"Contract Amount"}]', "enabled": "true", "change_summary": "Add amount variable", }, ) self.assertEqual(response.status_code, 200) body = response.json()["data"] self.assertEqual(body["variables"][1]["name"], "contract_amount") self.assertEqual(self.audit_log_service.events[0]["action"], "update_template") def test_admin_can_seed_default_templates(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.post("/api/v1/templates/seed-defaults") self.assertEqual(response.status_code, 200) body = response.json()["data"] self.assertEqual(body["total"], 3) self.assertEqual(self.audit_log_service.events[0]["action"], "seed_default_templates") self.assertEqual( self.audit_log_service.events[0]["detail_json"], { "created_count": 3, "existing_count": 0, "total": 3, "template_names": [], }, ) def test_admin_can_delete_template(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } response = self.client.delete("/api/v1/templates/tpl-123") self.assertEqual(response.status_code, 204) self.assertEqual(self.audit_log_service.events[0]["action"], "delete_template") self.assertEqual( self.audit_log_service.events[0]["detail_json"], { "name": "Employment Template", "contract_type": "labor", "enabled": True, "variable_count": 0, }, ) def test_admin_can_publish_unpublish_and_rollback_template(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-admin", "tenant_id": "tenant-demo-001", "role": "admin", } publish_response = self.client.post("/api/v1/templates/tpl-123/publish") unpublish_response = self.client.post("/api/v1/templates/tpl-123/unpublish") rollback_response = self.client.post("/api/v1/templates/tpl-123/rollback", data={"target_version_label": "v1.1"}) self.assertEqual(publish_response.status_code, 200) self.assertEqual(unpublish_response.status_code, 200) self.assertEqual(rollback_response.status_code, 200) self.assertEqual(publish_response.json()["data"]["published_by"], "user-admin") self.assertEqual(unpublish_response.json()["data"]["published_at"], None) self.assertEqual(rollback_response.json()["data"]["current_version_label"], "v1.3") self.assertEqual(self.audit_log_service.events[-3]["action"], "publish_template") self.assertEqual(self.audit_log_service.events[-2]["action"], "unpublish_template") self.assertEqual(self.audit_log_service.events[-1]["action"], "rollback_template") def test_member_cannot_access_templates(self): app.dependency_overrides[require_current_user] = lambda: { "id": "user-member", "tenant_id": "tenant-demo-001", "role": "member", } response = self.client.get("/api/v1/templates") self.assertEqual(response.status_code, 403) self.assertEqual(response.json()["message"], "forbidden") self.assertEqual(self.audit_log_service.events, []) if __name__ == "__main__": unittest.main()