test_captcha.py
11.2 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# -*- coding: utf-8 -*-
"""IAM 图片验证码登录的回归测试(模拟 DMS 按真站 HAR + IAM 源码:displayVerificationCode 返回 true/false、
图片在 Kaptcha.jpg、提交时区分大小写校验 j_checkcode)。云端识别用假对象直接挂到 cfg._cloud,不走网络。
edge\\vendor\\python38\\python.exe -m unittest tests.test_captcha (在 edge 目录下)
"""
import os
import sys
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
from tests import test_edge # noqa: E402
from tests.test_edge import logins, mock, mock_state # noqa: E402
from edgeclient.connectors.base import CaptchaWrong, LoginError, LoginRejected # noqa: E402
from edgeclient.connectors.gtmc import auth # noqa: E402
from edgeclient.connectors.gtmc.api import DmsSession # noqa: E402
from edgeclient.core.cloud import CloudError # noqa: E402
import base64 # noqa: E402
class FakeRecognizer(object):
"""假的云端识别:从模拟 DMS 的假图片里读出正确答案,再按 plan 依次决定返回什么。
plan 里每一项:ok(正确答案)/ swap(大小写反过来 = 识别错)/ short(只返回 3 位)/ error(云端识别失败)/ down(连不上云端)。
用完之后一直按最后一项。"""
def __init__(self, *plan):
self.plan, self.calls, self.outcomes = list(plan or ["ok"]), [], []
def recognize_captcha(self, image_b64, text_length=None, mime="image/png", timeout=60):
img = base64.b64decode(image_b64)
if b"CAPTCHA:" in img: # 接口登录:Kaptcha.jpg 原样传上来,尾巴上有答案
answer = img.split(b"CAPTCHA:", 1)[1].decode()
else: # 浏览器登录:传上来的是页面截图,答案问模拟 DMS
answer = mock_state()["captcha_answer"]
how = self.plan[min(len(self.calls), len(self.plan) - 1)]
self.calls.append((how, answer, text_length, mime, timeout))
eid = len(self.calls)
if how == "down":
raise CloudError("云端连不上", 0)
if how == "error":
return {"text": "", "error": "模型超时", "image_evidence_id": eid}
wrong = ("X" if answer[0] != "X" else "Y") + answer[1:]
text = {"ok": answer, "swap": wrong, "short": answer[:3]}[how]
return {"text": text, "image_evidence_id": eid, "result_evidence_id": eid + 1000, "elapsed": 0.1}
def captcha_outcome(self, result_evidence_id, outcome, tip="", how="api"):
self.outcomes.append((result_evidence_id, outcome, how))
return {"ok": True}
class CaptchaTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
test_edge.EdgeTests.setUpClass.__func__(cls)
@classmethod
def tearDownClass(cls):
test_edge.EdgeTests.tearDownClass.__func__(cls)
def setUp(self):
mock(reset=True)
test_edge.LIMITER.reset()
def cfg(self, recognizer=None, **runtime):
c = test_edge.EdgeTests.cfg(self, runtime=runtime)
c._cloud = recognizer
return c
def test_no_captcha_submits_placeholder_like_browser(self):
"""IAM 不要求验证码:不拉图、不识别,j_checkcode 和浏览器一样提交占位值「验证码」。"""
rec = FakeRecognizer()
DmsSession(self.cfg(rec)).login()
st = mock_state()
self.assertEqual(st["last_checkcode"], "验证码")
self.assertEqual(st["count"]["kaptcha"], 0)
self.assertEqual(rec.calls, [])
self.assertEqual(logins(), 1)
def test_captcha_recognized_and_login_ok(self):
mock(captcha=True)
rec = FakeRecognizer("ok")
s = DmsSession(self.cfg(rec))
s.login()
st = mock_state()
self.assertEqual(st["count"]["kaptcha"], 1)
self.assertEqual(logins(), 1)
self.assertEqual(len(rec.calls), 1)
self.assertEqual(rec.calls[0][2], 4) # 提示云端 4 位
self.assertEqual(st["last_checkcode"], rec.calls[0][1]) # 提交的就是答案(区分大小写)
self.assertEqual(s.login_state()["state"], "ok")
def test_bad_length_refetches_without_submitting(self):
"""识别结果位数不对:换一张图再识别,不拿错结果去提交密码。"""
mock(captcha=True)
rec = FakeRecognizer("short", "error", "ok")
DmsSession(self.cfg(rec, captcha_max_retries=3)).login()
self.assertEqual(mock_state()["count"]["kaptcha"], 3)
self.assertEqual(logins(), 1)
def test_recognition_exhausted_stops_before_password(self):
"""次数用完:报登录失败(不是「账号被拒」),密码一次都没提交,不算今日登录次数,也不暂停。"""
mock(captcha=True)
rec = FakeRecognizer("short", "down")
s = DmsSession(self.cfg(rec, captcha_max_retries=2))
with self.assertRaises(LoginError) as cm:
s.login()
self.assertNotIsInstance(cm.exception, LoginRejected)
self.assertIn("验证码", str(cm.exception))
self.assertEqual(logins(), 0)
self.assertEqual(mock_state()["count"]["kaptcha"], 2)
self.assertFalse(s.login_state()["paused"])
self.assertEqual(s.stats["today_logins"], 0)
def test_disabled_stops_before_password(self):
mock(captcha=True)
rec = FakeRecognizer("ok")
with self.assertRaises(LoginError) as cm:
DmsSession(self.cfg(rec, captcha_enabled=False)).login()
self.assertIn("已关闭", str(cm.exception))
self.assertEqual(logins(), 0)
self.assertEqual(rec.calls, [])
def test_no_cloud_stops_before_password(self):
mock(captcha=True)
with self.assertRaises(LoginError):
DmsSession(self.cfg(None)).login()
self.assertEqual(logins(), 0)
def test_wrong_captcha_not_rejected_and_daily_limit(self):
"""验证码识别错(大小写反了):不按「账号被拒」永久暂停;每天最多错 3 次,之后不再提交密码。"""
mock(captcha=True)
run = test_edge.tempfile.mkdtemp(dir=self.tmp)
rec = FakeRecognizer("swap")
c = test_edge.build(test_edge.make_local(self.tmp, run_dir=run), test_edge.make_remote(), "gtmc")
c._cloud = rec
s = DmsSession(c)
for i in range(3):
with self.assertRaises(CaptchaWrong):
s.login()
self.assertFalse(s.login_state()["paused"])
self.assertEqual(logins(), 3)
with self.assertRaises(LoginError) as cm:
s.login()
self.assertIn("今天验证码已错 3 次", str(cm.exception))
self.assertEqual(logins(), 3)
# 进程重启(同一天):计数从登录态文件恢复,仍然不提交
s2 = DmsSession(c)
with self.assertRaises(LoginError):
s2.login()
self.assertEqual(logins(), 3)
# 第二天自动恢复
s2.stats["day"] = "2000-01-01"
rec.plan = ["ok"]
s2.login()
self.assertEqual(logins(), 4)
def test_disabled_and_not_required_is_unchanged(self):
"""开关关闭 + IAM 不要验证码:和合作商改动之前完全一样(提交占位值「验证码」),不拉图、不碰云端。"""
rec = FakeRecognizer("ok")
DmsSession(self.cfg(rec, captcha_enabled=False)).login()
st = mock_state()
self.assertEqual(st["last_checkcode"], "验证码")
self.assertEqual(st["count"]["kaptcha"], 0)
self.assertEqual((rec.calls, rec.outcomes), ([], []))
self.assertEqual(logins(), 1)
def test_outcome_reported(self):
"""要求验证码的登录结束后,把结果回报云端(登录成功 / 验证码不对 / 没识别出)。"""
mock(captcha=True)
rec = FakeRecognizer("ok")
DmsSession(self.cfg(rec)).login()
self.assertEqual(rec.outcomes, [(1001, "ok", "api")])
rec2 = FakeRecognizer("swap")
with self.assertRaises(CaptchaWrong):
DmsSession(self.cfg(rec2)).login()
self.assertEqual(rec2.outcomes, [(1001, "captcha_wrong", "api")])
rec3 = FakeRecognizer("short")
with self.assertRaises(LoginError):
DmsSession(self.cfg(rec3, captcha_max_retries=1)).login()
self.assertEqual(rec3.outcomes, [(1001, "not_submitted", "api")])
def test_screenshot_token_sso_submit_password_once(self):
"""截图 token → sso:截图前的接口登录验证码填错了,sso 不再重新提交一次密码。"""
from edgeclient.browser import screenshot
mock(captcha=True)
c = self.cfg(FakeRecognizer("swap"), strategies=["token", "sso"])
out = test_edge.tempfile.mkdtemp(dir=self.tmp)
with self.assertRaises(screenshot.ScreenshotError) as cm:
screenshot.capture(c, DmsSession(c), [("po_list.png", screenshot.po_list_url(c), [])], out)
self.assertEqual(logins(), 1)
self.assertIn("不再重试", str(cm.exception))
def test_probe_a_detects_validation_then_b_passes(self):
"""菜单 15:IAM 不要验证码时也在会话里拉一张;A 故意填错 → 验证码错误;B 识别填写 → 登录成功。
(模拟 DMS 只要会话里拉过图就校验,对应「IAM 拉图后会校验」的情况)"""
mock(captcha=True)
rec = FakeRecognizer("ok")
c = self.cfg(rec)
s = DmsSession(c)
with self.assertRaises(CaptchaWrong):
s.run_password_login(lambda: auth.login(s.client, c, force_captcha="wrong"))
self.assertEqual(mock_state()["last_checkcode"], auth.PROBE_WRONG_CODE)
self.assertEqual(rec.calls, []) # A 不识别
s.client.jar.clear()
s.run_password_login(lambda: auth.login(s.client, c, force_captcha="recognize"))
self.assertEqual(logins(), 2)
self.assertEqual(rec.outcomes[-1][1:], ("ok", "probe_recognize"))
def test_probe_a_when_iam_ignores(self):
"""IAM 不要验证码、也不校验(模拟 DMS captcha=false 时不校验):A 故意填错也登录成功。"""
rec = FakeRecognizer("ok")
c = self.cfg(rec)
s = DmsSession(c)
s.run_password_login(lambda: auth.login(s.client, c, force_captcha="wrong"))
self.assertEqual(mock_state()["count"]["kaptcha"], 1)
self.assertEqual(logins(), 1)
def test_captcha_test_menu_never_submits_password(self):
mock(captcha=True)
rec = FakeRecognizer("ok")
c = self.cfg(rec)
r = auth.captcha_test(c, DmsSession(c, persist=False).client)
self.assertTrue(r["ok"], r)
self.assertTrue(r["need_captcha"])
self.assertEqual(r["recognized"], mock_state()["captcha_answer"])
self.assertEqual(r["image_evidence_id"], 1)
self.assertEqual(logins(), 0)
# IAM 不要求验证码时也能拉图测试识别
mock(captcha=False)
r = auth.captcha_test(c, DmsSession(c, persist=False).client)
self.assertTrue(r["ok"], r)
self.assertFalse(r["need_captcha"])
self.assertEqual(logins(), 0)
if __name__ == "__main__":
unittest.main()