#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 端到端冒烟测试。 用 Python 而非 bash:Git Bash 在 Windows 下向 curl 传中文参数会按 GBK 转码, 导致服务端收到乱码。Python 全程 UTF-8,且 json 往返零歧义。 覆盖:认证 → 权限 → 发文 → 区块校验 → 缓存 → 互动 → 评论 → 审核 → 导出 → 搜索 → 后台 """ import json import sys import time import urllib.parse import urllib.request import urllib.error API = "http://127.0.0.1:18080" PASS = FAIL = 0 FAILURES = [] def call(method, path, body=None, token=None, raw=False): url = API + path data = None if body is not None: data = json.dumps(body, ensure_ascii=False).encode("utf-8") req = urllib.request.Request(url, data=data, method=method) if data: req.add_header("Content-Type", "application/json; charset=utf-8") if token: req.add_header("Authorization", "Bearer " + token) try: with urllib.request.urlopen(req, timeout=15) as r: payload = r.read() if raw: return r.status, payload, dict(r.headers) return r.status, json.loads(payload.decode("utf-8")), dict(r.headers) except urllib.error.HTTPError as e: payload = e.read() try: return e.code, json.loads(payload.decode("utf-8")), dict(e.headers) except Exception: return e.code, {"raw": payload.decode("utf-8", "replace")}, dict(e.headers) def ok(msg): global PASS PASS += 1 print(f" \033[32m✓\033[0m {msg}") def bad(msg, detail=""): global FAIL FAIL += 1 FAILURES.append((msg, detail)) print(f" \033[31m✗\033[0m {msg}") if detail: print(f" -> {detail}") def step(n, title): print(f"\n\033[36m▶ {n}. {title}\033[0m") def check(cond, msg, detail=""): ok(msg) if cond else bad(msg, detail) SUF = str(int(time.time())) AUTHOR = f"smoke_a{SUF}" READER = f"smoke_r{SUF}" # ══════════ 1. 认证 ══════════ step(1, "用户注册") st, r, _ = call("POST", "/api/v1/auth/register", { "account": AUTHOR, "password": "SmokePass123!", "nickname": "冒烟作者"}) TOKEN_A = r.get("data", {}).get("token", "") AUTHOR_ID = r.get("data", {}).get("user", {}).get("id", "") check(st == 201 and TOKEN_A, f"作者注册成功 id={AUTHOR_ID[:8]}...", r) st, r, _ = call("POST", "/api/v1/auth/register", { "account": READER, "password": "SmokePass123!", "nickname": "冒烟读者"}) TOKEN_R = r.get("data", {}).get("token", "") check(st == 201 and TOKEN_R, "读者注册成功", r) # 新用户默认 role=user,发文需 author 权限。真实业务由后台授予,这里模拟。 import subprocess PSQL = r"C:\Program Files\PostgreSQL\16\bin\psql.exe" for acct in (AUTHOR, READER): subprocess.run([PSQL, "-h", "127.0.0.1", "-p", "55432", "-U", "postgres", "-d", "article_platform", "-q", "-c", f"UPDATE users SET role='author' WHERE account='{acct}';"], capture_output=True) ok("测试账号已提升为 author(模拟后台授权)") step(2, "注册与登录防护") st, _, _ = call("POST", "/api/v1/auth/register", {"account": AUTHOR, "password": "SmokePass123!"}) check(st == 409, "重复账号返回 409", f"got {st}") st, _, _ = call("POST", "/api/v1/auth/login", {"account": AUTHOR, "password": "WrongPass123!"}) check(st == 401, "错误密码返回 401", f"got {st}") st, _, _ = call("POST", "/api/v1/auth/login", {"account": "nobody_xyz_999", "password": "Whatever123!"}) check(st == 401, "不存在的账号同样 401(防枚举)", f"got {st}") st, r, _ = call("GET", "/api/v1/auth/me", token=TOKEN_A) check(r.get("data", {}).get("nickname") == "冒烟作者", "GET /me 中文昵称正确(UTF-8 往返无损)", r) st, _, _ = call("GET", "/api/v1/auth/me") check(st == 401, "未登录访问 /me 返回 401", f"got {st}") # ══════════ 2. 文章创建 ══════════ step(3, "创建文章(4 种区块)") sections = [ {"kind": "text", "order_index": 0, "payload": {"plain_text": '这是正文第一段,含中文与特殊符号 <>&"。', "text_align": "left"}}, {"kind": "subtitle", "order_index": 1, "payload": {"text": "小标题测试"}}, {"kind": "image", "order_index": 2, "payload": {"images": [{"url": "https://example.com/a.jpg", "caption": "配图", "width": 800, "height": 600}], "layout": "single"}}, {"kind": "location", "order_index": 3, "payload": {"name": "上海外滩", "address": "黄浦区中山东一路", "latitude": 31.24, "longitude": 121.49}}, ] st, r, _ = call("POST", "/api/v1/articles", { "title": f"冒烟测试文章 {SUF}", "subtitle": "端到端验证", "abstract": "验证创建、渲染、缓存、导出全链路", "sections": sections, }, token=TOKEN_A) MASK = r.get("data", {}).get("mask_id", "") ART_ID = r.get("data", {}).get("id", "") nsec = len(r.get("data", {}).get("sections") or []) check(st == 201 and MASK, f"文章创建成功 mask={MASK}", r) check(nsec == 4, f"4 个区块全部落库", f"got {nsec}") step(4, "区块类型校验") st, r, _ = call("POST", "/api/v1/articles", { "title": "非法投票", "sections": [{"kind": "vote", "order_index": 0, "payload": {"question": "只有一个选项", "options": [{"id": "1", "text": "A", "count": 0}]}}], }, token=TOKEN_A) msg = (r.get("error") or {}).get("message", "") check("2 个选项" in msg, "投票少于 2 个选项被拒", r) st, r, _ = call("POST", "/api/v1/articles", { "title": "未知类型", "sections": [{"kind": "unknown_kind", "order_index": 0, "payload": {}}], }, token=TOKEN_A) check("未知区块类型" in (r.get("error") or {}).get("message", ""), "未知 kind 被拒", r) st, r, _ = call("POST", "/api/v1/articles", { "title": " ", "sections": [], }, token=TOKEN_A) check(st == 400, "空白标题被拒(400)", f"got {st}") # ══════════ 3. 权限隔离 ══════════ step(5, "草稿权限隔离") st, _, _ = call("GET", f"/api/v1/articles/{MASK}") check(st == 403, "草稿对游客不可见(403)", f"got {st}") st, _, _ = call("GET", f"/api/v1/articles/{MASK}", token=TOKEN_R) check(st == 403, "草稿对其他用户不可见(403)", f"got {st}") st, r, _ = call("GET", f"/api/v1/articles/{MASK}", token=TOKEN_A) check(st == 200, "作者本人可读自己草稿", f"got {st}") # ══════════ 4. 发布与审核 ══════════ step(6, "发布流程") st, r, _ = call("POST", f"/api/v1/articles/{MASK}/publish", {}, token=TOKEN_A) check((r.get("data") or {}).get("status") == "pending", "发布后进入待审核", r) st, _, _ = call("POST", f"/api/v1/articles/{MASK}/publish", {}, token=TOKEN_R) check(st == 403, "他人不能发布我的文章(403)", f"got {st}") step(7, "审核流转") for acct in (AUTHOR,): subprocess.run([PSQL, "-h", "127.0.0.1", "-p", "55432", "-U", "postgres", "-d", "article_platform", "-q", "-c", f"UPDATE users SET role='super_admin' WHERE account='{acct}';"], capture_output=True) ok("作者提升为 super_admin(获得审核权限)") st, r, _ = call("GET", "/api/v1/review/pending", token=TOKEN_A) pending = len(r.get("data", {}).get("items") or []) check(pending >= 1, f"待审列表可见({pending} 篇)", r) st, r, _ = call("POST", f"/api/v1/review/{MASK}/approve", {"note": "内容合规"}, token=TOKEN_A) check((r.get("data") or {}).get("status") == "published", "审核通过转为 published", r) st, _, _ = call("POST", f"/api/v1/review/{MASK}/reject", {"note": "x"}, token=TOKEN_R) check(st == 403, "普通用户不能审核(403)", f"got {st}") # ══════════ 5. 公开读取与缓存 ══════════ step(8, "公开读取与缓存") st, r, _ = call("GET", f"/api/v1/articles/{MASK}") d = r.get("data") or {} check(st == 200 and d.get("title", "").startswith("冒烟测试文章"), "游客可读已发布文章", r) check(len(d.get("sections") or []) == 4, "详情返回 4 个区块", f"got {len(d.get('sections') or [])}") t0 = time.time() for _ in range(20): call("GET", f"/api/v1/articles/{MASK}") avg = (time.time() - t0) / 20 * 1000 check(avg < 50, f"缓存命中 20 次平均 {avg:.1f}ms(Valkey 生效)", f"{avg:.1f}ms") # ══════════ 6. 互动 ══════════ step(9, "点赞计数") st, r, _ = call("POST", f"/api/v1/articles/{MASK}/like", {}, token=TOKEN_R) check((r.get("data") or {}).get("count") == 1, "点赞成功,计数=1", r) st, r, _ = call("DELETE", f"/api/v1/articles/{MASK}/like", token=TOKEN_R) check((r.get("data") or {}).get("count") == 0, "取消点赞,计数归零", r) st, r, _ = call("POST", f"/api/v1/articles/{MASK}/like", {}, token=TOKEN_R) ok("重新点赞(供 worker 落库验证)") step(10, "评论与层级") st, r, _ = call("POST", f"/api/v1/articles/{MASK}/comments", {"content": "一级评论,测试中文与标点。"}, token=TOKEN_R) CID = (r.get("data") or {}).get("id", "") check(st == 201 and CID, "一级评论创建成功", r) st, r, _ = call("POST", f"/api/v1/articles/{MASK}/comments", {"content": "这是回复", "parent_id": CID}, token=TOKEN_A) check((r.get("data") or {}).get("depth") == 1, "二级回复 depth=1", r) st, r, _ = call("GET", f"/api/v1/articles/{MASK}/comments") tree0 = (r.get("data") or {}).get("items") or [] ok_tree = (len(tree0) == 1 and len(tree0[0].get("replies") or []) == 1) check(ok_tree, "评论树:1 条顶层评论带 1 条回复", f"threads={len(tree0)} replies={len(tree0[0].get('replies') or []) if tree0 else 0}") st, _, _ = call("POST", f"/api/v1/articles/{MASK}/comments", {"content": " "}, token=TOKEN_R) check(st == 400, "空白评论被拒(400)", f"got {st}") # ══════════ 评论树分页 ══════════ step(10.5, "评论树分页") # 用一篇全新文章隔离测试,避免与前面的评论混在一起 st, r, _ = call("POST", "/api/v1/articles", { "title": f"评论树测试 {SUF}", "sections": [{"kind": "text", "order_index": 0, "payload": {"plain_text": "用于验证评论树分页"}}], }, token=TOKEN_A) TMASK = (r.get("data") or {}).get("mask_id", "") call("POST", f"/api/v1/articles/{TMASK}/publish", {}, token=TOKEN_A) call("POST", f"/api/v1/review/{TMASK}/approve", {"note": "ok"}, token=TOKEN_A) # 造 3 条顶层评论;先发的那条挂 2 条回复 roots = [] for i in range(3): st, r, _ = call("POST", f"/api/v1/articles/{TMASK}/comments", {"content": f"顶层评论 {i + 1}"}, token=TOKEN_R) roots.append((r.get("data") or {}).get("id")) time.sleep(0.01) # 确保 created_at 严格递增,排序确定 check(all(roots), "创建 3 条顶层评论") for i in range(2): st, r, _ = call("POST", f"/api/v1/articles/{TMASK}/comments", {"content": f"对第一条的回复 {i + 1}", "parent_id": roots[0]}, token=TOKEN_A) time.sleep(0.01) check(st == 201, "为最早那条挂 2 条回复") # 分页:limit=2,第一页应是最新 2 条(roots[2], roots[1]),roots[0] 在第二页 st, r, _ = call("GET", f"/api/v1/articles/{TMASK}/comments?limit=2") tree = r.get("data", {}) items = tree.get("items") or [] check(len(items) == 2, f"顶层分页 limit=2 返回 {len(items)} 条", r) check(tree.get("total") == 3, "total 只统计顶层评论(=3,不含回复)", tree.get("total")) check(bool(tree.get("next_cursor")), "返回 next_cursor") # 第一页的顶层评论都还没有回复,replies 应为空数组而不是 null check(all(isinstance(t.get("replies"), list) for t in items), "无回复的 thread 返回空数组(不是 null)") # 第二页应取到 roots[0],它带 2 条回复 st, r2, _ = call("GET", f"/api/v1/articles/{TMASK}/comments?limit=2&cursor=" + urllib.parse.quote(tree["next_cursor"])) items2 = r2.get("data", {}).get("items") or [] check(len(items2) == 1, f"第二页返回 {len(items2)} 条", r2) target = items2[0] if items2 else None if target and target["comment"]["id"] == roots[0]: check(len(target["replies"]) == 2, f"回复随父级一起返回({len(target['replies'])} 条)", target["replies"]) check(target["reply_count"] == 2, "reply_count=2", target["reply_count"]) times = [x["created_at"] for x in target["replies"]] check(times == sorted(times), "回复按时间正序") else: bad("第二页未取到带回复的顶层评论", [t["comment"]["id"] for t in items2]) ids1 = {t["comment"]["id"] for t in items} ids2 = {t["comment"]["id"] for t in items2} check(not (ids1 & ids2), "两页无重复(keyset 分页正确)", ids1 & ids2) # 懒加载全部回复 st, r, _ = call("GET", f"/api/v1/comments/{roots[0]}/replies?limit=50") lazy = r.get("data") or {} check(lazy.get("total") == 2, "懒加载接口 total=2", lazy.get("total")) check(len(lazy.get("items") or []) == 2, "懒加载返回 2 条回复") # 回复不得越权:不存在的评论返回空而不是 500 st, r, _ = call("GET", "/api/v1/comments/01a10000-0000-7000-8000-000000000000/replies") check(st == 200 and (r.get("data") or {}).get("total") == 0, "不存在的评论返回空列表(不 500)", st) step(10.6, "对象存储直传") st, r, _ = call("POST", "/api/v1/media/presign", { "filename": "cover.png", "content_type": "image/png", "size": 102400, "media_type": "image"}, TOKEN_A) ok_media = st == 200 and (r.get("data") or {}).get("asset_id") check(bool(ok_media), "正常图片签发凭证成功", r) upload_url = (r.get("data") or {}).get("upload_url", "") check("X-Amz-Signature=" in upload_url, "签名 URL 含 X-Amz-Signature") check("X-Amz-Expires=900" in upload_url, "有效期为 15 分钟") ASSET_ID = (r.get("data") or {}).get("asset_id", "") st, r, _ = call("POST", "/api/v1/media/presign", { "filename": "evil.exe", "content_type": "image/png", "size": 1024, "media_type": "image"}, TOKEN_A) check(st == 400 and "白名单" in (r.get("error") or {}).get("message", ""), "扩展名白名单拦截 .exe", r) st, r, _ = call("POST", "/api/v1/media/presign", { "filename": "x.png", "content_type": "application/octet-stream", "size": 1024, "media_type": "image"}, TOKEN_A) check(st == 400, "不支持的 content_type 被拒", r) st, r, _ = call("POST", "/api/v1/media/presign", { "filename": "big.png", "content_type": "image/png", "size": 30 * 1024 * 1024, "media_type": "image"}, TOKEN_A) check(st == 413, "超体积返回 413", f"got {st}") st, r, _ = call("POST", "/api/v1/media/presign", { "filename": "a.mp4", "content_type": "video/mp4", "size": 5 * 1024 * 1024, "media_type": "video"}, TOKEN_A) check(st == 200, "视频类型可签发", r) import hashlib fake_sha = hashlib.sha256(b"smoke-test-content").hexdigest() st, r, _ = call("POST", "/api/v1/media/confirm", { "asset_id": ASSET_ID, "sha256": fake_sha, "width": 800, "height": 600}, TOKEN_A) conf = r.get("data") or {} check(st == 200 and conf.get("status") == "ready", "确认后状态 ready", r) check(fake_sha[:2] in conf.get("object_key", ""), "object_key 为内容寻址(含 hash 前缀)", conf.get("object_key")) st, r, _ = call("POST", "/api/v1/media/confirm", { "asset_id": ASSET_ID, "sha256": "bad"}, TOKEN_A) check(st == 400, "非法 sha256 被拒", f"got {st}") # 别人的资源不能确认 st, _, _ = call("POST", "/api/v1/media/presign", { "filename": "other.png", "content_type": "image/png", "size": 1024, "media_type": "image"}, TOKEN_R) st, r, _ = call("POST", "/api/v1/media/confirm", { "asset_id": ASSET_ID, "sha256": fake_sha}, TOKEN_R) check(st == 403, "他人不能确认我的媒体资源(403)", f"got {st}") # ══════════ 可观测性 ══════════ step(10.7, "指标端点") st, body, _ = call("GET", "/metrics", raw=True) text = body.decode("utf-8") if isinstance(body, bytes) else str(body) check(st == 200, "/metrics 可访问") check("http_requests_total" in text, "暴露 http_requests_total") check("http_request_duration_seconds" in text, "暴露耗时直方图") check("cache_hits_total" in text, "暴露缓存命中计数") check("go_goroutines" in text, "暴露 Go 运行时指标") check('route="/api/v1/articles/{maskID}"' in text or 'route="/api/v1/articles"' in text, "路由标签已归一化(不含具体 ID)") # ══════════ 7. 导出 ══════════ step(11, "分享与导出") st, body, _ = call("GET", f"/api/v1/share/{MASK}/html", raw=True) html = body.decode("utf-8") if isinstance(body, bytes) else str(body) check(st == 200 and "上海外滩" in html, f"导出 HTML 含地点区块({len(html)}B)") check("冒烟测试文章" in html, "导出 HTML 中文标题正确") check('src="https://example.com/a.jpg"' in html, "导出 HTML 含图片标签") check("

