test_captcha.py
5.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"""验证码识别接口:取数端上传验证码图片 → 视觉模型识别(打桩)→ 图片和结果存证据、写日志 → 后台能看最近记录。"""
from __future__ import annotations
import base64
import json
import logging
from pathlib import Path
import pytest
from app.services import captcha, edge, settings
PNG = b"\x89PNG\r\n\x1a\n" + b"fake-captcha-image"
@pytest.fixture()
def fake_model(monkeypatch):
calls: list[dict] = []
state = {"reply": "n8nA", "error": None}
def fake(image, text_length=None, timeout=None):
calls.append({"image": image, "text_length": text_length, "timeout": timeout})
if state["error"]:
raise RuntimeError(state["error"])
return state["reply"]
monkeypatch.setattr(captcha, "recognize", fake)
return calls, state
def _post(kit, image=PNG, **kw):
body = {"image": base64.b64encode(image).decode(), "text_length": 4} | kw
return kit.c.post("/api/edge/v1/captcha/recognize", json=body, headers=kit.eh)
def _read(eid: int) -> bytes:
return Path(edge.evidence(eid)["abs_path"]).read_bytes()
def test_recognize_ok_saves_evidence_and_logs(kit, fake_model, caplog):
calls, _ = fake_model
with caplog.at_level(logging.INFO, logger="server.captcha"):
r = _post(kit)
assert r.status_code == 200, r.text
j = r.json()
assert j["text"] == "n8nA" and "error" not in j
assert calls[0]["text_length"] == 4
assert calls[0]["timeout"] == settings.get("edge_runtime").captcha_timeout # 用运行参数里的超时
img = edge.evidence(j["image_evidence_id"])
assert img["kind"] == "captcha_image" and img["mime"] == "image/png" and _read(img["id"]) == PNG
rec = json.loads(_read(j["result_evidence_id"]))
assert rec["recognized"] == "n8nA" and rec["length_ok"] and rec["image_evidence_id"] == img["id"]
assert rec["device_name"] == "配件部电脑"
assert any("n8nA" in m for m in caplog.messages)
# 后台最近记录
rows = kit.c.get("/api/client/captcha/recent", headers=kit.h).json()["rows"]
assert rows[0]["recognized"] == "n8nA" and rows[0]["image_evidence_id"] == img["id"]
def test_recognize_failure_returns_error_not_5xx(kit, fake_model, caplog):
_, state = fake_model
state["error"] = "没有配置大模型 API Key"
with caplog.at_level(logging.WARNING, logger="server.captcha"):
r = _post(kit, image=b"\xff\xd8\xff" + b"jpeg")
assert r.status_code == 200
j = r.json()
assert j["text"] == "" and "API Key" in j["error"]
assert edge.evidence(j["image_evidence_id"])["mime"] == "image/jpeg"
assert any("识别失败" in m for m in caplog.messages)
rows = kit.c.get("/api/client/captcha/recent", headers=kit.h).json()["rows"]
assert rows[0]["error"] and rows[0]["recognized"] == ""
def test_wrong_length_flagged(kit, fake_model):
_, state = fake_model
state["reply"] = "n8n"
j = _post(kit).json()
assert j["text"] == "n8n" # 原样返回,由取数端决定换图
assert json.loads(_read(j["result_evidence_id"]))["length_ok"] is False
def test_bad_requests(kit, fake_model):
assert kit.c.post("/api/edge/v1/captcha/recognize", json={"image": "aGk="},
headers={"X-Edge-Token": "wrong"}).status_code == 401
assert _post(kit, image=b"").status_code in (400, 422)
assert kit.c.post("/api/edge/v1/captcha/recognize", json={"image": "不是base64!!"},
headers=kit.eh).status_code == 400
assert fake_model[0] == [] # 都没调模型
def test_outcome_and_judge(kit, fake_model):
j = _post(kit).json()
rid = j["result_evidence_id"]
r = kit.c.post("/api/edge/v1/captcha/outcome", json={"result_evidence_id": rid, "outcome": "ok", "how": "ui"},
headers=kit.eh)
assert r.status_code == 200, r.text
assert kit.c.post("/api/edge/v1/captcha/outcome", json={"result_evidence_id": rid, "outcome": "bad"},
headers=kit.eh).status_code == 400
assert kit.c.post("/api/edge/v1/captcha/outcome", json={"result_evidence_id": 99999999, "outcome": "ok"},
headers=kit.eh).status_code == 400
r = kit.c.post(f"/api/client/captcha/{rid}/judge", json={"correct": False, "answer": "n8nB "}, headers=kit.h)
assert r.status_code == 200, r.text
body = kit.c.get("/api/client/captcha/recent", headers=kit.h).json()
row = body["rows"][0]
assert row["outcome"] == "ok" and row["outcome_cn"] == "登录成功" and row["how"] == "浏览器模拟登录"
assert row["judge"]["correct"] is False and row["judge"]["answer"] == "n8nB"
assert body["stats"] == {"judged": 1, "correct": 0, "submitted": 1, "accepted": 1}
ev = kit.c.get("/api/events?limit=20", headers=kit.h)
if ev.status_code == 200:
assert any("IAM 要求了验证码" in str(e) for e in (ev.json() if isinstance(ev.json(), list) else ev.json().get("rows", [])))
def test_captcha_runtime_settings_roundtrip(kit):
r = kit.c.get("/api/client/runtime", headers=kit.h).json()["values"]
assert r["captcha_enabled"] is True and r["captcha_max_retries"] == 2
r = kit.c.put("/api/client/runtime", json={"captcha_enabled": False, "captcha_max_retries": 3}, headers=kit.h)
assert r.status_code == 200, r.text
rt = kit.c.get("/api/edge/v1/config", headers=kit.eh).json()["runtime"]
assert rt["captcha_enabled"] is False and rt["captcha_max_retries"] == 3 # 随 /config 下发
assert kit.c.put("/api/client/runtime", json={"captcha_max_retries": 0}, headers=kit.h).status_code == 400
kit.c.put("/api/client/runtime", json={"captcha_enabled": True, "captcha_max_retries": 2}, headers=kit.h)