chore: initialize GSREA website project

This commit is contained in:
zlwu committed 2026-10-30 11:05:55 +08:00
commit d3c5461de5
1842 files changed
+246140

No files matched your search

+226
View File
@@ -0,0 +1,226 @@
"""栏目文章三类:工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_column_category(client, staff: dict[str, str], category: str) -> None:
listed = client.get(f"/api/admin/about/articles/{category}", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def test_column_articles_publish_filter_and_placeholders(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
for category in ("work_briefs", "annual_reports", "qualifications"):
_clear_column_category(client, staff, category)
empty_briefs = client.get("/api/site/about/articles/work_briefs")
assert empty_briefs.status_code == 200, empty_briefs.text
assert "暂无工作简报" in empty_briefs.text
assert "暂无年度报告或工作计划" in client.get("/api/site/about/articles/annual_reports").text
assert "暂无资质与荣誉" in client.get("/api/site/about/articles/qualifications").text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("批复扫描件.pdf", b"%PDF-1.4\nscan", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
report = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "annual_reports",
"title": "2025年协会工作报告",
"publishedAt": "2026-01-15T08:00:00",
"published": True,
"bodyHtml": "<p>公开公示版</p><script>alert(1)</script>",
"attachmentFileIds": [],
},
)
assert report.status_code == 200, report.text
article_ids.append(report.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "annual_reports",
"title": "内部财务稿",
"publishedAt": "2026-01-16T08:00:00",
"published": False,
"bodyHtml": "<p>内部财务稿</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
honor = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "qualifications",
"title": "主管单位批复文件",
"publishedAt": "2024-03-01T08:00:00",
"published": True,
"bodyHtml": "<p>批复摘要</p>",
"attachmentFileIds": [file_ids[0]],
},
)
assert honor.status_code == 200, honor.text
article_ids.append(honor.json()["id"])
reports = client.get("/api/site/about/articles/annual_reports")
assert reports.status_code == 200, reports.text
assert "2025年协会工作报告" in reports.text
assert "内部财务稿" not in reports.text
assert "暂无年度报告或工作计划" not in reports.text
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
body = detail.json()["bodyHtml"].lower()
assert "公开公示版" in detail.json()["bodyHtml"]
assert "script" not in body
assert "alert" not in body
hidden = client.get(f"/api/site/home/articles/{article_ids[1]}")
assert hidden.status_code == 404
honors = client.get("/api/site/about/articles/qualifications")
assert honors.status_code == 200, honors.text
assert "主管单位批复文件" in honors.text
honor_detail = client.get(f"/api/site/home/articles/{article_ids[2]}")
assert honor_detail.status_code == 200, honor_detail.text
assert [item["filename"] for item in honor_detail.json()["attachments"]] == ["批复扫描件.pdf"]
home = client.get("/api/site/home")
assert home.status_code == 200, home.text
home_json = home.json()
assert "annual_reports" not in home_json
assert "work_briefs" not in home_json
assert "qualifications" not in home_json
assert "2025年协会工作报告" not in home.text
editor = client.get("/api/admin/home", headers=staff)
assert editor.status_code == 200, editor.text
categories = {item["category"] for item in editor.json()["articles"]}
assert "annual_reports" not in categories
assert "work_briefs" not in categories
assert "qualifications" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "work_briefs",
"title": "会员不得发布",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员不得发布" not in client.get("/api/site/about/articles/work_briefs").text
assert "暂无工作简报" in client.get("/api/site/about/articles/work_briefs").text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
def test_column_articles_public_pagination(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
try:
_clear_column_category(client, staff, "work_briefs")
for index in range(11):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "work_briefs",
"title": f"简报分页样例-{index:02d}",
"publishedAt": f"2026-02-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>简报分页样例-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/work_briefs?current=1&size=10")
assert page1.status_code == 200, page1.text
body1 = page1.json()
assert body1["total"] == 11
assert body1["current"] == 1
assert body1["size"] == 10
assert len(body1["items"]) == 10
assert body1["items"][0]["title"] == "简报分页样例-10"
page2 = client.get("/api/site/about/articles/work_briefs?current=2&size=10")
assert page2.status_code == 200, page2.text
body2 = page2.json()
assert body2["total"] == 11
assert body2["current"] == 2
assert len(body2["items"]) == 1
assert body2["items"][0]["title"] == "简报分页样例-00"
size20 = client.get("/api/site/about/articles/work_briefs?current=1&size=20")
assert size20.status_code == 200, size20.text
assert size20.json()["size"] == 20
assert len(size20.json()["items"]) == 11
bad_size = client.get("/api/site/about/articles/work_briefs?current=1&size=15")
assert bad_size.status_code == 200, bad_size.text
assert bad_size.json()["size"] == 10
assert len(bad_size.json()["items"]) == 10
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
+148
View File
@@ -0,0 +1,148 @@
"""专家委员会:工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def test_expert_committees_list_detail_delete_and_placeholder(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
ids: list[int] = []
file_id = None
try:
empty = client.get("/api/site/about/experts")
assert empty.status_code == 200, empty.text
assert "暂无专家委员会信息" in empty.text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("专家名录.pdf", b"%PDF-1.4\nexperts", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_id = pdf.json()["id"]
first = client.post(
"/api/admin/about/experts",
headers=staff,
json={
"name": "房地产估价专家委员会",
"bodyHtml": "<p>估价技术咨询</p><script>alert(1)</script>",
"sortOrder": 1,
"published": True,
"attachmentFileIds": [file_id],
},
)
assert first.status_code == 200, first.text
ids.append(first.json()["id"])
second = client.post(
"/api/admin/about/experts",
headers=staff,
json={
"name": "行业自律专家委员会",
"bodyHtml": "<p>自律意见</p>",
"sortOrder": 2,
"published": True,
"attachmentFileIds": [],
},
)
assert second.status_code == 200, second.text
ids.append(second.json()["id"])
draft = client.post(
"/api/admin/about/experts",
headers=staff,
json={
"name": "内部筹备组",
"bodyHtml": "<p>内部</p>",
"sortOrder": 0,
"published": False,
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
ids.append(draft.json()["id"])
listing = client.get("/api/site/about/experts")
assert listing.status_code == 200, listing.text
names = [item["name"] for item in listing.json()["items"]]
assert names == ["房地产估价专家委员会", "行业自律专家委员会"]
assert "内部筹备组" not in listing.text
detail = client.get(f"/api/site/about/experts/{ids[0]}")
assert detail.status_code == 200, detail.text
assert "估价技术咨询" in detail.json()["bodyHtml"]
lowered = detail.json()["bodyHtml"].lower()
assert "script" not in lowered
assert "alert" not in lowered
assert [item["filename"] for item in detail.json()["attachments"]] == ["专家名录.pdf"]
hidden = client.get(f"/api/site/about/experts/{ids[2]}")
assert hidden.status_code == 404
deleted = client.delete(f"/api/admin/about/experts/{ids[1]}", headers=staff)
assert deleted.status_code == 200, deleted.text
ids.remove(ids[1])
after = client.get("/api/site/about/experts")
assert "行业自律专家委员会" not in after.text
assert "房地产估价专家委员会" in after.text
rejected = client.post(
"/api/admin/about/experts",
headers=_headers("member"),
json={
"name": "会员委员会",
"bodyHtml": "<p>x</p>",
"sortOrder": 9,
"published": True,
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员委员会" not in client.get("/api/site/about/experts").text
finally:
for expert_id in list(ids):
client.delete(f"/api/admin/about/experts/{expert_id}", headers=staff)
leftover = client.get("/api/site/about/experts")
# clean any published leftovers from failed runs
admin_list = client.get("/api/admin/about/experts", headers=staff)
if admin_list.status_code == 200:
for item in admin_list.json().get("items", []):
client.delete(f"/api/admin/about/experts/{item['id']}", headers=staff)
assert "暂无专家委员会信息" in client.get("/api/site/about/experts").text
if file_id is not None:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+188
View File
@@ -0,0 +1,188 @@
"""单篇页:协会简介等。工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def test_association_intro_page_publish_filter_and_placeholder(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
file_id = None
try:
before = client.get("/api/site/about/pages/intro")
assert before.status_code == 200, before.text
assert "协会简介整理中" in before.text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("协会章程.pdf", b"%PDF-1.4\ncharter", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_id = pdf.json()["id"]
saved = client.put(
"/api/admin/about/pages/intro",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>服务会员与规范执业</p><script>alert(1)</script>",
"attachmentFileIds": [file_id],
},
)
assert saved.status_code == 200, saved.text
public = client.get("/api/site/about/pages/intro")
assert public.status_code == 200, public.text
data = public.json()
assert "服务会员与规范执业" in data["bodyHtml"]
lowered = data["bodyHtml"].lower()
assert "script" not in lowered
assert "alert" not in lowered
assert [item["filename"] for item in data["attachments"]] == ["协会章程.pdf"]
assert "协会简介整理中" not in public.text
emptied = client.put(
"/api/admin/about/pages/intro",
headers=staff,
json={"published": True, "bodyHtml": "", "attachmentFileIds": []},
)
assert emptied.status_code == 200, emptied.text
empty_public = client.get("/api/site/about/pages/intro")
assert empty_public.status_code == 200, empty_public.text
assert "协会简介整理中" in empty_public.text
published_again = client.put(
"/api/admin/about/pages/intro",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>服务会员与规范执业</p>",
"attachmentFileIds": [file_id],
},
)
assert published_again.status_code == 200, published_again.text
before_member = client.get("/api/site/about/pages/intro").json()
rejected = client.put(
"/api/admin/about/pages/intro",
headers=_headers("member"),
json={"published": True, "bodyHtml": "<p>会员篡改</p>", "attachmentFileIds": []},
)
assert rejected.status_code in (401, 403)
after_member = client.get("/api/site/about/pages/intro")
assert after_member.status_code == 200
assert after_member.json()["bodyHtml"] == before_member["bodyHtml"]
assert "会员篡改" not in after_member.text
finally:
client.put(
"/api/admin/about/pages/intro",
headers=staff,
json={"published": False, "bodyHtml": "", "attachmentFileIds": []},
)
if file_id is not None:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
def test_org_structure_page_unpublished_placeholder(client):
staff = _headers("staff")
client.put(
"/api/admin/about/pages/org",
headers=staff,
json={"published": False, "bodyHtml": "<p>草稿架构</p>", "attachmentFileIds": []},
)
public = client.get("/api/site/about/pages/org")
assert public.status_code == 200, public.text
assert "组织机构整理中" in public.text
assert "草稿架构" not in public.text
rejected = client.put(
"/api/admin/about/pages/org",
headers=_headers("member"),
json={"published": True, "bodyHtml": "<p>会员</p>", "attachmentFileIds": []},
)
assert rejected.status_code in (401, 403)
def test_contact_cooperation_page_without_forms(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
file_id = None
try:
unpublished = client.get("/api/site/about/pages/contact")
# reset first
client.put(
"/api/admin/about/pages/contact",
headers=staff,
json={"published": False, "bodyHtml": "", "attachmentFileIds": []},
)
unpublished = client.get("/api/site/about/pages/contact")
assert "联系与合作信息整理中" in unpublished.text
doc = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("入会申请表.docx", b"PK\x03\x04join", "application/octet-stream")},
)
assert doc.status_code == 200, doc.text
file_id = doc.json()["id"]
saved = client.put(
"/api/admin/about/pages/contact",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>来访请先电话预约</p>",
"attachmentFileIds": [file_id],
},
)
assert saved.status_code == 200, saved.text
public = client.get("/api/site/about/pages/contact")
assert public.status_code == 200, public.text
data = public.json()
assert "来访请先电话预约" in data["bodyHtml"]
assert [item["filename"] for item in data["attachments"]] == ["入会申请表.docx"]
assert "formFields" not in data
assert "signupUrl" not in data
assert client.post("/api/site/about/pages/contact/intent", json={}).status_code == 404
assert client.post("/api/site/about/pages/contact/join", json={}).status_code == 404
finally:
client.put(
"/api/admin/about/pages/contact",
headers=staff,
json={"published": False, "bodyHtml": "", "attachmentFileIds": []},
)
if file_id is not None:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+230
View File
@@ -0,0 +1,230 @@
"""专项估价指南:分类筛选、占位、分页、未发布不可见。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_guides(client, staff: dict[str, str]) -> None:
listed = client.get("/api/admin/about/articles/appraisal_guides", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def test_appraisal_guides_kind_filter_placeholder_and_pagination(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
_clear_guides(client, staff)
empty = client.get("/api/site/about/articles/appraisal_guides")
assert empty.status_code == 200, empty.text
assert "暂无估价指南" in empty.text
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("住宅估价流程.pdf", b"%PDF-1.4\nguide", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
missing_kind = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"title": "缺分类指南",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert missing_kind.status_code == 400
residential = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"kind": "residential",
"title": "住宅估价服务指南",
"publishedAt": "2025-06-01T08:00:00",
"published": True,
"bodyHtml": "<p>住宅流程</p><script>alert(1)</script>",
"imageFileId": file_ids[0],
"attachmentFileIds": [file_ids[1]],
},
)
assert residential.status_code == 200, residential.text
article_ids.append(residential.json()["id"])
commercial = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"kind": "commercial",
"title": "商业估价服务指南",
"publishedAt": "2025-06-02T08:00:00",
"published": True,
"bodyHtml": "<p>商业流程</p>",
"attachmentFileIds": [],
},
)
assert commercial.status_code == 200, commercial.text
article_ids.append(commercial.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"kind": "industrial",
"title": "工业估价内部稿",
"publishedAt": "2025-06-03T08:00:00",
"published": False,
"bodyHtml": "<p>内部</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
all_list = client.get("/api/site/about/articles/appraisal_guides")
assert all_list.status_code == 200, all_list.text
titles = [item["title"] for item in all_list.json()["items"]]
assert "住宅估价服务指南" in titles
assert "商业估价服务指南" in titles
assert "工业估价内部稿" not in titles
residential_item = next(item for item in all_list.json()["items"] if "住宅" in item["title"])
assert residential_item["kind"] == "residential"
assert residential_item["kindLabel"] == "住宅"
assert residential_item.get("imageUrl")
only_residential = client.get("/api/site/about/articles/appraisal_guides?kind=residential")
assert only_residential.status_code == 200, only_residential.text
assert [item["title"] for item in only_residential.json()["items"]] == ["住宅估价服务指南"]
only_commercial = client.get("/api/site/about/articles/appraisal_guides?kind=commercial")
assert [item["title"] for item in only_commercial.json()["items"]] == ["商业估价服务指南"]
empty_specialty = client.get("/api/site/about/articles/appraisal_guides?kind=specialty")
assert empty_specialty.status_code == 200, empty_specialty.text
assert "暂无估价指南" in empty_specialty.text
bad_kind = client.get("/api/site/about/articles/appraisal_guides?kind=unknown")
assert bad_kind.status_code == 404
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
assert detail.json()["kind"] == "residential"
assert detail.json()["kindLabel"] == "住宅"
assert "住宅流程" in detail.json()["bodyHtml"]
assert "script" not in detail.json()["bodyHtml"].lower()
assert detail.json().get("imageUrl")
assert [item["filename"] for item in detail.json()["attachments"]] == ["住宅估价流程.pdf"]
hidden = client.get(f"/api/site/home/articles/{article_ids[2]}")
assert hidden.status_code == 404
for index in range(10):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"kind": "specialty",
"title": f"特色地产指南-{index:02d}",
"publishedAt": f"2025-01-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>特色-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/appraisal_guides?kind=specialty&current=1&size=10")
assert page1.status_code == 200, page1.text
assert page1.json()["total"] == 10
assert page1.json()["size"] == 10
assert len(page1.json()["items"]) == 10
home = client.get("/api/admin/home", headers=staff)
assert home.status_code == 200, home.text
categories = {item["category"] for item in home.json()["articles"]}
assert "appraisal_guides" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "appraisal_guides",
"kind": "residential",
"title": "会员不得发布指南",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员不得发布指南" not in client.get("/api/site/about/articles/appraisal_guides").text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+421
View File
@@ -0,0 +1,421 @@
import time
import uuid
from contextlib import contextmanager
import httpx
import pytest
import urllib3
from fastapi import HTTPException
from minio.error import S3Error
from sqlalchemy import func, inspect, select
from app.core.config import get_settings
from app.services.html_filter import filter_html
_PUBLIC_KEYS = {
"siteName",
"logoUrl",
"bannerUrls",
"icpText",
"policeText",
"friendLinks",
"linkCirea",
"linkHousing",
}
def test_object_key_keeps_safe_extension(monkeypatch):
monkeypatch.setenv("MINIO_BASE_URL", "http://127.0.0.1:9000/gsfdc-public/")
get_settings.cache_clear()
try:
from app.services.storage import make_object_key, public_object_url, safe_filename
assert safe_filename("../../logo.PNG") == "logo.PNG"
key = make_object_key("../../logo.PNG")
assert ".." not in key
assert key.endswith(".png")
url = public_object_url(key)
assert url == "http://127.0.0.1:9000/gsfdc-public/" + key
assert "//" not in url.replace("://", "")
finally:
get_settings.cache_clear()
def test_html_whitelist_removes_active_content():
html = (
'<p onClick="alert(1)" class="keep">正文敏感词</p>'
'<a href="javascript:alert(1)" title="t">链接</a>'
"<script>alert(1)</script>"
"<style>p{color:red}</style>"
'<div>前<iframe src="https://evil.test">密文</iframe>后</div>'
'<img src="https://evil.test/a.png" alt="x">'
'<img src="http://127.0.0.1:9000/gsfdc-public/2026/10/19/abc.png" alt="ok">'
)
cleaned = filter_html(html, ["2026/10/19/abc.png"], "http://127.0.0.1:9000/gsfdc-public")
lowered = cleaned.lower()
assert "<script" not in lowered
assert "onclick" not in lowered
assert "javascript:" not in lowered
assert "<style" not in lowered
assert "<iframe" not in lowered
assert "密文" not in cleaned
assert "alert" not in lowered
assert "evil.test" not in cleaned
assert "正文敏感词" in cleaned
assert 'class="keep"' in cleaned
assert "链接" in cleaned
assert 'title="t"' in cleaned
assert 'alt="x"' in cleaned
assert "2026/10/19/abc.png" in cleaned
assert "前" in cleaned and "后" in cleaned
def _database_configured() -> bool:
get_settings.cache_clear()
return bool(get_settings().database_url.strip())
def _load_routers():
try:
from app.api.admin.content import router as admin_router
from app.api.site.settings import router as site_router
except ModuleNotFoundError:
pytest.skip("app.db 尚未就绪")
return admin_router, site_router
@pytest.fixture
def api_client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
admin_router, site_router = _load_routers()
from fastapi.testclient import TestClient
from app.main import create_app
app = create_app()
paths = {getattr(route, "path", "") for route in app.routes}
if "/api/admin/files" not in paths:
app.include_router(admin_router, prefix="/api/admin")
if "/api/site/settings" not in paths:
app.include_router(site_router, prefix="/api/site")
with TestClient(app) as client:
yield client
get_settings.cache_clear()
def _staff_headers() -> dict[str, str]:
from app.core.security import create_access_token
token = create_access_token("1", "staff")
return {"Authorization": f"Bearer {token}"}
@contextmanager
def _session():
from app.db import get_db
resource = get_db()
if hasattr(resource, "__next__"):
db = next(resource)
try:
yield db
finally:
db.rollback()
resource.close()
return
try:
yield resource
finally:
resource.rollback()
resource.close()
def _prepare_tables() -> None:
from app.db import Base
from app.models.content import AdminFile, SensitiveWord, SiteSetting, ensure_site_defaults
with _session() as db:
Base.metadata.create_all(
bind=db.get_bind(),
tables=[SiteSetting.__table__, AdminFile.__table__, SensitiveWord.__table__],
)
ensure_site_defaults(db)
def _table_names() -> set[str]:
with _session() as db:
return set(inspect(db.get_bind()).get_table_names())
def _count_files() -> int:
from app.models.content import AdminFile
with _session() as db:
return int(db.scalar(select(func.count()).select_from(AdminFile)) or 0)
@pytest.fixture
def ready_client(api_client):
if not _database_configured():
pytest.skip("DATABASE_URL 为空")
_prepare_tables()
return api_client
def test_file_list_matches_filename(ready_client):
from app.db import SessionLocal
from app.models.content import AdminFile
token = uuid.uuid4().hex[:10]
names = [f"检索甲-{token}.txt", f"检索乙-{token}.png", f"其他-{token}.txt"]
db = SessionLocal()
ids: list[int] = []
try:
for name in names:
row = AdminFile(
bucket="public",
object_key=f"test/{token}/{name}",
filename=name,
content_type="text/plain",
size=1,
)
db.add(row)
db.flush()
ids.append(row.id)
db.commit()
finally:
db.close()
headers = _staff_headers()
try:
found = ready_client.get(
"/api/admin/files",
headers=headers,
params={"q": f"检索甲-{token}", "size": 20},
)
assert found.status_code == 200, found.text
body = found.json()
assert [item["filename"] for item in body["records"]] == [f"检索甲-{token}.txt"]
assert body["total"] == 1
wildcard = ready_client.get(
"/api/admin/files",
headers=headers,
params={"q": "%", "size": 100},
)
assert wildcard.status_code == 200, wildcard.text
assert f"检索甲-{token}.txt" not in [item["filename"] for item in wildcard.json()["records"]]
finally:
db = SessionLocal()
try:
for file_id in ids:
row = db.get(AdminFile, file_id)
if row is not None:
db.delete(row)
db.commit()
finally:
db.close()
def test_admin_content_requires_login(api_client):
checks = [
("get", "/api/admin/files", None),
("get", "/api/admin/files/1", None),
("get", "/api/admin/site-settings", None),
("get", "/api/admin/sensitive-words", None),
("put", "/api/admin/site-settings", {"site_name": "x"}),
("post", "/api/admin/sensitive-words", {"word": "x"}),
("post", "/api/admin/content/preview-filter", {"html": "<p>a</p>"}),
("delete", "/api/admin/sensitive-words/1", None),
("delete", "/api/admin/files/1", None),
]
for method, path, payload in checks:
kwargs = {"json": payload} if payload is not None else {}
response = getattr(api_client, method)(path, **kwargs)
assert response.status_code == 401, path
uploaded = api_client.post(
"/api/admin/files",
data={"bucket": "public"},
files={"file": ("a.txt", b"hi", "text/plain")},
)
assert uploaded.status_code == 401
def test_preview_filter_reports_words_without_new_tables(ready_client):
headers = _staff_headers()
word = "预览" + uuid.uuid4().hex[:12]
created = ready_client.post("/api/admin/sensitive-words", json={"word": word}, headers=headers)
assert created.status_code == 200, created.text
word_id = created.json()["id"]
try:
before_tables = _table_names()
before_count = len(ready_client.get("/api/admin/sensitive-words", headers=headers).json())
html = f'<p onclick="alert(1)">正文{word}</p><script>alert(1){word}</script>'
response = ready_client.post(
"/api/admin/content/preview-filter",
json={"html": html},
headers=headers,
)
assert response.status_code == 200, response.text
body = response.json()
assert word in body["hits"]
assert body["html"].count(word) == 1
assert "<script" not in body["html"].lower()
assert "onclick" not in body["html"].lower()
assert _table_names() == before_tables
after_count = len(ready_client.get("/api/admin/sensitive-words", headers=headers).json())
assert after_count == before_count
finally:
ready_client.delete(f"/api/admin/sensitive-words/{word_id}", headers=headers)
def test_upload_over_limit_is_rejected(ready_client):
headers = _staff_headers()
current = ready_client.get("/api/admin/site-settings", headers=headers)
assert current.status_code == 200, current.text
original = current.json()["upload_max_bytes"]
try:
updated = ready_client.put(
"/api/admin/site-settings",
json={"upload_max_bytes": 4},
headers=headers,
)
assert updated.status_code == 200, updated.text
before = _count_files()
rejected = ready_client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "public"},
files={"file": ("note.txt", b"12345", "text/plain")},
)
assert rejected.status_code == 400
assert rejected.json()["detail"] == "文件超过大小上限"
assert _count_files() == before
finally:
ready_client.put(
"/api/admin/site-settings",
json={"upload_max_bytes": original},
headers=headers,
)
def test_public_settings_hide_login_lock(ready_client):
headers = _staff_headers()
before = ready_client.get("/api/admin/site-settings", headers=headers)
assert before.status_code == 200, before.text
original = before.json()
assert isinstance(original["upload_max_bytes"], int)
assert isinstance(original["login_max_failures"], int)
assert isinstance(original["login_lock_minutes"], int)
assert isinstance(original["logoUrl"], str)
assert isinstance(original["bannerUrls"], list)
link = {"name": "示例链接", "url": "https://example.com/gsrea"}
try:
rejected = ready_client.put(
"/api/admin/site-settings",
json={"theme": "dark"},
headers=headers,
)
assert rejected.status_code == 400
saved = ready_client.put(
"/api/admin/site-settings",
json={
"site_name": "甘肃价协测试站点",
"icp_text": "陇ICP备测试号",
"friend_links": [link],
},
headers=headers,
)
assert saved.status_code == 200, saved.text
response = ready_client.get("/api/site/settings")
assert response.status_code == 200, response.text
body = response.json()
assert set(body) == _PUBLIC_KEYS
assert body["siteName"] == "甘肃价协测试站点"
assert body["icpText"] == "陇ICP备测试号"
assert body["friendLinks"] == [link]
assert isinstance(body["logoUrl"], str)
assert isinstance(body["bannerUrls"], list)
text = response.text
assert "login_max_failures" not in text
assert "login_lock_minutes" not in text
assert "loginMaxFailures" not in text
assert "loginLockMinutes" not in text
assert "upload_max_bytes" not in text
assert "uploadMaxBytes" not in text
finally:
ready_client.put(
"/api/admin/site-settings",
json={
"site_name": original["site_name"],
"icp_text": original["icp_text"],
"friend_links": original["friend_links"],
},
headers=headers,
)
def _minio_ready() -> bool:
from app.services.storage import ensure_buckets
try:
ensure_buckets()
except (urllib3.exceptions.HTTPError, OSError, TimeoutError):
return False
except (HTTPException, S3Error):
return False
return True
def test_public_object_and_private_expiry(ready_client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
from app.models.content import AdminFile
from app.services.storage import private_object_url
headers = _staff_headers()
payload = b"gsfdc-public-png"
created_ids: list[int] = []
try:
uploaded = ready_client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "public"},
files={"file": ("logo.png", payload, "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
public_body = uploaded.json()
created_ids.append(public_body["id"])
assert public_body["expiresAt"] is None
base = get_settings().minio_base_url.strip().rstrip("/")
assert public_body["url"].startswith(base + "/")
assert "//" not in public_body["url"].replace("://", "")
downloaded = httpx.get(public_body["url"], timeout=5.0, follow_redirects=True)
assert downloaded.status_code == 200
assert downloaded.content == payload
private = ready_client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "private"},
files={"file": ("secret.bin", b"gsfdc-private-bin", "application/octet-stream")},
)
assert private.status_code == 200, private.text
private_body = private.json()
created_ids.append(private_body["id"])
assert private_body["expiresAt"]
with _session() as db:
row = db.get(AdminFile, private_body["id"])
assert row is not None
assert row.created_by == 1
object_key = row.object_key
fresh, _ = private_object_url(object_key, expires_seconds=60)
assert httpx.get(fresh, timeout=5.0, follow_redirects=True).status_code == 200
short, _ = private_object_url(object_key, expires_seconds=1)
time.sleep(2)
expired = httpx.get(short, timeout=5.0, follow_redirects=True)
assert expired.status_code != 200
finally:
for file_id in created_ids:
ready_client.delete(f"/api/admin/files/{file_id}", headers=headers)
+319
View File
@@ -0,0 +1,319 @@
"""行业自律:三类栏目文章公开阅读;投诉加密保存,查询码只看状态。"""
import base64
import hashlib
from datetime import datetime, timedelta
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import select
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
key = base64.b64encode(hashlib.sha256(b"discipline-field-key").digest()).decode("ascii")
monkeypatch.setenv("FIELD_AES_KEY", key)
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def _clear_category(client, staff: dict[str, str], category: str) -> None:
listed = client.get(f"/api/admin/about/articles/{category}", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def _purge_complaints(codes: list[str]) -> list[int]:
from app.db import SessionLocal
from app.models.discipline import DisciplineComplaint, DisciplineComplaintFile
db = SessionLocal()
file_ids: list[int] = []
try:
rows = db.scalars(select(DisciplineComplaint).where(DisciplineComplaint.code.in_(codes))).all()
ids = [row.id for row in rows]
if not ids:
return []
links = db.scalars(
select(DisciplineComplaintFile).where(DisciplineComplaintFile.complaint_id.in_(ids))
).all()
file_ids = [link.file_id for link in links]
for link in links:
db.delete(link)
for row in rows:
db.delete(row)
db.commit()
finally:
db.close()
return file_ids
def test_discipline_articles_notice_and_complaint(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
member = _headers("member")
article_ids: list[int] = []
file_ids: list[int] = []
codes: list[str] = []
word_id = None
previous_workdays = None
try:
for category, placeholder in (
("warning_cases", "暂无警示案例"),
("integrity_records", "暂无诚信档案"),
("discipline_results", "暂无结果公示"),
):
_clear_category(client, staff, category)
empty = client.get(f"/api/site/about/articles/{category}")
assert empty.status_code == 200, empty.text
assert placeholder in empty.text
denied = client.get("/api/admin/discipline/complaints", headers=member)
assert denied.status_code == 403, denied.text
assert client.get("/api/admin/discipline/complaints").status_code == 401
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
attachment = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("note.txt", b"public-note", "text/plain")},
)
assert attachment.status_code == 200, attachment.text
file_ids.append(attachment.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "warning_cases",
"title": "未发布警示",
"published": False,
"bodyHtml": "<p>内部草稿</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
published = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "discipline_results",
"title": "某机构处理结果",
"published": True,
"bodyHtml": "<p>已脱敏的处理结果</p><script>alert(1)</script>",
"imageFileId": file_ids[0],
"attachmentFileIds": [file_ids[1]],
},
)
assert published.status_code == 200, published.text
article_ids.append(published.json()["id"])
hidden = client.get("/api/site/about/articles/warning_cases")
assert "未发布警示" not in hidden.text
shown = client.get("/api/site/about/articles/discipline_results")
titles = [item["title"] for item in shown.json()["items"]]
assert "某机构处理结果" in titles
detail = client.get(f"/api/site/home/articles/{published.json()['id']}")
assert "已脱敏的处理结果" in detail.text
assert "script" not in detail.text
assert "note.txt" in detail.text
home = client.get("/api/admin/home", headers=staff)
categories = {item["category"] for item in home.json()["articles"]}
assert "warning_cases" not in categories
assert "discipline_results" not in categories
settings = client.get("/api/admin/site-settings", headers=staff)
assert settings.status_code == 200, settings.text
previous_workdays = settings.json().get("complaint_workdays", "")
updated = client.put(
"/api/admin/site-settings",
headers=staff,
json={"complaint_workdays": 12},
)
assert updated.status_code == 200, updated.text
notice = client.put(
"/api/admin/discipline/notice",
headers=staff,
json={
"phone": "0931-1234567",
"email": "report@example.com",
"scopeHtml": "<p>受理估价执业违规</p><script>alert(1)</script>",
"processHtml": "<p>受理后核查</p>",
},
)
assert notice.status_code == 200, notice.text
assert notice.json()["workdays"] == 12
public_notice = client.get("/api/site/discipline/notice")
assert public_notice.status_code == 200, public_notice.text
assert "0931-1234567" in public_notice.text
assert "受理估价执业违规" in public_notice.text
assert "script" not in public_notice.text
assert public_notice.json()["workdays"] == 12
missing = client.post(
"/api/site/discipline/complaints",
data={
"title": "缺证据",
"subject": "某机构",
"body": "没有附件",
"contactName": "李四",
"mobile": "13800138000",
},
)
assert missing.status_code == 400, missing.text
assert "证据" in missing.text
word = "自律禁词" + hashlib.sha256(b"discipline-word").hexdigest()[:8]
created_word = client.post("/api/admin/sensitive-words", headers=staff, json={"word": word})
assert created_word.status_code == 200, created_word.text
word_id = created_word.json()["id"]
blocked = client.post(
"/api/site/discipline/complaints",
data={
"title": f"标题含{word}",
"subject": "某机构",
"body": "事实说明",
"contactName": "李四",
"mobile": "13800138000",
},
files=[("evidence", ("proof.png", _png(), "image/png"))],
)
assert blocked.status_code == 400, blocked.text
assert "敏感词" in blocked.text
secret = "只应工作人员看到的违规事实"
submitted = client.post(
"/api/site/discipline/complaints",
data={
"title": "估价报告违规",
"subject": "某估价机构",
"body": secret,
"contactName": "张三",
"mobile": "138-0013-8000",
"email": "a@example.com",
},
files=[("evidence", ("proof.png", _png(), "image/png"))],
)
assert submitted.status_code == 200, submitted.text
payload = submitted.json()
codes.append(payload["code"])
assert payload["status"] == "pending"
assert payload["workdays"] == 12
assert secret not in submitted.text
assert "13800138000" not in submitted.text
listed = client.get("/api/admin/discipline/complaints", headers=staff)
assert listed.status_code == 200, listed.text
item = next(row for row in listed.json()["items"] if row["code"] == payload["code"])
assert item["mobileMask"] == "138****8000"
assert item["emailMask"] == "a***@example.com"
assert secret not in listed.text
assert "13800138000" not in listed.text
assert item["attachmentCount"] == 1
opened = client.get(f"/api/admin/discipline/complaints/{item['id']}", headers=staff)
assert opened.status_code == 200, opened.text
assert opened.json()["mobile"] == "13800138000"
assert opened.json()["email"] == "a@example.com"
assert secret in opened.text
assert opened.json()["attachments"][0]["filename"] == "proof.png"
assert opened.json()["attachments"][0]["url"]
file_ids.append(opened.json()["attachments"][0]["id"])
status = client.get(f"/api/site/discipline/complaints/{payload['code']}")
assert status.status_code == 200, status.text
assert status.json()["statusLabel"] == "待处理"
assert secret not in status.text
assert "13800138000" not in status.text
assert "张三" not in status.text
assert "proof.png" not in status.text
from app.db import SessionLocal
from app.models.discipline import DisciplineComplaint
db = SessionLocal()
try:
row = db.scalar(select(DisciplineComplaint).where(DisciplineComplaint.code == payload["code"]))
assert row is not None
row.created_at = datetime.now() - timedelta(days=40)
db.commit()
finally:
db.close()
overdue = client.get("/api/admin/discipline/complaints?status=pending", headers=staff)
overdue_item = next(row for row in overdue.json()["items"] if row["code"] == payload["code"])
assert overdue_item["overdue"] is True
public_overdue = client.get(f"/api/site/discipline/complaints/{payload['code']}")
assert public_overdue.json()["overdue"] is True
done = client.post(f"/api/admin/discipline/complaints/{item['id']}/process", headers=staff)
assert done.status_code == 200, done.text
finished = client.get(f"/api/site/discipline/complaints/{payload['code'].lower()}")
assert finished.json()["status"] == "processed"
assert finished.json()["overdue"] is False
assert client.get("/api/site/discipline/complaints/NO-SUCH").status_code == 404
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
evidence_ids = _purge_complaints(codes)
for file_id in [*file_ids, *evidence_ids]:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
if word_id is not None:
client.delete(f"/api/admin/sensitive-words/{word_id}", headers=staff)
client.put(
"/api/admin/discipline/notice",
headers=staff,
json={"phone": "", "email": "", "scopeHtml": "", "processHtml": ""},
)
if previous_workdays is not None:
client.put(
"/api/admin/site-settings",
headers=staff,
json={"complaint_workdays": previous_workdays},
)
+223
View File
@@ -0,0 +1,223 @@
"""继续教育:在线教育外链卡片与教育公告。工作人员写入,门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def _clear_notices(client, staff: dict[str, str]) -> None:
listed = client.get("/api/admin/about/articles/edu_notices", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def test_edu_platforms_are_public_cards_and_notices_follow_publish_rules(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
file_ids: list[int] = []
try:
empty = client.get("/api/site/edu/platforms")
assert empty.status_code == 200, empty.text
assert empty.json()["placeholder"] == "暂无在线教育"
missing = client.put(
"/api/admin/edu/platforms",
headers=staff,
json={"items": [{"name": "省继续教育", "url": "https://example.com/edu", "sortOrder": 1}]},
)
assert missing.status_code == 400
assert "图片" in missing.text
script_url = client.put(
"/api/admin/edu/platforms",
headers=staff,
json={
"items": [
{
"name": "省继续教育",
"url": "javascript:alert(1)",
"imageFileId": 1,
"sortOrder": 1,
}
]
},
)
assert script_url.status_code == 400
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("platform.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
second = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("later.png", _png(), "image/png")},
)
assert second.status_code == 200, second.text
file_ids.append(second.json()["id"])
saved = client.put(
"/api/admin/edu/platforms",
headers=staff,
json={
"items": [
{
"name": "后配置的平台",
"url": "https://example.com/later",
"imageFileId": file_ids[1],
"sortOrder": 2,
},
{
"name": "甘肃省继续教育",
"url": "https://example.com/edu",
"imageFileId": file_ids[0],
"sortOrder": 1,
},
]
},
)
assert saved.status_code == 200, saved.text
admin_list = client.get("/api/admin/edu/platforms", headers=staff)
assert admin_list.status_code == 200, admin_list.text
assert [item["name"] for item in admin_list.json()["items"]] == [
"甘肃省继续教育",
"后配置的平台",
]
public = client.get("/api/site/edu/platforms")
assert public.status_code == 200, public.text
body = public.json()
assert "placeholder" not in body
assert [item["name"] for item in body["items"]] == ["甘肃省继续教育", "后配置的平台"]
first = body["items"][0]
assert first["url"] == "https://example.com/edu"
assert first["navigation"] == "newWindow"
assert first["imageUrl"]
assert "imageFileId" not in first
rejected = client.put(
"/api/admin/edu/platforms",
headers=_headers("member"),
json={"items": []},
)
assert rejected.status_code in (401, 403)
assert client.get("/api/site/edu/platforms").json()["items"][0]["name"] == "甘肃省继续教育"
shortcut = client.put(
"/api/admin/home/menu",
headers=staff,
json={
"items": [
{
"key": "edu",
"label": "继续教育",
"url": "https://example.com/edu",
"visible": True,
"sortOrder": 1,
}
]
},
)
assert shortcut.status_code == 400
labels = [item["label"] for item in client.get("/api/site/home").json()["shortcutMenu"]["items"]]
assert "继续教育" not in labels
_clear_notices(client, staff)
empty_notices = client.get("/api/site/about/articles/edu_notices")
assert empty_notices.status_code == 200, empty_notices.text
assert empty_notices.json()["placeholder"] == "暂无教育公告"
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "edu_notices",
"title": "内部培训草稿",
"published": False,
"bodyHtml": "<p>尚未公示</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
published = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "edu_notices",
"title": "2026年度培训计划",
"published": True,
"bodyHtml": "<p>线上与线下安排</p><script>alert(1)</script>",
"imageFileId": file_ids[0],
"attachmentFileIds": [],
},
)
assert published.status_code == 200, published.text
notices = client.get("/api/site/about/articles/edu_notices")
assert notices.status_code == 200, notices.text
titles = [item["title"] for item in notices.json()["items"]]
assert titles == ["2026年度培训计划"]
assert "内部培训草稿" not in notices.text
assert notices.json()["items"][0]["imageUrl"]
detail = client.get(f"/api/site/home/articles/{published.json()['id']}")
assert detail.status_code == 200, detail.text
assert "线上与线下安排" in detail.text
assert "script" not in detail.text
assert "alert" not in detail.text
home = client.get("/api/admin/home", headers=staff)
categories = {item["category"] for item in home.json()["articles"]}
assert "edu_notices" not in categories
finally:
client.put("/api/admin/edu/platforms", headers=staff, json={"items": []})
_clear_notices(client, staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+181
View File
@@ -0,0 +1,181 @@
"""专家答疑:会员提问、只读本人、工作人员回复、待回复计数与超时。"""
from datetime import datetime, timedelta
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
from app.models.expert import is_overdue, workday_deadline
from app.services.email_code import _key
from app.services.redis_client import get_redis
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
monkeypatch.setenv("SMTP_HOST", "")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
try:
get_redis().ping()
except Exception:
pytest.skip("Redis 不可达")
monkeypatch.setattr("app.services.email_code.send_email", lambda **kwargs: None)
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _code(purpose: str, email: str) -> str:
stored = get_redis().get(_key(purpose, email))
assert stored is not None
if isinstance(stored, bytes):
stored = stored.decode("utf-8")
return stored
def _register(client, email: str, password: str = "Passw0rd1") -> str:
assert client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"}).status_code == 200
code = _code("register", email)
registered = client.post(
"/api/site/auth/register",
json={"email": email, "code": code, "password": password, "privacyAccepted": True},
)
assert registered.status_code == 200, registered.text
return registered.json()["accessToken"]
def test_workday_deadline_skips_weekend():
# 周五提交,3 个工作日后是下周三
friday = datetime(2025, 1, 3, 10, 0, 0) # Friday
assert workday_deadline(friday, 3) == datetime(2025, 1, 8).date() # Wed
assert is_overdue(friday, 3, now=datetime(2025, 1, 8, 9, 0, 0)) is False
assert is_overdue(friday, 3, now=datetime(2025, 1, 9, 9, 0, 0)) is True
def test_expert_qa_ask_reply_isolation_and_pending_count(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
import time
email_a = f"qa-a-{int(time.time() * 1000)}@example.com"
email_b = f"qa-b-{int(time.time() * 1000)}@example.com"
token_a = _register(client, email_a)
token_b = _register(client, email_b)
headers_a = {"Authorization": f"Bearer {token_a}"}
headers_b = {"Authorization": f"Bearer {token_b}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
denied = client.post(
"/api/site/member/expert-questions",
json={"title": "未登录", "body": "x", "attachmentFileIds": []},
)
assert denied.status_code in (401, 403)
uploaded = client.post(
"/api/site/member/files",
headers=headers_a,
files={"file": ("证据.pdf", b"%PDF-1.4\nqa", "application/pdf")},
)
assert uploaded.status_code == 200, uploaded.text
file_id = uploaded.json()["id"]
created = client.post(
"/api/site/member/expert-questions",
headers=headers_a,
json={
"title": "住宅估价流程咨询",
"body": "请问住宅估价需要哪些材料?",
"attachmentFileIds": [file_id],
},
)
assert created.status_code == 200, created.text
question_id = created.json()["id"]
mine = client.get("/api/site/member/expert-questions", headers=headers_a)
assert mine.status_code == 200, mine.text
assert mine.json()["items"][0]["title"] == "住宅估价流程咨询"
assert mine.json()["items"][0]["status"] == "pending"
other = client.get(f"/api/site/member/expert-questions/{question_id}", headers=headers_b)
assert other.status_code == 404
other_list = client.get("/api/site/member/expert-questions", headers=headers_b)
assert other_list.json()["items"] == []
pending = client.get("/api/admin/expert-questions/pending-count", headers=staff)
assert pending.status_code == 200, pending.text
assert pending.json()["count"] >= 1
listed = client.get("/api/admin/expert-questions?status=pending", headers=staff)
assert listed.status_code == 200, listed.text
assert any(item["id"] == question_id for item in listed.json()["items"])
member_reply = client.post(
f"/api/admin/expert-questions/{question_id}/reply",
headers=headers_a,
json={"bodyHtml": "<p>会员不得回复</p>", "attachmentFileIds": []},
)
assert member_reply.status_code in (401, 403)
replied = client.post(
f"/api/admin/expert-questions/{question_id}/reply",
headers=staff,
json={
"bodyHtml": "<p>请准备产权证与房屋平面图</p><script>alert(1)</script>",
"attachmentFileIds": [],
},
)
assert replied.status_code == 200, replied.text
detail = client.get(f"/api/site/member/expert-questions/{question_id}", headers=headers_a)
assert detail.status_code == 200, detail.text
assert detail.json()["status"] == "replied"
assert "产权证" in detail.json()["reply"]["bodyHtml"]
assert "script" not in detail.json()["reply"]["bodyHtml"].lower()
assert detail.json()["attachments"][0]["filename"] == "证据.pdf"
assert "contentType" in detail.json()["attachments"][0]
after = client.get("/api/admin/expert-questions/pending-count", headers=staff)
assert after.json()["count"] == pending.json()["count"] - 1
# 人为把另一条提问改成超时
overdue_created = client.post(
"/api/site/member/expert-questions",
headers=headers_a,
json={"title": "超时样例", "body": "等待回复", "attachmentFileIds": []},
)
assert overdue_created.status_code == 200, overdue_created.text
overdue_id = overdue_created.json()["id"]
from app.db import SessionLocal
from app.models.expert import ExpertQuestion
db = SessionLocal()
try:
row = db.get(ExpertQuestion, overdue_id)
row.created_at = datetime.now() - timedelta(days=14)
db.commit()
finally:
db.close()
admin_detail = client.get(f"/api/admin/expert-questions/{overdue_id}", headers=staff)
assert admin_detail.status_code == 200, admin_detail.text
assert admin_detail.json()["overdue"] is True
+58
View File
@@ -0,0 +1,58 @@
import base64
import hashlib
import pytest
from fastapi import HTTPException
from app.core.config import get_settings
from app.core.field_crypto import decrypt_text, encrypt_text
from app.core.masking import mask_id_card, mask_mobile
_ID_CARD = "620102199001011234"
_MOBILE = "13800138000"
def _use_key(monkeypatch, encoded: str) -> None:
monkeypatch.setenv("FIELD_AES_KEY", encoded)
get_settings.cache_clear()
def test_id_card_and_mobile_roundtrip(monkeypatch):
key = hashlib.sha256(b"field-crypto-test").digest()
assert len(key) == 32
_use_key(monkeypatch, base64.b64encode(key).decode("ascii"))
try:
token = encrypt_text(_ID_CARD)
assert token
assert token != _ID_CARD
assert decrypt_text(token) == _ID_CARD
assert mask_id_card(decrypt_text(token)) == "6201**********1234"
assert mask_id_card(_ID_CARD) == "6201**********1234"
mobile_token = encrypt_text(_MOBILE)
assert decrypt_text(mobile_token) == _MOBILE
assert mask_mobile(_MOBILE) == "138****8000"
assert encrypt_text("") == ""
assert decrypt_text("") == ""
finally:
get_settings.cache_clear()
def test_missing_or_short_field_key(monkeypatch):
try:
_use_key(monkeypatch, "")
assert encrypt_text("") == ""
with pytest.raises(HTTPException) as missing:
encrypt_text(_ID_CARD)
assert missing.value.status_code == 503
assert missing.value.detail == "字段加密未配置"
short_key = base64.b64encode(b"0123456789abcdef").decode("ascii")
_use_key(monkeypatch, short_key)
with pytest.raises(HTTPException) as short:
encrypt_text(_ID_CARD)
assert short.value.status_code == 503
assert short.value.detail == "字段加密未配置"
finally:
get_settings.cache_clear()
+52
View File
@@ -0,0 +1,52 @@
import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from fastapi.testclient import TestClient
os.environ["JWT_SECRET"] = "test-secret-must-be-32-characters!"
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
os.environ["API_PAYLOAD_AES_KEY"] = base64.b64encode(b"0123456789abcdef0123456789abcdef").decode()
from app.core.config import get_settings
from app.core.security import create_access_token
from app.main import create_app
get_settings.cache_clear()
def test_site_health_is_public():
client = TestClient(create_app())
response = client.get("/api/site/health")
assert response.status_code == 200
assert response.json()["scope"] == "site"
def test_admin_requires_staff_token():
client = TestClient(create_app())
assert client.get("/api/admin/health").status_code == 401
member = create_access_token("member-1", "member")
rejected = client.get("/api/admin/health", headers={"Authorization": f"Bearer {member}"})
assert rejected.status_code == 403
staff = create_access_token("staff-1", "staff")
accepted = client.get("/api/admin/health", headers={"Authorization": f"Bearer {staff}"})
assert accepted.status_code == 200
assert accepted.json()["subject"] == "staff-1"
def test_payload_encryption_roundtrip(monkeypatch):
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "true")
get_settings.cache_clear()
client = TestClient(create_app())
key = base64.b64decode(os.environ["API_PAYLOAD_AES_KEY"])
nonce = b"123456789012"
plain = b'{"ping":true}'
token = base64.b64encode(nonce + AESGCM(key).encrypt(nonce, plain, None)).decode()
response = client.post("/api/site/health", json={"data": token})
assert response.status_code == 405
body = response.json()
assert "data" in body
raw = base64.b64decode(body["data"])
decoded = AESGCM(key).decrypt(raw[:12], raw[12:], None)
assert b"Method Not Allowed" in decoded or "detail" in decoded.decode()
get_settings.cache_clear()
File diff suppressed because it is too large. Load diff
+273
View File
@@ -0,0 +1,273 @@
"""机构名录栏目文章:工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_category(client, staff: dict[str, str]) -> None:
listed = client.get("/api/admin/about/articles/institution_directories", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def test_institution_directory_publish_filter_placeholder_and_attachment(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
_clear_category(client, staff)
empty = client.get("/api/site/about/articles/institution_directories")
assert empty.status_code == 200, empty.text
assert "暂无机构名录" in empty.text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("名录.pdf", b"%PDF-1.4\nroster", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "institution_directories",
"title": "甘肃省房地产价格评估行业协会单位会员名录(2025年6月)",
"publishedAt": "2025-06-05T08:00:00",
"published": True,
"bodyHtml": (
"<p>兰州市</p><table><tr><td>甘肃中瑞房地产资产评估有限公司</td></tr></table>"
"<script>alert(1)</script>"
),
"attachmentFileIds": [file_ids[0]],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "institution_directories",
"title": "未发布名录",
"publishedAt": "2025-06-06T08:00:00",
"published": False,
"bodyHtml": "<p>未发布名录</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
listed = client.get("/api/site/about/articles/institution_directories")
assert listed.status_code == 200, listed.text
assert "甘肃省房地产价格评估行业协会单位会员名录(2025年6月)" in listed.text
assert "未发布名录" not in listed.text
assert "暂无机构名录" not in listed.text
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
body = detail.json()["bodyHtml"]
assert "甘肃中瑞房地产资产评估有限公司" in body
assert "table" in body.lower()
lowered = body.lower()
assert "script" not in lowered
assert "alert" not in lowered
assert [item["filename"] for item in detail.json()["attachments"]] == ["名录.pdf"]
hidden = client.get(f"/api/site/home/articles/{article_ids[1]}")
assert hidden.status_code == 404
editor = client.get("/api/admin/home", headers=staff)
assert editor.status_code == 200, editor.text
categories = {item["category"] for item in editor.json()["articles"]}
assert "institution_directories" not in categories
before = client.get("/api/site/about/articles/institution_directories").text
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "institution_directories",
"title": "会员不得发布名录",
"published": True,
"bodyHtml": "<p>会员不得发布名录</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
after = client.get("/api/site/about/articles/institution_directories")
assert after.text == before
assert "会员不得发布名录" not in after.text
renamed = client.put(
f"/api/admin/home/articles/{article_ids[0]}",
headers=staff,
json={
"category": "institution_directories",
"title": "甘肃省房地产价格评估行业协会单位会员名录(2025年6月修订)",
"publishedAt": "2025-06-05T08:00:00",
"published": True,
"bodyHtml": "<p>兰州市</p><table><tr><td>甘肃中瑞房地产资产评估有限公司</td></tr></table>",
"attachmentFileIds": [file_ids[0]],
},
)
assert renamed.status_code == 200, renamed.text
revised = client.get("/api/site/about/articles/institution_directories")
assert "单位会员名录(2025年6月修订)" in revised.text
assert "单位会员名录(2025年6月)" not in revised.text.replace("单位会员名录(2025年6月修订)", "")
deleted = client.delete(f"/api/admin/home/articles/{article_ids[0]}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
article_ids.remove(article_ids[0])
gone = client.get("/api/site/about/articles/institution_directories")
assert "单位会员名录(2025年6月修订)" not in gone.text
assert "暂无机构名录" in gone.text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
def test_institution_directory_public_pagination(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
try:
_clear_category(client, staff)
for index in range(11):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "institution_directories",
"title": f"名录分页样例-{index:02d}",
"publishedAt": f"2026-03-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>名录分页样例-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/institution_directories?current=1&size=10")
assert page1.status_code == 200, page1.text
body1 = page1.json()
assert body1["total"] == 11
assert body1["current"] == 1
assert body1["size"] == 10
assert len(body1["items"]) == 10
assert body1["items"][0]["title"] == "名录分页样例-10"
page2 = client.get("/api/site/about/articles/institution_directories?current=2&size=10")
assert page2.status_code == 200, page2.text
body2 = page2.json()
assert body2["total"] == 11
assert body2["current"] == 2
assert len(body2["items"]) == 1
assert body2["items"][0]["title"] == "名录分页样例-00"
size20 = client.get("/api/site/about/articles/institution_directories?current=1&size=20")
assert size20.status_code == 200, size20.text
assert size20.json()["size"] == 20
assert len(size20.json()["items"]) == 11
bad_size = client.get("/api/site/about/articles/institution_directories?current=1&size=15")
assert bad_size.status_code == 200, bad_size.text
assert bad_size.json()["size"] == 10
assert len(bad_size.json()["items"]) == 10
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
PUBLISHED_TITLES = [
"甘肃省房地产价格评估行业协会单位会员名录(2025年6月)",
"甘肃省房地产价格评估行业协会个人会员名录(2025年5月)",
"甘肃省房地产价格评估行业协会个人会员名录(2023年6月)",
"甘肃省房地产价格评估行业协会单位会员名录(2023年6月)",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2022年4月)",
"甘肃省房地产价格评估行业协会单位会员名录(2022年4月)",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2021年7月)",
"甘肃省房地产价格评估行业协会估价师单位会员名录(2021年7月)",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2021年5月)",
"甘肃省房地产价格评估行业协会单位会员名录(2021年5月)",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2020年)",
"甘肃省房地产价格评估行业协会单位会员名录(2020年)",
"甘肃省最低收费备案标准名单",
"甘肃省住房和城乡建设厅关于公布甘肃省房地产估价机构名录的通知",
"甘肃省房地产价格评估行业协会单位会员名录",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2019年)",
]
def test_institution_directory_import_keeps_titles_and_is_idempotent(client):
staff = _headers("staff")
from app.commands.import_institution_directories import import_institution_directories
from app.db import SessionLocal
db = SessionLocal()
try:
_clear_category(client, staff)
import_institution_directories(db)
listed = client.get("/api/site/about/articles/institution_directories?current=1&size=20")
assert listed.status_code == 200, listed.text
body = listed.json()
assert body["total"] == 16
assert [item["title"] for item in body["items"]] == PUBLISHED_TITLES
detail = client.get(f"/api/site/home/articles/{body['items'][0]['id']}")
assert detail.status_code == 200, detail.text
assert "甘肃中瑞房地产资产评估有限公司" in detail.json()["bodyHtml"]
assert "table" in detail.json()["bodyHtml"].lower()
import_institution_directories(db)
again = client.get("/api/site/about/articles/institution_directories?current=1&size=20")
assert again.status_code == 200, again.text
titles = [item["title"] for item in again.json()["items"]]
assert titles == PUBLISHED_TITLES
assert len(titles) == len(set(titles))
finally:
db.close()
_clear_category(client, staff)
+88
View File
@@ -0,0 +1,88 @@
"""合规正文:隐私政策 / 使用条款 / 网站声明。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _staff() -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
def test_legal_pages_publish_filter_placeholder_and_footer_links(client):
staff = _staff()
try:
for key, placeholder in (
("privacy", "隐私政策整理中"),
("terms", "使用条款整理中"),
("statement", "网站声明整理中"),
):
empty = client.get(f"/api/site/legal/{key}")
assert empty.status_code == 200, empty.text
assert placeholder in empty.text
home = client.get("/api/site/home")
assert home.status_code == 200, home.text
labels = [item["label"] for item in home.json()["compliance"]["links"]]
assert labels == ["隐私政策", "使用条款", "网站声明"]
assert all(item["navigation"] == "sameWindow" for item in home.json()["compliance"]["links"])
assert home.json()["compliance"]["links"][0]["url"] == "/legal/privacy"
assert "隐私政策、使用条款与网站声明整理中" not in home.text
saved = client.put(
"/api/admin/legal/privacy",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>我们如何处理个人信息</p><script>alert(1)</script>",
},
)
assert saved.status_code == 200, saved.text
public = client.get("/api/site/legal/privacy")
assert public.status_code == 200, public.text
assert public.json()["title"] == "隐私政策"
assert "我们如何处理个人信息" in public.json()["bodyHtml"]
lowered = public.json()["bodyHtml"].lower()
assert "script" not in lowered
assert "alert" not in lowered
assert "隐私政策整理中" not in public.text
rejected = client.put(
"/api/admin/legal/privacy",
headers={"Authorization": f"Bearer {create_access_token('1', 'member')}"},
json={"published": True, "bodyHtml": "<p>会员不得改</p>"},
)
assert rejected.status_code in (401, 403)
assert "会员不得改" not in client.get("/api/site/legal/privacy").text
cleared = client.put(
"/api/admin/legal/privacy",
headers=staff,
json={"published": False, "bodyHtml": "<p></p>"},
)
assert cleared.status_code == 200, cleared.text
assert "隐私政策整理中" in client.get("/api/site/legal/privacy").text
finally:
for key in ("privacy", "terms", "statement"):
client.put(
f"/api/admin/legal/{key}",
headers=staff,
json={"published": False, "bodyHtml": "<p></p>"},
)
+226
View File
@@ -0,0 +1,226 @@
"""资料库:政策分类、标题与正文检索、案例库、未发布不可见。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def test_library_publish_kind_search_and_cases(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
empty_policy = client.get("/api/site/about/articles/policy_analyses")
assert empty_policy.status_code == 200, empty_policy.text
assert "暂无政策分析" in empty_policy.text
empty_cases = client.get("/api/site/about/articles/case_library")
assert empty_cases.status_code == 200, empty_cases.text
assert "暂无案例库" in empty_cases.text
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("政策.pdf", b"%PDF-1.4\npolicy", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
published = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "policy_analyses",
"kind": "national",
"title": "资料库检索样例-民法典导读",
"published": True,
"publishedAt": "2025-09-12T08:00:00",
"bodyHtml": "<p>本条标注:现行有效。</p>",
"imageFileId": cover.json()["id"],
"attachmentFileIds": [pdf.json()["id"]],
},
)
assert published.status_code == 200, published.text
article_ids.append(published.json()["id"])
local = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "policy_analyses",
"kind": "local",
"title": "资料库检索样例-地方配套",
"published": True,
"publishedAt": "2025-03-08T08:00:00",
"bodyHtml": "<p>仅收录本地区政策。</p>",
"attachmentFileIds": [],
},
)
assert local.status_code == 200, local.text
article_ids.append(local.json()["id"])
hidden = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "policy_analyses",
"kind": "expert",
"title": "资料库检索样例-未发布解读",
"published": False,
"bodyHtml": "<p>正文里有未发布机密词。</p>",
"attachmentFileIds": [],
},
)
assert hidden.status_code == 200, hidden.text
article_ids.append(hidden.json()["id"])
bad_kind = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "policy_analyses",
"kind": "residential",
"title": "资料库检索样例-错误分类",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert bad_kind.status_code == 400
case_with_kind = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "case_library",
"kind": "national",
"title": "资料库检索样例-案例不分类",
"published": True,
"bodyHtml": "<p>案例正文</p>",
"attachmentFileIds": [],
},
)
assert case_with_kind.status_code == 400
case = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "case_library",
"title": "资料库检索样例-城关区案例",
"published": True,
"publishedAt": "2025-08-16T08:00:00",
"bodyHtml": "<p>可比案例说明。</p>",
"imageFileId": cover.json()["id"],
"attachmentFileIds": [pdf.json()["id"]],
},
)
assert case.status_code == 200, case.text
article_ids.append(case.json()["id"])
listed = client.get("/api/site/about/articles/policy_analyses")
titles = [item["title"] for item in listed.json()["items"]]
assert "资料库检索样例-民法典导读" in titles
assert "资料库检索样例-未发布解读" not in titles
national = next(item for item in listed.json()["items"] if item["title"] == "资料库检索样例-民法典导读")
assert national["kind"] == "national"
assert national["kindLabel"] == "国家级"
assert national["imageUrl"]
only_local = client.get("/api/site/about/articles/policy_analyses?kind=local")
assert [item["title"] for item in only_local.json()["items"]] == ["资料库检索样例-地方配套"]
by_title = client.get("/api/site/about/articles/policy_analyses?q=民法典")
assert [item["title"] for item in by_title.json()["items"]] == ["资料库检索样例-民法典导读"]
by_body = client.get("/api/site/about/articles/policy_analyses?q=现行有效")
assert [item["title"] for item in by_body.json()["items"]] == ["资料库检索样例-民法典导读"]
hidden_body = client.get("/api/site/about/articles/policy_analyses?q=未发布机密词")
assert hidden_body.json()["placeholder"] == "未找到相关政策"
assert hidden_body.json()["items"] == []
unknown = client.get("/api/site/about/articles/policy_analyses?kind=unknown")
assert unknown.status_code == 404
cases = client.get("/api/site/about/articles/case_library")
assert cases.json()["items"][0]["title"] == "资料库检索样例-城关区案例"
assert "kind" not in cases.json()["items"][0]
detail = client.get(f"/api/site/home/articles/{national['id']}")
assert detail.status_code == 200, detail.text
assert "现行有效" in detail.text
assert "政策.pdf" in detail.text
home = client.get("/api/admin/home", headers=staff)
categories = {item["category"] for item in home.json()["articles"]}
assert "policy_analyses" not in categories
assert "case_library" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "policy_analyses",
"kind": "national",
"title": "会员不得发布政策",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+166
View File
@@ -0,0 +1,166 @@
"""门户邮箱账号:注册、登录、重置密码与令牌隔离。"""
from datetime import datetime, timezone
import jwt
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
from app.services.email_code import _key
from app.services.redis_client import get_redis
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
monkeypatch.setenv("SMTP_HOST", "")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
try:
get_redis().ping()
except Exception:
pytest.skip("Redis 不可达")
def _noop_send(**kwargs):
return None
monkeypatch.setattr("app.services.email_code.send_email", _noop_send)
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _code(purpose: str, email: str) -> str:
stored = get_redis().get(_key(purpose, email))
assert stored is not None, f"missing code for {purpose}/{email}"
if isinstance(stored, bytes):
stored = stored.decode("utf-8")
return stored
def _unique_email() -> str:
import time
return f"member-{int(time.time() * 1000)}@example.com"
def test_member_token_lasts_seven_days(client):
settings = get_settings()
token = create_access_token("42", "member")
payload = jwt.decode(token, settings.jwt_secret, algorithms=["HS256"])
exp = datetime.fromtimestamp(payload["exp"], tz=timezone.utc)
remaining = (exp - datetime.now(timezone.utc)).total_seconds()
assert remaining > 6.5 * 24 * 3600
assert remaining < 7.5 * 24 * 3600
def test_register_keeps_code_when_password_invalid(client):
"""弱密码拒收后,同一验证码仍可用于再次提交。"""
email = _unique_email()
sent = client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"})
assert sent.status_code == 200, sent.text
code = _code("register", email)
weak = client.post(
"/api/site/auth/register",
json={"email": email, "code": code, "password": "short", "privacyAccepted": True},
)
assert weak.status_code == 400, weak.text
assert "验证码" not in weak.json().get("detail", "")
registered = client.post(
"/api/site/auth/register",
json={"email": email, "code": code, "password": "Passw0rd1", "privacyAccepted": True},
)
assert registered.status_code == 200, registered.text
assert registered.json()["tokenType"] == "member"
def test_register_login_reset_and_token_isolation(client):
email = _unique_email()
password = "Passw0rd1"
new_password = "Passw0rd2"
no_privacy = client.post(
"/api/site/auth/register",
json={"email": email, "code": "000000", "password": password, "privacyAccepted": False},
)
assert no_privacy.status_code == 400
assert "隐私政策" in no_privacy.text
sent = client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"})
assert sent.status_code == 200, sent.text
code = _code("register", email)
registered = client.post(
"/api/site/auth/register",
json={"email": email, "code": code, "password": password, "privacyAccepted": True},
)
assert registered.status_code == 200, registered.text
token = registered.json()["accessToken"]
assert registered.json()["tokenType"] == "member"
me = client.get("/api/site/member/me", headers={"Authorization": f"Bearer {token}"})
assert me.status_code == 200, me.text
assert me.json()["email"] == email.lower()
again = client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"})
assert again.status_code == 400
bad_login = client.post(
"/api/site/auth/login",
json={"email": email, "password": "WrongPass1"},
)
assert bad_login.status_code == 401
login = client.post(
"/api/site/auth/login",
json={"email": email, "password": password},
)
assert login.status_code == 200, login.text
login_token = login.json()["accessToken"]
reset_sent = client.post("/api/site/auth/email-code", json={"email": email, "purpose": "reset"})
assert reset_sent.status_code == 200, reset_sent.text
# 上一发可能还在 60s 频控内;若失败则直接用 redis 写入
if reset_sent.status_code == 200:
reset_code = _code("reset", email)
else:
pytest.fail(reset_sent.text)
# 若仍被频控挡住了第一次 reset 请求以外的路径,上面已成功
reset = client.post(
"/api/site/auth/reset-password",
json={"email": email, "code": reset_code, "password": new_password},
)
assert reset.status_code == 200, reset.text
old_login = client.post(
"/api/site/auth/login",
json={"email": email, "password": password},
)
assert old_login.status_code == 401
new_login = client.post(
"/api/site/auth/login",
json={"email": email, "password": new_password},
)
assert new_login.status_code == 200, new_login.text
member_on_admin = client.get(
"/api/admin/home",
headers={"Authorization": f"Bearer {login_token}"},
)
assert member_on_admin.status_code in (401, 403)
staff_on_member = client.get(
"/api/site/member/me",
headers={"Authorization": f"Bearer {create_access_token('1', 'staff')}"},
)
assert staff_on_member.status_code in (401, 403)
+224
View File
@@ -0,0 +1,224 @@
"""行业党建:支部介绍单篇 + 党建活动栏目文章。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_category(client, staff: dict[str, str], category: str) -> None:
listed = client.get(f"/api/admin/about/articles/{category}", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def test_party_branch_page_and_activities(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
_clear_category(client, staff, "party_activities")
empty_page = client.get("/api/site/about/pages/party_branch")
assert empty_page.status_code == 200, empty_page.text
assert "协会党支部介绍整理中" in empty_page.text
empty_list = client.get("/api/site/about/articles/party_activities")
assert empty_list.status_code == 200, empty_list.text
assert "暂无党建活动" in empty_list.text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("党支部制度.pdf", b"%PDF-1.4\ncharter", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
saved_page = client.put(
"/api/admin/about/pages/party_branch",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>党建引领行业发展</p><script>alert(1)</script>",
"attachmentFileIds": [file_ids[0]],
},
)
assert saved_page.status_code == 200, saved_page.text
public_page = client.get("/api/site/about/pages/party_branch")
assert public_page.status_code == 200, public_page.text
assert "党建引领行业发展" in public_page.json()["bodyHtml"]
lowered = public_page.json()["bodyHtml"].lower()
assert "script" not in lowered
assert "alert" not in lowered
assert [item["filename"] for item in public_page.json()["attachments"]] == ["党支部制度.pdf"]
assert "协会党支部介绍整理中" not in public_page.text
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
activity_pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("学习纪要.pdf", b"%PDF-1.4\nnotes", "application/pdf")},
)
assert activity_pdf.status_code == 200, activity_pdf.text
file_ids.append(activity_pdf.json()["id"])
published = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "party_activities",
"title": "主题党日:学习估价行业诚信自律要求",
"publishedAt": "2025-10-12T08:00:00",
"published": True,
"bodyHtml": "<p>主题党日学习</p><script>alert(1)</script>",
"imageFileId": file_ids[1],
"attachmentFileIds": [file_ids[2]],
},
)
assert published.status_code == 200, published.text
article_ids.append(published.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "party_activities",
"title": "内部筹备党建活动",
"publishedAt": "2025-10-13T08:00:00",
"published": False,
"bodyHtml": "<p>内部</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
listed = client.get("/api/site/about/articles/party_activities")
assert listed.status_code == 200, listed.text
assert "主题党日:学习估价行业诚信自律要求" in listed.text
assert "内部筹备党建活动" not in listed.text
assert listed.json()["items"][0].get("imageUrl")
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
assert "主题党日学习" in detail.json()["bodyHtml"]
body = detail.json()["bodyHtml"].lower()
assert "script" not in body
assert detail.json().get("imageUrl")
assert [item["filename"] for item in detail.json()["attachments"]] == ["学习纪要.pdf"]
assert client.get(f"/api/site/home/articles/{article_ids[1]}").status_code == 404
for index in range(10):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "party_activities",
"title": f"党建分页样例-{index:02d}",
"publishedAt": f"2025-01-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>党建分页样例-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/party_activities?current=1&size=10")
assert page1.json()["total"] == 11
assert page1.json()["size"] == 10
assert len(page1.json()["items"]) == 10
assert len(client.get("/api/site/about/articles/party_activities?current=2&size=10").json()["items"]) == 1
assert client.get("/api/site/about/articles/party_activities?current=1&size=20").json()["size"] == 20
assert client.get("/api/site/about/articles/party_activities?current=1&size=15").json()["size"] == 10
home = client.get("/api/admin/home", headers=staff)
assert home.status_code == 200, home.text
categories = {item["category"] for item in home.json()["articles"]}
assert "party_activities" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "party_activities",
"title": "会员不得发布党建",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员不得发布党建" not in client.get("/api/site/about/articles/party_activities").text
emptied = client.put(
"/api/admin/about/pages/party_branch",
headers=staff,
json={"published": False, "bodyHtml": "<p></p>", "attachmentFileIds": []},
)
assert emptied.status_code == 200, emptied.text
assert "协会党支部介绍整理中" in client.get("/api/site/about/pages/party_branch").text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
client.put(
"/api/admin/about/pages/party_branch",
headers=staff,
json={"published": False, "bodyHtml": "<p></p>", "attachmentFileIds": []},
)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+721
View File
@@ -0,0 +1,721 @@
import importlib
import os
import re
import sys
import types
import uuid
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
from sqlalchemy import delete, select, text, update
from sqlalchemy.orm import Session
os.environ["JWT_SECRET"] = "test-secret-must-be-32-characters!"
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
PASSWORD_RULE = "密码至少 8 位,且同时包含字母和数字"
LOGIN_FAILURE = "用户名或密码错误"
KEEP_SELF = "不能停用或注销当前登录用户"
KEEP_FULL_ADMIN = "至少保留一名拥有全部系统菜单的正常用户"
def _install_stub(module_name: str, **attrs: object) -> None:
try:
module = importlib.import_module(module_name)
except Exception:
sys.modules.pop(module_name, None)
module = types.ModuleType(module_name)
sys.modules[module_name] = module
for key, value in attrs.items():
setattr(module, key, value)
return
for key, value in attrs.items():
if not hasattr(module, key):
setattr(module, key, value)
def _encrypt_text(value: str) -> str:
return f"enc:{value}"
def _consume_captcha(captcha_id: str, code: str) -> bool:
return False
def _is_currently_locked(user) -> bool:
return False
def _record_failure(db, user) -> None:
user.failed_login_count = int(user.failed_login_count or 0) + 1
def _clear_failures(db, user) -> None:
user.failed_login_count = 0
user.locked_until = None
_install_stub("app.core.field_crypto", encrypt_text=_encrypt_text)
_install_stub("app.services.captcha", consume_captcha=_consume_captcha)
_install_stub(
"app.services.login_guard",
is_currently_locked=_is_currently_locked,
record_failure=_record_failure,
clear_failures=_clear_failures,
)
from app.api.admin.rbac import public_router, router
from app.commands.create_superuser import seed_superuser
from app.core.config import get_settings
from app.core.masking import mask_mobile
from app.core.security import create_access_token
from app.db import Base, get_db, get_engine
from app.main import create_app
from app.models.rbac import AdminResource, AdminRole, AdminRoleResource, AdminUser, AdminUserRole, utcnow
from app.services.rbac import count_full_admins, preserve_full_admin
get_settings.cache_clear()
def _safe_error(exc: Exception) -> str:
raw = str(exc).splitlines()[0] if str(exc) else ""
raw = re.sub(r"://\S+", "://***", raw)
raw = re.sub(r"password=\S+", "password=***", raw, flags=re.I)
return f"{exc.__class__.__name__}: {raw[:180]}"
def _database_url() -> str:
get_settings.cache_clear()
return get_settings().database_url.strip()
def _suffix(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex[:10]}"
def _staff_headers(subject: str = "1") -> dict[str, str]:
token = create_access_token(subject, "staff")
return {"Authorization": f"Bearer {token}"}
def _mount(app) -> None:
paths = {getattr(route, "path", "") for route in app.routes}
if "/api/admin/users" not in paths:
app.include_router(public_router, prefix="/api/admin")
app.include_router(router, prefix="/api/admin")
def _committed(username: str) -> bool:
other = Session(bind=get_engine())
try:
found = other.scalar(select(AdminUser.id).where(AdminUser.username == username))
return found is not None
finally:
other.close()
def _delete_committed_user(username: str) -> None:
other = Session(bind=get_engine())
try:
row = other.scalar(select(AdminUser).where(AdminUser.username == username))
if row is None:
return
other.execute(delete(AdminUserRole).where(AdminUserRole.user_id == row.id))
other.delete(row)
other.commit()
finally:
other.close()
def _assert_isolated(connection, username: str) -> None:
probe = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
now = utcnow()
probe.add(
AdminUser(
username=username,
password_hash="probe",
display_name="probe",
mobile_mask="",
status="active",
failed_login_count=0,
created_at=now,
updated_at=now,
)
)
probe.commit()
probe.close()
if _committed(username):
_delete_committed_user(username)
pytest.fail("测试事务没有隔离,已停止,避免改动已有数据")
@pytest.fixture
def client():
if not _database_url():
pytest.skip("DATABASE_URL 未配置")
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
get_settings.cache_clear()
try:
engine = get_engine()
with engine.connect() as probe:
probe.execute(text("SELECT 1"))
Base.metadata.create_all(bind=engine)
except Exception as exc:
pytest.skip(f"数据库不可用:{_safe_error(exc)}")
connection = engine.connect()
transaction = connection.begin()
probe_name = _suffix("probe")
try:
_assert_isolated(connection, probe_name)
app = create_app()
_mount(app)
app.state.connection = connection
def override_db():
db = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_db
with TestClient(app) as test_client:
yield test_client
finally:
try:
transaction.rollback()
except Exception:
pass
connection.close()
def _walk(nodes: list[dict]):
for node in nodes:
yield node
yield from _walk(node.get("children") or [])
def _no_password(payload) -> None:
if isinstance(payload, dict):
for key, value in payload.items():
assert "password" not in key.lower()
assert key not in {"mobileCipher", "mobile_cipher", "password_hash"}
_no_password(value)
elif isinstance(payload, list):
for item in payload:
_no_password(item)
def test_users_requires_staff_token(client: TestClient):
missing = client.get("/api/admin/users")
assert missing.status_code == 401
member = create_access_token("member-1", "member")
rejected = client.get("/api/admin/users", headers={"Authorization": f"Bearer {member}"})
assert rejected.status_code == 403
def test_weak_password_rejected(client: TestClient):
headers = _staff_headers()
username = _suffix("weak")
response = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": "abcdefgh",
"displayName": "弱密码",
"roleIds": [],
},
)
assert response.status_code == 400
assert response.json()["detail"] == PASSWORD_RULE
digits = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": "12345678",
"displayName": "弱密码",
"roleIds": [],
},
)
assert digits.status_code == 400
assert digits.json()["detail"] == PASSWORD_RULE
def test_cannot_cancel_self(client: TestClient):
headers = _staff_headers("0")
username = _suffix("self")
created = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": "Abcdef12",
"displayName": "本人",
"roleIds": [],
},
)
assert created.status_code == 200
user_id = created.json()["id"]
own = _staff_headers(str(user_id))
cancelled = client.put(
f"/api/admin/users/{user_id}",
headers=own,
json={"displayName": "本人", "status": "cancelled", "roleIds": []},
)
assert cancelled.status_code == 400
assert cancelled.json()["detail"] == KEEP_SELF
listed = client.get("/api/admin/users", headers=headers, params={"username": username})
assert listed.status_code == 200
record = next(item for item in listed.json()["records"] if item["username"] == username)
assert record["status"] == "active"
def test_user_list_masks_mobile_and_hides_password(client: TestClient, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr("app.services.rbac.encrypt_text", lambda value: "cipher-text")
headers = _staff_headers()
username = _suffix("mobile")
mobile = "13812348000"
password = "Abcdef12"
created = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": password,
"displayName": "脱敏",
"mobile": mobile,
"roleIds": [],
},
)
assert created.status_code == 200
created_body = created.json()
assert created_body["mobileMask"] == mask_mobile(mobile) == "138****8000"
_no_password(created_body)
assert mobile not in created.text
assert password not in created.text
assert "cipher-text" not in created.text
listed = client.get("/api/admin/users", headers=headers, params={"username": username})
assert listed.status_code == 200
body = listed.json()
record = next(item for item in body["records"] if item["username"] == username)
assert record["mobileMask"] == "138****8000"
assert set(record) >= {
"id",
"username",
"displayName",
"mobileMask",
"status",
"roleIds",
"createdAt",
"updatedAt",
}
_no_password(body)
assert mobile not in listed.text
assert password not in listed.text
assert "cipher-text" not in listed.text
assert not _committed(username)
def test_login_hides_reason(client: TestClient, monkeypatch: pytest.MonkeyPatch):
failures: list[int] = []
clears: list[int] = []
def consume(captcha_id: str, code: str) -> bool:
return code == "ok"
def record(db, user) -> None:
failures.append(user.id)
def clear(db, user) -> None:
clears.append(user.id)
user.failed_login_count = 0
user.locked_until = None
locked = {"value": False}
monkeypatch.setattr("app.services.rbac.consume_captcha", consume)
monkeypatch.setattr("app.services.rbac.record_failure", record)
monkeypatch.setattr("app.services.rbac.clear_failures", clear)
monkeypatch.setattr("app.services.rbac.is_currently_locked", lambda user: locked["value"])
headers = _staff_headers()
username = _suffix("login")
password = "Abcdef12"
created = client.post(
"/api/admin/users",
headers=headers,
json={"username": username, "password": password, "displayName": "登录", "roleIds": []},
)
assert created.status_code == 200
missing_user = client.post(
"/api/admin/auth/login",
json={"username": _suffix("none"), "password": password, "captchaId": "c1", "captchaCode": "ok"},
)
assert missing_user.status_code == 401
assert missing_user.json()["detail"] == LOGIN_FAILURE
assert failures == []
bad_captcha = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": "c1", "captchaCode": "bad"},
)
assert bad_captcha.status_code == 401
assert bad_captcha.json()["detail"] == LOGIN_FAILURE
assert len(failures) == 1
bad_password = client.post(
"/api/admin/auth/login",
json={"username": username, "password": "Wrongpass1", "captchaId": "c1", "captchaCode": "ok"},
)
assert bad_password.status_code == 401
assert bad_password.json()["detail"] == LOGIN_FAILURE
assert len(failures) == 2
locked["value"] = True
locked_response = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": "c1", "captchaCode": "ok"},
)
assert locked_response.status_code == 401
assert locked_response.json()["detail"] == LOGIN_FAILURE
assert len(failures) == 2
locked["value"] = False
success = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": "c1", "captchaCode": "ok"},
)
assert success.status_code == 200
payload = success.json()
assert payload["user"]["username"] == username
assert payload["user"]["displayName"] == "登录"
assert isinstance(payload["menus"], list)
assert isinstance(payload["permissions"], list)
assert payload["token"]
_no_password(payload)
assert clears == [created.json()["id"]]
def test_login_menu_excludes_buttons(client: TestClient, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr("app.services.rbac.consume_captcha", lambda captcha_id, code: True)
monkeypatch.setattr("app.services.rbac.is_currently_locked", lambda user: False)
monkeypatch.setattr("app.services.rbac.record_failure", lambda db, user: None)
monkeypatch.setattr("app.services.rbac.clear_failures", lambda db, user: None)
headers = _staff_headers()
mark = uuid.uuid4().hex[:8]
directory = client.post(
"/api/admin/resources",
headers=headers,
json={
"type": "directory",
"name": f"Dir{mark}",
"title": "目录",
"path": f"/t-{mark}",
"sort": 2,
"visible": True,
"status": "active",
},
)
assert directory.status_code == 200
directory_id = directory.json()["id"]
later = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": directory_id,
"type": "menu",
"name": f"Later{mark}",
"title": "后",
"path": f"/t-{mark}/later",
"component": f"/t-{mark}/later",
"sort": 2,
"status": "active",
},
)
earlier = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": directory_id,
"type": "menu",
"name": f"Early{mark}",
"title": "先",
"path": f"/t-{mark}/early",
"component": f"/t-{mark}/early",
"sort": 1,
"status": "active",
},
)
hidden = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": directory_id,
"type": "menu",
"name": f"Off{mark}",
"title": "停用页",
"path": f"/t-{mark}/off",
"component": f"/t-{mark}/off",
"sort": 3,
"status": "disabled",
},
)
button_z = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": earlier.json()["id"],
"type": "button",
"name": f"b:z:{mark}",
"title": "乙",
"permission": f"b:z:{mark}",
"visible": False,
"status": "active",
},
)
button_a = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": earlier.json()["id"],
"type": "button",
"name": f"b:a:{mark}",
"title": "甲",
"permission": f"b:a:{mark}",
"visible": False,
"status": "active",
},
)
assert later.status_code == earlier.status_code == hidden.status_code == 200
assert button_z.status_code == button_a.status_code == 200
role = client.post(
"/api/admin/roles",
headers=headers,
json={"code": f"R_{mark}", "name": "菜单角色", "description": ""},
)
assert role.status_code == 200
role_id = role.json()["id"]
disabled_role = client.post(
"/api/admin/roles",
headers=headers,
json={"code": f"R_OFF_{mark}", "name": "停用角色"},
)
assert disabled_role.status_code == 200
resource_ids = [
directory_id,
later.json()["id"],
earlier.json()["id"],
button_a.json()["id"],
button_z.json()["id"],
]
replaced = client.put(
f"/api/admin/roles/{role_id}/resources",
headers=headers,
json={"resourceIds": resource_ids},
)
assert replaced.status_code == 200
client.put(
f"/api/admin/roles/{disabled_role.json()['id']}",
headers=headers,
json={"name": "停用角色", "description": "", "status": "disabled"},
)
extra_button = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": earlier.json()["id"],
"type": "button",
"name": f"b:off:{mark}",
"title": "停用角色按钮",
"permission": f"b:off:{mark}",
"visible": False,
"status": "active",
},
)
client.put(
f"/api/admin/roles/{disabled_role.json()['id']}/resources",
headers=headers,
json={"resourceIds": [extra_button.json()["id"]]},
)
username = _suffix("menu")
created = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": "Abcdef12",
"displayName": "菜单",
"roleIds": [role_id, disabled_role.json()["id"]],
},
)
assert created.status_code == 200
logged = client.post(
"/api/admin/auth/login",
json={"username": username, "password": "Abcdef12", "captchaId": "c", "captchaCode": "1"},
)
assert logged.status_code == 200
body = logged.json()
nodes = list(_walk(body["menus"]))
assert [node["type"] for node in nodes if node["type"] == "button"] == []
titles = [node["title"] for node in nodes]
assert "停用页" not in titles
children = body["menus"][0]["children"]
assert [item["sort"] for item in children] == [1, 2]
assert body["permissions"] == [f"b:a:{mark}", f"b:z:{mark}"]
assert f"b:off:{mark}" not in body["permissions"]
def test_delete_resource_with_children(client: TestClient):
headers = _staff_headers()
mark = uuid.uuid4().hex[:8]
parent = client.post(
"/api/admin/resources",
headers=headers,
json={"type": "directory", "name": f"P{mark}", "title": "父", "sort": 1, "status": "active"},
)
assert parent.status_code == 200
child = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": parent.json()["id"],
"type": "menu",
"name": f"C{mark}",
"title": "子",
"path": f"/c-{mark}",
"component": f"/c-{mark}",
"status": "active",
},
)
assert child.status_code == 200
denied = client.delete(f"/api/admin/resources/{parent.json()['id']}", headers=headers)
assert denied.status_code == 400
assert denied.json()["detail"] == "存在子节点,不能删除"
removed = client.delete(f"/api/admin/resources/{child.json()['id']}", headers=headers)
assert removed.status_code == 200
removed_parent = client.delete(f"/api/admin/resources/{parent.json()['id']}", headers=headers)
assert removed_parent.status_code == 200
def test_preserve_last_full_admin(client: TestClient):
connection = client.app.state.connection
db = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
nested = db.begin_nested()
try:
db.execute(update(AdminUser).values(status="disabled"))
db.flush()
db.expire_all()
assert count_full_admins(db) == 0
def make_user(tag: str) -> AdminUser:
now = utcnow()
role = AdminRole(code=_suffix("RF"), name=tag, status="active", created_at=now, updated_at=now)
user = AdminUser(
username=_suffix(tag),
password_hash="x",
display_name=tag,
mobile_mask="",
status="active",
failed_login_count=0,
created_at=now,
updated_at=now,
)
db.add_all([role, user])
db.flush()
for resource_id in db.scalars(select(AdminResource.id).where(AdminResource.status == "active")).all():
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.add(AdminUserRole(user_id=user.id, role_id=role.id))
db.flush()
return user
first = make_user("fulla")
second = make_user("fullb")
db.expire_all()
assert count_full_admins(db) == 2
def disable_first() -> None:
row = db.get(AdminUser, first.id)
assert row is not None
row.status = "disabled"
preserve_full_admin(db, disable_first)
db.expire_all()
assert count_full_admins(db) == 1
def disable_last() -> None:
row = db.get(AdminUser, second.id)
assert row is not None
row.status = "disabled"
with pytest.raises(HTTPException) as caught:
preserve_full_admin(db, disable_last)
assert caught.value.detail == KEEP_FULL_ADMIN
finally:
nested.rollback()
db.close()
def test_seed_superuser_is_idempotent(client: TestClient):
connection = client.app.state.connection
db = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
username = _suffix("boot")
try:
seed_superuser(db, username, "Seedpass1")
seed_superuser(db, username, "Seedpass1")
db.commit()
users = db.scalars(select(AdminUser).where(AdminUser.username == username)).all()
assert len(users) == 1
role = db.scalar(select(AdminRole).where(AdminRole.code == "R_SUPER"))
assert role is not None
assert role.name == "超级管理员"
directory = db.scalar(
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "System")
)
assert directory is not None
assert directory.path == "/system"
assert directory.icon == "ri:settings-3-line"
page = db.scalar(select(AdminResource).where(AdminResource.parent_id == directory.id, AdminResource.name == "User"))
assert page is not None
assert page.component == "/system/user"
button = db.scalar(
select(AdminResource).where(AdminResource.parent_id == page.id, AdminResource.name == "user:add")
)
assert button is not None
assert button.type == "button"
assert button.permission == "user:add"
assert button.visible is False
linked = db.get(AdminUserRole, (users[0].id, role.id))
assert linked is not None
finally:
db.close()
assert not _committed(username)
+173
View File
@@ -0,0 +1,173 @@
"""报告备案对照,以及首页报告查询、报告审核固定打开站内页。"""
from uuid import uuid4
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
FOUND = "以出具机构数据为准,协会结果仅供参考。"
MISSING = "协会备案库没有该编号,请向出具机构核实。"
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _filing(number: str, *, published: bool, institution: str = "兰州示例估价") -> dict:
return {
"institutionName": institution,
"reportNumber": number,
"issuedOn": "2026-03-18",
"published": published,
}
def test_public_query_reads_only_published_filings(client: TestClient):
staff = _headers("staff")
member = _headers("member")
number = f"GS-{uuid4().hex[:10]}"
other = f"GS-{uuid4().hex[:10]}"
filing_id = None
other_id = None
try:
body = _filing(f" {number} ", published=False, institution=" 兰州示例估价 ")
assert client.post("/api/admin/reports", json=body).status_code == 401
assert client.post("/api/admin/reports", headers=member, json=body).status_code == 403
created = client.post("/api/admin/reports", headers=staff, json=body)
assert created.status_code == 200, created.text
filing_id = created.json()["id"]
hidden = client.get("/api/site/reports/query", params={"number": number})
assert hidden.status_code == 200, hidden.text
assert hidden.json() == {"found": False, "notice": MISSING}
assert "兰州示例估价" not in hidden.text
assert "真" not in hidden.text
assert "伪" not in hidden.text
published = client.put(
f"/api/admin/reports/{filing_id}",
headers=staff,
json=_filing(number, published=True),
)
assert published.status_code == 200, published.text
found = client.get("/api/site/reports/query", params={"number": number})
assert found.json() == {
"found": True,
"institutionName": "兰州示例估价",
"reportNumber": number,
"issuedOn": "2026-03-18",
"notice": FOUND,
}
assert "真" not in found.text
assert "伪" not in found.text
duplicate = client.post("/api/admin/reports", headers=staff, json=_filing(number, published=True))
assert duplicate.status_code == 400
assert duplicate.json()["detail"] == "报告编号已存在"
second = client.post("/api/admin/reports", headers=staff, json=_filing(other, published=True))
assert second.status_code == 200, second.text
other_id = second.json()["id"]
clash = client.put(
f"/api/admin/reports/{filing_id}",
headers=staff,
json=_filing(other, published=True),
)
assert clash.status_code == 400
assert clash.json()["detail"] == "报告编号已存在"
blank = client.get("/api/site/reports/query", params={"number": " "})
assert blank.status_code == 400
assert blank.json()["detail"] == "请填写报告编号"
listed = client.get("/api/admin/reports", headers=staff)
assert listed.status_code == 200
assert any(item["id"] == filing_id and item["published"] is True for item in listed.json()["items"])
assert client.get("/api/admin/reports", headers=member).status_code == 403
finally:
for item_id in (filing_id, other_id):
if item_id is not None:
client.delete(f"/api/admin/reports/{item_id}", headers=staff)
gone = client.get("/api/site/reports/query", params={"number": number})
assert gone.json()["found"] is False
def test_hot_links_open_report_pages_on_site(client: TestClient):
staff = _headers("staff")
before = client.get("/api/admin/home", headers=staff).json()["hotLinks"]["links"]
hidden = [
{"key": "reportQuery", "label": "报告查询", "url": "/reports/query", "visible": False, "sortOrder": 0},
{"key": "reportReview", "label": "报告审核", "url": "/reports/review", "visible": False, "sortOrder": 1},
{"key": "complaint", "label": "投诉举报", "url": "", "visible": False, "sortOrder": 2},
]
try:
saved = client.put(
"/api/admin/home/hot-links",
headers=staff,
json={
"links": [
{
"key": "reportReview",
"label": "辅助审核",
"url": "https://example.com/review",
"visible": True,
"sortOrder": 0,
},
{
"key": "complaint",
"label": "投诉举报",
"url": "https://example.com/complaint",
"visible": True,
"sortOrder": 1,
},
{
"key": "reportQuery",
"label": "查备案",
"url": "https://example.com/report-check",
"visible": True,
"sortOrder": 2,
},
]
},
)
assert saved.status_code == 200, saved.text
home = client.get("/api/site/home")
assert home.json()["hotLinks"]["links"] == [
{"label": "辅助审核", "url": "/reports/review", "navigation": "sameWindow"},
{"label": "投诉举报", "url": "https://example.com/complaint", "navigation": "newWindow"},
{"label": "查备案", "url": "/reports/query", "navigation": "sameWindow"},
]
assert "example.com/report-check" not in home.text
assert "example.com/review" not in home.text
rejected = client.put(
"/api/admin/home/hot-links",
headers=staff,
json={"links": [{"key": "reportQuery", "label": "报告查询", "url": "/reports/query", "visible": True, "sortOrder": 0}]},
)
assert rejected.status_code == 400
cleared = client.put("/api/admin/home/hot-links", headers=staff, json={"links": hidden})
assert cleared.status_code == 200, cleared.text
assert client.get("/api/site/home").json()["hotLinks"]["placeholder"] == "报告查询、报告审核与投诉举报入口即将开放"
finally:
restore = before or hidden
client.put("/api/admin/home/hot-links", headers=staff, json={"links": restore})
+228
View File
@@ -0,0 +1,228 @@
import base64
import inspect
from datetime import datetime, timedelta, timezone
import pytest
def test_captcha_missing_wrong_and_second_use():
from app.services.captcha import CAPTCHA_ALPHABET, consume_captcha, issue_captcha
from app.services.redis_client import get_redis
assert consume_captcha("", "ab12") is False
assert consume_captcha("missing-id", "") is False
assert consume_captcha("", "") is False
try:
client = get_redis()
client.ping()
except Exception:
pytest.skip("Redis 不可达")
wrong = issue_captcha()
wrong_id = wrong["captchaId"]
assert wrong["image"].startswith("data:image/png;base64,")
raw = base64.b64decode(wrong["image"].split(",", 1)[1])
assert raw.startswith(b"\x89PNG")
stored = client.get(f"gsfdc:captcha:{wrong_id}")
assert isinstance(stored, str)
assert len(stored) == 4
assert set(stored).issubset(set(CAPTCHA_ALPHABET.lower()))
ttl = client.ttl(f"gsfdc:captcha:{wrong_id}")
assert 0 < ttl <= 120
assert consume_captcha(wrong_id, "0000") is False
assert client.get(f"gsfdc:captcha:{wrong_id}") is None
assert consume_captcha(wrong_id, stored) is False
ok = issue_captcha()
ok_id = ok["captchaId"]
stored_ok = client.get(f"gsfdc:captcha:{ok_id}")
assert consume_captcha(ok_id, stored_ok.upper()) is True
assert consume_captcha(ok_id, stored_ok) is False
def test_is_currently_locked_respects_utc_and_does_not_mutate():
from types import SimpleNamespace
from app.services.login_guard import is_currently_locked
user = SimpleNamespace(failed_login_count=2, locked_until=None)
assert is_currently_locked(user) is False
assert user.failed_login_count == 2
user.locked_until = datetime.now(timezone.utc) + timedelta(minutes=1)
assert is_currently_locked(user) is True
assert user.failed_login_count == 2
user.locked_until = datetime.now(timezone.utc) - timedelta(seconds=1)
assert is_currently_locked(user) is False
user.locked_until = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(seconds=1)
assert is_currently_locked(user) is False
assert user.failed_login_count == 2
def test_lock_after_small_limit_and_past_deadline():
pytest.importorskip("app.db")
pytest.importorskip("app.models.content")
pytest.importorskip("app.models.rbac")
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.models.content import SiteSetting
from app.models.rbac import AdminUser
from app.services.login_guard import is_currently_locked, read_login_policy, record_failure
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
SiteSetting.__table__.create(engine)
AdminUser.__table__.create(engine)
db = sessionmaker(bind=engine, expire_on_commit=False)()
try:
assert read_login_policy(db) == (5, 15)
db.add(SiteSetting(key="login_max_failures", value="2"))
db.add(SiteSetting(key="login_lock_minutes", value="3"))
db.commit()
user = _new_user(AdminUser, "sec-lock-test")
db.add(user)
db.commit()
db.refresh(user)
assert is_currently_locked(user) is False
record_failure(db, user)
assert user.failed_login_count == 1
assert user.locked_until is None
assert is_currently_locked(user) is False
assert user.failed_login_count == 1
record_failure(db, user)
assert user.failed_login_count == 0
assert user.locked_until is not None
locked_until = user.locked_until
if locked_until.tzinfo is not None:
locked_until = locked_until.astimezone(timezone.utc).replace(tzinfo=None)
delta = locked_until - datetime.now(timezone.utc).replace(tzinfo=None)
assert timedelta(minutes=2) < delta < timedelta(minutes=4)
assert is_currently_locked(user) is True
assert user.failed_login_count == 0
user.locked_until = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(seconds=30)
db.add(user)
db.commit()
db.refresh(user)
assert is_currently_locked(user) is False
assert user.failed_login_count == 0
finally:
db.close()
def test_write_audit_does_not_accept_secret_fields():
from app.services.audit import write_audit
signature = inspect.signature(write_audit)
names = list(signature.parameters)
assert names == ["user_id", "username", "method", "path", "status_code", "ip"]
for parameter in signature.parameters.values():
assert parameter.kind is inspect.Parameter.KEYWORD_ONLY
banned = {"body", "password", "captcha", "captcha_id", "id_card", "mobile", "phone"}
assert banned.isdisjoint(names)
with pytest.raises(TypeError):
write_audit(
user_id=None,
username=None,
method="POST",
path="/api/admin/auth/login",
status_code=400,
ip="127.0.0.1",
body="x",
)
with pytest.raises(TypeError):
write_audit(
user_id=None,
username=None,
method="POST",
path="/api/admin/auth/login",
status_code=400,
ip="127.0.0.1",
password="x",
)
with pytest.raises(TypeError):
write_audit(
user_id=None,
username=None,
method="POST",
path="/api/admin/auth/login",
status_code=400,
ip="127.0.0.1",
captcha="x",
)
def test_ip_blacklist_blocks_then_unblocks():
from app.core.config import get_settings
if not (get_settings().database_url or "").strip():
pytest.skip("DATABASE_URL 为空")
from sqlalchemy import delete
from app.db import SessionLocal
from app.models.security import AdminIpBlacklist
from app.services.ip_guard import is_ip_blocked
test_ip = "203.0.113.214"
db = SessionLocal()
try:
AdminIpBlacklist.__table__.create(db.get_bind(), checkfirst=True)
db.execute(delete(AdminIpBlacklist).where(AdminIpBlacklist.ip == test_ip))
db.commit()
assert is_ip_blocked(test_ip) is False
db.add(AdminIpBlacklist(ip=test_ip, remark="security-test"))
db.commit()
assert is_ip_blocked(test_ip) is True
db.execute(delete(AdminIpBlacklist).where(AdminIpBlacklist.ip == test_ip))
db.commit()
assert is_ip_blocked(test_ip) is False
finally:
try:
db.rollback()
db.execute(delete(AdminIpBlacklist).where(AdminIpBlacklist.ip == test_ip))
db.commit()
except Exception:
db.rollback()
finally:
db.close()
def _new_user(model, username: str):
user = model()
if hasattr(user, "username"):
user.username = username
if hasattr(user, "status"):
user.status = "active"
if hasattr(user, "failed_login_count"):
user.failed_login_count = 0
if hasattr(user, "locked_until"):
user.locked_until = None
if hasattr(user, "display_name"):
user.display_name = "lock-test"
if hasattr(user, "password_hash"):
user.password_hash = "test-only-hash"
for column in user.__table__.columns:
if column.primary_key or column.nullable:
continue
if column.default is not None or column.server_default is not None:
continue
if getattr(user, column.key) is not None:
continue
try:
kind = column.type.python_type
except Exception:
kind = str
setattr(user, column.key, 0 if kind is int else "test")
return user
+223
View File
@@ -0,0 +1,223 @@
"""技术交流两类栏目文章:工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_category(client, staff: dict[str, str], category: str) -> None:
listed = client.get(f"/api/admin/about/articles/{category}", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def test_tech_exchange_publish_filter_placeholder_cover_and_pagination(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
for category in ("tech_seminars", "tech_exchange"):
_clear_category(client, staff, category)
empty_seminars = client.get("/api/site/about/articles/tech_seminars")
assert empty_seminars.status_code == 200, empty_seminars.text
assert "暂无技术研讨" in empty_seminars.text
assert "暂无技术交流" in client.get("/api/site/about/articles/tech_exchange").text
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("研讨通知.pdf", b"%PDF-1.4\nnotice", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
award = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("获奖名单公示.pdf", b"%PDF-1.4\nawards", "application/pdf")},
)
assert award.status_code == 200, award.text
file_ids.append(award.json()["id"])
seminar = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "tech_seminars",
"title": "城市更新中的房地产估价服务专题研讨",
"publishedAt": "2025-11-08T08:00:00",
"published": True,
"bodyHtml": "<p>城市更新研讨</p><script>alert(1)</script>",
"imageFileId": file_ids[0],
"attachmentFileIds": [file_ids[1]],
},
)
assert seminar.status_code == 200, seminar.text
article_ids.append(seminar.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "tech_seminars",
"title": "内部筹备研讨",
"publishedAt": "2025-11-09T08:00:00",
"published": False,
"bodyHtml": "<p>内部</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
exchange = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "tech_exchange",
"title": "2018年度优秀报告评选表彰与实践分享(公示)",
"publishedAt": "2019-04-26T08:00:00",
"published": True,
"bodyHtml": "<p>优秀报告公示</p>",
"attachmentFileIds": [file_ids[2]],
},
)
assert exchange.status_code == 200, exchange.text
article_ids.append(exchange.json()["id"])
seminars = client.get("/api/site/about/articles/tech_seminars")
assert seminars.status_code == 200, seminars.text
assert "城市更新中的房地产估价服务专题研讨" in seminars.text
assert "内部筹备研讨" not in seminars.text
assert seminars.json()["items"][0].get("imageUrl")
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
body = detail.json()["bodyHtml"].lower()
assert "城市更新研讨" in detail.json()["bodyHtml"]
assert "script" not in body
assert "alert" not in body
assert detail.json().get("imageUrl")
assert [item["filename"] for item in detail.json()["attachments"]] == ["研讨通知.pdf"]
hidden = client.get(f"/api/site/home/articles/{article_ids[1]}")
assert hidden.status_code == 404
exchanges = client.get("/api/site/about/articles/tech_exchange")
assert exchanges.status_code == 200, exchanges.text
assert "2018年度优秀报告评选表彰与实践分享(公示)" in exchanges.text
exchange_detail = client.get(f"/api/site/home/articles/{article_ids[2]}")
assert exchange_detail.status_code == 200, exchange_detail.text
assert [item["filename"] for item in exchange_detail.json()["attachments"]] == ["获奖名单公示.pdf"]
for index in range(10):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "tech_seminars",
"title": f"研讨分页样例-{index:02d}",
"publishedAt": f"2025-01-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>研讨分页样例-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/tech_seminars?current=1&size=10")
assert page1.status_code == 200, page1.text
assert page1.json()["total"] == 11
assert page1.json()["size"] == 10
assert len(page1.json()["items"]) == 10
page2 = client.get("/api/site/about/articles/tech_seminars?current=2&size=10")
assert page2.status_code == 200, page2.text
assert len(page2.json()["items"]) == 1
size20 = client.get("/api/site/about/articles/tech_seminars?current=1&size=20")
assert size20.json()["size"] == 20
assert len(size20.json()["items"]) == 11
bad_size = client.get("/api/site/about/articles/tech_seminars?current=1&size=15")
assert bad_size.json()["size"] == 10
home = client.get("/api/admin/home", headers=staff)
assert home.status_code == 200, home.text
categories = {item["category"] for item in home.json()["articles"]}
assert "tech_seminars" not in categories
assert "tech_exchange" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "tech_seminars",
"title": "会员不得发布研讨",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员不得发布研讨" not in client.get("/api/site/about/articles/tech_seminars").text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+673
View File
@@ -0,0 +1,673 @@
"""上传案例:会员提交住宅,管理端只读,不进案例库文章。"""
import time
from datetime import date
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
from app.services.email_code import _key
from app.services.redis_client import get_redis
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
monkeypatch.setenv("SMTP_HOST", "")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
try:
get_redis().ping()
except Exception:
pytest.skip("Redis 不可达")
monkeypatch.setattr("app.services.email_code.send_email", lambda **kwargs: None)
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def _code(purpose: str, email: str) -> str:
stored = get_redis().get(_key(purpose, email))
assert stored is not None
if isinstance(stored, bytes):
stored = stored.decode("utf-8")
return stored
def _register(client, email: str) -> str:
assert client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"}).status_code == 200
registered = client.post(
"/api/site/auth/register",
json={"email": email, "code": _code("register", email), "password": "Passw0rd1", "privacyAccepted": True},
)
assert registered.status_code == 200, registered.text
return registered.json()["accessToken"]
def _commercial_payload(estate: str, **overrides) -> dict:
body = {
"kind": "commercial",
"caseType": "拍卖成交",
"province": "甘肃省",
"city": "兰州市",
"district": "城关区",
"estateName": estate,
"structure": "砖混",
"caseDate": "2025-06-01",
"location": "张掖路 8 号",
"builtYear": date.today().year,
"totalFloors": "6",
"floorNo": "1",
"layout": "大开间",
"decoration": "高档",
"streetFrontage": "单面临街",
"area": "120",
"orientation": "南",
"footTraffic": "一般",
"shopType": "住宅底商",
"businessFormats": ["餐饮"],
"unitPrice": "80",
"valueIncludes": [],
"remark": "",
"institutionName": "甘肃示例评估",
"photoFileIds": [],
}
body.update(overrides)
return body
def _payload(estate: str, **overrides) -> dict:
body = {
"kind": "residential",
"caseType": "买卖成交",
"province": "甘肃省",
"city": "兰州市",
"district": "城关区",
"estateName": estate,
"structure": "钢混",
"caseDate": "2025-08-16",
"location": "张掖路 1 号",
"builtYear": date.today().year,
"totalFloors": "18",
"floorNo": "-1",
"purpose": "普通住宅",
"layoutStructure": "平面",
"decoration": "中档",
"valueIncludes": ["装饰装修"],
"area": "88.5",
"layout": "两室一厅",
"orientation": "南北",
"unitPrice": "12000",
"remark": "一层带院",
"institutionName": "甘肃示例评估",
"photoFileIds": [],
}
body.update(overrides)
return body
def test_residential_upload_is_private_and_admin_readable(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
email = f"case-{int(time.time() * 1000)}@example.com"
token = _register(client, email)
headers = {"Authorization": f"Bearer {token}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
estate = f"上传案例样例-{int(time.time())}"
created_ids: list[int] = []
options = client.get("/api/site/uploaded-case-options")
assert options.status_code == 200, options.text
assert date.today().year in options.json()["residential"]["builtYears"]
assert 1979 not in options.json()["residential"]["builtYears"]
assert any(item["name"] == "甘肃省" for item in options.json()["regions"])
denied = client.post("/api/site/member/uploaded-cases", json=_payload(estate))
assert denied.status_code == 401
staff_submit = client.post("/api/site/member/uploaded-cases", headers=staff, json=_payload(estate))
assert staff_submit.status_code == 403
uploaded = client.post(
"/api/site/member/files",
headers=headers,
files={"file": ("位置图.png", _png(), "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
photo_id = uploaded.json()["id"]
missing = client.post("/api/site/member/uploaded-cases", headers=headers, json=_payload(estate, photoFileIds=[]))
assert missing.status_code == 400
assert "照片" in missing.text
bad_year = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, builtYear=1979, photoFileIds=[photo_id]),
)
assert bad_year.status_code == 400
assert "建筑年代" in bad_year.text
bad_region = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, city="天水市", photoFileIds=[photo_id]),
)
assert bad_region.status_code == 400
closed = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, kind="other", photoFileIds=[photo_id]),
)
assert closed.status_code == 400
assert "案例种类不正确" in closed.text
me = client.get("/api/site/member/me", headers=headers)
member_id = me.json()["id"]
from app.db import SessionLocal
from app.models.content import AdminFile
db = SessionLocal()
try:
huge = AdminFile(
bucket="private",
object_key="tests/huge-photo",
filename="过大.png",
content_type="image/png",
size=5 * 1024 * 1024 + 1,
created_by=member_id,
)
db.add(huge)
db.commit()
db.refresh(huge)
huge_id = huge.id
finally:
db.close()
too_big = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, photoFileIds=[huge_id]),
)
assert too_big.status_code == 400
assert "5MB" in too_big.text
created = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, photoFileIds=[photo_id]),
)
assert created.status_code == 200, created.text
assert created.json()["message"] == "提交成功"
case_id = created.json()["id"]
created_ids.append(case_id)
second = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate + "-新", photoFileIds=[photo_id]),
)
assert second.status_code == 200, second.text
created_ids.append(second.json()["id"])
hidden = client.get("/api/site/member/uploaded-cases", headers=headers)
assert hidden.status_code in (404, 405)
public = client.get("/api/site/about/articles/case_library")
assert estate not in public.text
searched = client.get("/api/site/about/articles/case_library", params={"q": estate})
assert estate not in searched.text
member_admin = client.get("/api/admin/uploaded-cases", headers=headers)
assert member_admin.status_code == 403
member_detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=headers)
assert member_detail.status_code == 403
listed = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "residential"})
assert listed.status_code == 200, listed.text
names = [item["estateName"] for item in listed.json()["items"]]
assert names.index(estate + "-新") < names.index(estate)
newer = listed.json()["items"][names.index(estate + "-新")]
assert newer["memberEmail"] == email
older = next(item for item in listed.json()["items"] if item["estateName"] == estate)
assert "城关区" in older["address"]
matched = client.get(
"/api/admin/uploaded-cases",
headers=staff,
params={"kind": "residential", "q": estate + "-新"},
)
assert matched.status_code == 200, matched.text
matched_names = [item["estateName"] for item in matched.json()["items"]]
assert matched_names == [estate + "-新"]
by_email = client.get(
"/api/admin/uploaded-cases",
headers=staff,
params={"kind": "residential", "q": email},
)
assert by_email.status_code == 200, by_email.text
assert {item["estateName"] for item in by_email.json()["items"]} >= {estate, estate + "-新"}
wildcard = client.get(
"/api/admin/uploaded-cases",
headers=staff,
params={"kind": "residential", "q": "%"},
)
assert wildcard.status_code == 200, wildcard.text
assert estate not in [item["estateName"] for item in wildcard.json()["items"]]
detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=staff)
assert detail.status_code == 200, detail.text
body = detail.json()
assert body["purpose"] == "普通住宅"
assert body["builtYear"] == date.today().year
assert body["floorNo"] == "-1"
assert body["photos"][0]["filename"] == "位置图.png"
assert body["memberEmail"] == email
other = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "commercial"})
assert other.status_code == 200
assert other.json()["items"] == []
from sqlalchemy import select
from app.models.uploaded_case import UploadedCase, UploadedCasePhoto
db = SessionLocal()
try:
for item_id in created_ids:
for photo in db.scalars(select(UploadedCasePhoto).where(UploadedCasePhoto.case_id == item_id)).all():
db.delete(photo)
row = db.get(UploadedCase, item_id)
if row is not None:
db.delete(row)
huge_row = db.get(AdminFile, huge_id)
if huge_row is not None:
db.delete(huge_row)
db.commit()
finally:
db.close()
def test_commercial_upload_stays_in_its_admin_tab(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
email = f"shop-{int(time.time() * 1000)}@example.com"
token = _register(client, email)
headers = {"Authorization": f"Bearer {token}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
estate = f"商业上传样例-{int(time.time())}"
created_ids: list[int] = []
options = client.get("/api/site/uploaded-case-options")
assert options.status_code == 200, options.text
assert "commercial" in options.json()["openKinds"]
commercial = options.json()["commercial"]
assert commercial["layouts"] == ["大开间", "隔档"]
assert "单面临街" in commercial["streetFrontages"]
assert commercial["shopTypes"][0] == "住宅底商"
assert "餐饮" in commercial["businessFormats"]
uploaded = client.post(
"/api/site/member/files",
headers=headers,
files={"file": ("商铺.png", _png(), "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
photo_id = uploaded.json()["id"]
extra = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_commercial_payload(estate, purpose="普通住宅", photoFileIds=[photo_id]),
)
assert extra.status_code == 400
assert "没有的字段" in extra.text
empty_formats = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_commercial_payload(estate, businessFormats=[], photoFileIds=[photo_id]),
)
assert empty_formats.status_code == 400
assert "经营业态" in empty_formats.text
too_many = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_commercial_payload(
estate,
businessFormats=["餐饮", "百货", "酒吧", "其他"],
photoFileIds=[photo_id],
),
)
assert too_many.status_code == 400
assert "经营业态" in too_many.text
created = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_commercial_payload(estate, businessFormats=["餐饮", "百货"], photoFileIds=[photo_id]),
)
assert created.status_code == 200, created.text
assert created.json()["message"] == "提交成功"
case_id = created.json()["id"]
created_ids.append(case_id)
hidden = client.get("/api/site/member/uploaded-cases", headers=headers)
assert hidden.status_code in (404, 405)
public = client.get("/api/site/about/articles/case_library")
assert estate not in public.text
shops = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "commercial"})
assert shops.status_code == 200, shops.text
assert any(item["estateName"] == estate and item["memberEmail"] == email for item in shops.json()["items"])
homes = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "residential"})
assert all(item["estateName"] != estate for item in homes.json()["items"])
detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=staff)
assert detail.status_code == 200, detail.text
body = detail.json()
assert body["kind"] == "commercial"
assert body["layout"] == "大开间"
assert body["streetFrontage"] == "单面临街"
assert body["footTraffic"] == "一般"
assert body["shopType"] == "住宅底商"
assert body["businessFormats"] == ["餐饮", "百货"]
assert "purpose" not in body
assert body["photos"][0]["filename"] == "商铺.png"
from sqlalchemy import select
from app.db import SessionLocal
from app.models.uploaded_case import UploadedCase, UploadedCasePhoto
db = SessionLocal()
try:
for item_id in created_ids:
for photo in db.scalars(select(UploadedCasePhoto).where(UploadedCasePhoto.case_id == item_id)).all():
db.delete(photo)
row = db.get(UploadedCase, item_id)
if row is not None:
db.delete(row)
db.commit()
finally:
db.close()
def _office_payload(estate: str, **overrides) -> dict:
body = {
"kind": "office",
"caseType": "评估案例",
"province": "甘肃省",
"city": "兰州市",
"district": "城关区",
"estateName": estate,
"structure": "钢混",
"caseDate": "2025-04-18",
"location": "东岗西路 12 号",
"builtYear": date.today().year,
"totalFloors": "22",
"floorNo": "8",
"layoutStructure": "写字楼(大开间)",
"decoration": "中档",
"area": "360",
"orientation": "东南",
"unitPrice": "45",
"valueIncludes": [],
"remark": "",
"institutionName": "甘肃示例评估",
"photoFileIds": [],
}
body.update(overrides)
return body
def test_office_upload_stays_in_its_admin_tab(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
email = f"office-{int(time.time() * 1000)}@example.com"
token = _register(client, email)
headers = {"Authorization": f"Bearer {token}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
estate = f"办公上传样例-{int(time.time())}"
created_ids: list[int] = []
options = client.get("/api/site/uploaded-case-options")
assert options.status_code == 200, options.text
assert "office" in options.json()["openKinds"]
office = options.json()["office"]
assert office["layoutStructures"] == ["办公楼(中间过道两边办公室)", "写字楼(大开间)"]
assert office["totalFloors"][-1] == "60"
assert office["floorNos"][0] == "-4"
assert "东南" in office["orientations"]
assert "layouts" not in office
uploaded = client.post(
"/api/site/member/files",
headers=headers,
files={"file": ("办公.png", _png(), "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
photo_id = uploaded.json()["id"]
extra = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_office_payload(estate, layout="大开间", photoFileIds=[photo_id]),
)
assert extra.status_code == 400
assert "没有的字段" in extra.text
created = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_office_payload(estate, photoFileIds=[photo_id]),
)
assert created.status_code == 200, created.text
assert created.json()["message"] == "提交成功"
case_id = created.json()["id"]
created_ids.append(case_id)
hidden = client.get("/api/site/member/uploaded-cases", headers=headers)
assert hidden.status_code in (404, 405)
public = client.get("/api/site/about/articles/case_library")
assert estate not in public.text
offices = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "office"})
assert offices.status_code == 200, offices.text
assert any(item["estateName"] == estate and item["memberEmail"] == email for item in offices.json()["items"])
homes = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "residential"})
assert all(item["estateName"] != estate for item in homes.json()["items"])
shops = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "commercial"})
assert all(item["estateName"] != estate for item in shops.json()["items"])
detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=staff)
assert detail.status_code == 200, detail.text
body = detail.json()
assert body["kind"] == "office"
assert body["layoutStructure"] == "写字楼(大开间)"
assert body["orientation"] == "东南"
assert body["totalFloors"] == 22
assert "layout" not in body
assert "purpose" not in body
assert "streetFrontage" not in body
assert body["photos"][0]["filename"] == "办公.png"
from sqlalchemy import select
from app.db import SessionLocal
from app.models.uploaded_case import UploadedCase, UploadedCasePhoto
db = SessionLocal()
try:
for item_id in created_ids:
for photo in db.scalars(select(UploadedCasePhoto).where(UploadedCasePhoto.case_id == item_id)).all():
db.delete(photo)
row = db.get(UploadedCase, item_id)
if row is not None:
db.delete(row)
db.commit()
finally:
db.close()
def _industrial_payload(estate: str, **overrides) -> dict:
body = {
"kind": "industrial",
"caseType": "买卖成交",
"province": "甘肃省",
"city": "兰州市",
"district": "西固区",
"estateName": estate,
"structure": "钢结构",
"caseDate": "2024-11-02",
"location": "西固工业园 3 号",
"builtYear": date.today().year,
"totalFloors": "3",
"layout": "开间",
"heading": "南北",
"decoration": "简易",
"roadFrontage": "主干道",
"area": "2400",
"orientation": "东西",
"industryType": "机械制造",
"unitPrice": "18",
"valueIncludes": ["装饰装修"],
"remark": "",
"institutionName": "甘肃示例评估",
"photoFileIds": [],
}
body.update(overrides)
return body
def test_industrial_upload_stays_in_its_admin_tab(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
email = f"plant-{int(time.time() * 1000)}@example.com"
token = _register(client, email)
headers = {"Authorization": f"Bearer {token}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
estate = f"工业上传样例-{int(time.time())}"
created_ids: list[int] = []
options = client.get("/api/site/uploaded-case-options")
assert options.status_code == 200, options.text
assert "industrial" in options.json()["openKinds"]
industrial = options.json()["industrial"]
assert industrial["totalFloors"] == [str(item) for item in range(1, 9)]
assert industrial["layouts"] == ["开间"]
assert industrial["headings"] == ["南北", "东西"]
assert industrial["orientations"] == ["南北", "东西"]
assert industrial["roadFrontages"] == ["主干道", "次干道", "街巷"]
assert industrial["industryTypes"][0] == "食品饮料加工"
assert industrial["valueIncludes"] == ["装饰装修", "家具用具"]
assert "floorNos" not in industrial
uploaded = client.post(
"/api/site/member/files",
headers=headers,
files={"file": ("厂房.png", _png(), "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
photo_id = uploaded.json()["id"]
extra = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_industrial_payload(estate, floorNo="1", photoFileIds=[photo_id]),
)
assert extra.status_code == 400
assert "没有的字段" in extra.text
too_tall = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_industrial_payload(estate, totalFloors="9", photoFileIds=[photo_id]),
)
assert too_tall.status_code == 400
assert "总层数" in too_tall.text
created = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_industrial_payload(estate, photoFileIds=[photo_id]),
)
assert created.status_code == 200, created.text
assert created.json()["message"] == "提交成功"
case_id = created.json()["id"]
created_ids.append(case_id)
hidden = client.get("/api/site/member/uploaded-cases", headers=headers)
assert hidden.status_code in (404, 405)
public = client.get("/api/site/about/articles/case_library")
assert estate not in public.text
plants = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "industrial"})
assert plants.status_code == 200, plants.text
assert any(item["estateName"] == estate and item["memberEmail"] == email for item in plants.json()["items"])
for other in ("residential", "commercial", "office"):
listed = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": other})
assert all(item["estateName"] != estate for item in listed.json()["items"])
detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=staff)
assert detail.status_code == 200, detail.text
body = detail.json()
assert body["kind"] == "industrial"
assert body["layout"] == "开间"
assert body["heading"] == "南北"
assert body["roadFrontage"] == "主干道"
assert body["orientation"] == "东西"
assert body["industryType"] == "机械制造"
assert body["totalFloors"] == 3
assert body["valueIncludes"] == ["装饰装修"]
assert "floorNo" not in body
assert "purpose" not in body
assert "streetFrontage" not in body
assert body["photos"][0]["filename"] == "厂房.png"
from sqlalchemy import select
from app.db import SessionLocal
from app.models.uploaded_case import UploadedCase, UploadedCasePhoto
db = SessionLocal()
try:
for item_id in created_ids:
for photo in db.scalars(select(UploadedCasePhoto).where(UploadedCasePhoto.case_id == item_id)).all():
db.delete(photo)
row = db.get(UploadedCase, item_id)
if row is not None:
db.delete(row)
db.commit()
finally:
db.close()