小标题测试

" in html, "导出 HTML 含小标题") check("<>&" in html, "导出 HTML 特殊字符已转义(XSS 防护)") st, r, _ = call("GET", f"/api/v1/share/{MASK}") check(st == 200, "分享接口返回 200", f"got {st}") # ══════════ 8. 搜索 ══════════ step(12, "搜索") kw = urllib.parse.quote("冒烟测试") st, r, _ = call("GET", f"/api/v1/search?keyword={kw}") hits = len(r.get("data", {}).get("items") or []) check(st == 200 and hits >= 1, f"中文搜索命中 {hits} 篇", r) st, r, _ = call("GET", "/api/v1/search") check(st == 400, "缺关键词返回 400", f"got {st}") # ══════════ 9. 通知 ══════════ step(13, "通知") st, r, _ = call("GET", "/api/v1/notifications/unread-count", token=TOKEN_A) unread = (r.get("data") or {}).get("unread", 0) check(unread >= 1, f"作者未读通知 {unread} 条(点赞+评论触发)", r) st, r, _ = call("GET", "/api/v1/notifications", token=TOKEN_A) items = r.get("data", {}).get("items") or [] check(len(items) >= 1, f"通知列表 {len(items)} 条", r) st, _, _ = call("PATCH", "/api/v1/notifications/read", {}, token=TOKEN_A) check(st == 200, "全部标记已读", f"got {st}") st, r, _ = call("GET", "/api/v1/notifications/unread-count", token=TOKEN_A) check((r.get("data") or {}).get("unread") == 0, "已读后未读数归零", r) # ══════════ 10. 后台 ══════════ step(14, "作者中心与管理后台") st, r, _ = call("GET", "/api/v1/author/stats/overview", token=TOKEN_A) check((r.get("data") or {}).get("articles", {}).get("published", 0) >= 1, "作者统计已发布数正确", r) st, r, _ = call("GET", "/api/v1/admin/analytics/overview", token=TOKEN_A) check(st == 200 and (r.get("data") or {}).get("total_articles", 0) >= 1, f"大盘总文章数={(r.get('data') or {}).get('total_articles')}", r) st, r, _ = call("GET", "/api/v1/admin/analytics/trends?days=7", token=TOKEN_A) check(len(r.get("data", {}).get("items") or []) == 7, "趋势图返回 7 天", r) st, _, _ = call("GET", "/api/v1/admin/users", token=TOKEN_R) check(st == 403, "普通用户访问用户管理被拒(403)", f"got {st}") st, _, _ = call("POST", "/api/v1/articles", {"title": "越权发文"}, token=TOKEN_R) # 注意:READER 已被提升为 author,这里应成功;用全新用户测 st2, r2, _ = call("POST", "/api/v1/auth/register", { "account": f"plain_{SUF}", "password": "PlainPass123!", "nickname": "普通用户"}) plain_token = (r2.get("data") or {}).get("token", "") st, _, _ = call("POST", "/api/v1/articles", {"title": "越权发文"}, token=plain_token) check(st == 403, "user 角色发文被拒(403)", f"got {st}") st, _, _ = call("GET", "/api/v1/admin/users", token=plain_token) check(st == 403, "user 角色访问后台被拒(403)", f"got {st}") # ══════════ 11. 分页与限流 ══════════ step(15, "分页与限流") st, r, _ = call("GET", "/api/v1/articles?limit=5") check(st == 200, "列表分页正常", f"got {st}") st, _, headers = call("POST", "/api/v1/articles", {"title": "限流头测试"}, token=plain_token) check("X-RateLimit-Limit" in headers or st == 403, "响应含限流头或已被权限拦截", str(headers)) # ══════════ 汇总 ══════════ print("\n" + "═" * 44) print(f" 通过: \033[32m{PASS}\033[0m 失败: \033[31m{FAIL}\033[0m") print("═" * 44) if FAILURES: print("\n失败明细:") for m, d in FAILURES: print(f" · {m}") if d: print(f" {str(d)[:200]}") sys.exit(0 if FAIL == 0 else 1)