test_retry.py
22.5 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# -*- coding: utf-8 -*-
"""3.1.0(_retry 版)新增能力的回归测试:auth-api 断连时浏览器代发重试、浏览器模拟人工登录(逐步确认 / 取消 / 超时 /
密码错误 / 验证码)、连接追踪、审计与抓包脱敏、等人工确认时暂停步骤计时、收集诊断。
edge\\vendor\\python38\\python.exe -m unittest tests.test_retry (在 edge 目录下)
模拟 DMS 与 test_edge 共用;auth-api 经 dev/flaky_proxy.py 断连代理(localhost:端口,和 DMS 的 127.0.0.1 跨域)。
UI 登录在测试里用无界面浏览器跑(SHOW_UI=1 时有界面,可以看着它点);"人点确认"由测试线程真实点击面板按钮模拟。
"""
import glob
import json
import os
import sys
import tempfile
import threading
import time
import unittest
import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
EDGE = os.path.dirname(HERE)
sys.path.insert(0, EDGE)
sys.path.insert(0, os.path.join(EDGE, "dev"))
from flaky_proxy import FlakyProxy # noqa: E402
from tests import test_edge # noqa: E402
from tests.test_edge import PORT, logins, mock, mock_state # noqa: E402
from tests.test_captcha import FakeRecognizer # noqa: E402
from tests.test_runtime import FakeCC # noqa: E402
from edgeclient import actions # noqa: E402
from edgeclient.browser import cdp, screenshot, ui_login # noqa: E402
from edgeclient.browser.screenshot import ScreenshotError # noqa: E402
from edgeclient.connectors.base import LoginError, LoginRejected # noqa: E402
from edgeclient.connectors.gtmc import auth as gtmc_auth # noqa: E402
from edgeclient.connectors.gtmc.api import DmsSession # noqa: E402
from edgeclient.connectors.gtmc.client import Client, NET_EVENTS # noqa: E402
from edgeclient.core.outbox import Outbox # noqa: E402
from edgeclient.core.tasks import TaskContext # noqa: E402
PWD = "mock_pass_123"
class AutoConfirm(threading.Thread):
"""模拟坐在电脑前的人:看到确认面板就真实点击「确认执行」(或「取消」)。"""
def __init__(self, answer="ok", limit=99):
super(AutoConfirm, self).__init__(daemon=True)
self.answer, self.limit, self.n = answer, limit, 0
self._stop = threading.Event()
def run(self):
js = ("(function(){var b=document.getElementById('__edge_%s'); if(!b) return null;"
"var r=b.getBoundingClientRect(); return [r.left+r.width/2, r.top+r.height/2]})()" % self.answer)
while not self._stop.is_set() and self.n < self.limit:
for c in list(cdp.ACTIVE):
try:
pos = c.evaluate(js, timeout=3)
if pos:
time.sleep(0.3)
c.mouse_click(pos[0], pos[1])
self.n += 1
time.sleep(1.0)
except Exception: # noqa: BLE001
pass
time.sleep(0.3)
def stop(self):
self._stop.set()
def _all_text(d):
out = []
for f in glob.glob(os.path.join(d, "*")):
if f.endswith((".json", ".jsonl", ".har", ".html")):
out.append(open(f, encoding="utf-8", errors="replace").read())
return "\n".join(out)
class RetryTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
test_edge.EdgeTests.setUpClass.__func__(cls)
cls._need_visible = ui_login.need_visible
if not os.environ.get("SHOW_UI"):
ui_login.need_visible = lambda cfg: False # 测试里无界面跑(逻辑与有界面一致)
@classmethod
def tearDownClass(cls):
ui_login.need_visible = cls._need_visible
test_edge.EdgeTests.tearDownClass.__func__(cls)
def cfg(self, **over):
return test_edge.EdgeTests.cfg(self, **over)
def setUp(self):
mock(reset=True)
test_edge.LIMITER.reset()
self.proxies = []
def tearDown(self):
for p in self.proxies:
p.stop()
def flaky(self, rate=0.0, first=0):
p = FlakyProxy(PORT, rate, first, seed=7).start()
self.proxies.append(p)
url = "http://localhost:%d/auth" % p.port
mock(auth_base=url)
return p, url
def ui_cfg(self, url, **rt):
r = {"strategies": ["ui"], "ui_confirm": True, "ui_confirm_timeout": 40, "ui_typing_delay_ms": 5,
"page_timeout": 20}
r.update(rt)
return self.cfg(auth_api=url, runtime=r)
def capture(self, c, s):
out = tempfile.mkdtemp(prefix="shot_", dir=self.tmp)
return out, screenshot.capture(c, s, [("po_list.png", screenshot.po_list_url(c), [])], out)
# ---------------- 浏览器模拟人工登录 ----------------
def test_ui_login_confirmed_with_flaky_auth(self):
"""逐步确认(5 步)→ 登录成功;auth-api 前 3 个连接被断,浏览器里的请求由取数端代发重试;密码只提交 1 次。"""
p, url = self.flaky(first=3)
c = self.ui_cfg(url)
s = DmsSession(c)
clicker = AutoConfirm("ok")
clicker.start()
try:
out, files = self.capture(c, s)
finally:
clicker.stop()
self.assertTrue(os.path.getsize(files[0]) > 5000)
self.assertEqual(clicker.n, 5)
self.assertEqual(logins(), 1)
self.assertGreaterEqual(p.stats["dropped"], 3)
self.assertEqual(s.stats.get("how"), "浏览器模拟人工登录")
s.stock_page(1, 1) # 浏览器登录的 token 接口也能用
audit = [json.loads(l) for l in open(os.path.join(out, "audit.jsonl"), encoding="utf-8")]
self.assertEqual(len([a for a in audit if a["kind"] == "ui.confirm"]), 5)
self.assertTrue(any(a["kind"] == "relay" and a.get("attempts", 1) > 1 for a in audit))
bh = json.load(open(os.path.join(out, "browser.har"), encoding="utf-8"))
self.assertTrue(any("取数端代发" in e.get("comment", "") for e in bh["log"]["entries"]))
self.assertTrue(glob.glob(os.path.join(out, "ui_*_login_page.png")))
text = _all_text(out)
self.assertNotIn(PWD, text)
self.assertNotIn(s.token.value, text)
def test_ui_cancel_aborts_without_submit(self):
_, url = self.flaky()
c = self.ui_cfg(url)
clicker = AutoConfirm("no", limit=1)
clicker.start()
try:
with self.assertRaises(ScreenshotError) as cm:
self.capture(c, DmsSession(c))
finally:
clicker.stop()
self.assertIn("人工取消", str(cm.exception))
self.assertEqual(logins(), 0)
def test_ui_confirm_timeout_does_nothing(self):
_, url = self.flaky()
c = self.ui_cfg(url, ui_confirm_timeout=2)
with self.assertRaises(ScreenshotError) as cm:
self.capture(c, DmsSession(c))
self.assertIn("超时", str(cm.exception))
self.assertEqual(logins(), 0)
def test_ui_wrong_password_single_submit_and_paused(self):
_, url = self.flaky()
c = self.cfg(auth_api=url, password="wrong_pass_1",
runtime={"strategies": ["ui", "token"], "ui_confirm": False, "ui_typing_delay_ms": 0})
s = DmsSession(c)
with self.assertRaises(LoginRejected):
self.capture(c, s)
self.assertEqual(logins(), 1) # 只点了一次登录,没有再试 token 方式
self.assertTrue(s.login_state()["paused"])
def _ui_captcha_cfg(self, url, rec, **rt):
r = {"strategies": ["ui"], "ui_confirm": False, "ui_typing_delay_ms": 0}
r.update(rt)
c = self.cfg(auth_api=url, runtime=r)
c._cloud = rec
return c
def test_ui_captcha_stops_when_disabled(self):
"""验证码识别关闭:和以前一样见验证码就停,密码不提交。"""
_, url = self.flaky()
mock(captcha=True)
rec = FakeRecognizer("ok")
c = self._ui_captcha_cfg(url, rec, captcha_enabled=False)
with self.assertRaises(ScreenshotError) as cm:
self.capture(c, DmsSession(c))
self.assertIn("已关闭", str(cm.exception))
self.assertEqual(logins(), 0)
self.assertEqual(rec.calls, [])
def test_ui_captcha_recognized_and_login(self):
"""浏览器登录页出现验证码:截下页面上那张图 → 识别 → 逐字填入 → 点登录(只提交 1 次)→ 截图成功。"""
_, url = self.flaky()
mock(captcha=True)
rec = FakeRecognizer("ok")
c = self._ui_captcha_cfg(url, rec)
s = DmsSession(c)
out, files = self.capture(c, s)
self.assertTrue(os.path.getsize(files[0]) > 5000)
self.assertEqual(logins(), 1)
self.assertEqual(len(rec.calls), 1)
self.assertEqual(rec.calls[0][3], "image/png") # 传上去的是元素截图
self.assertEqual(mock_state()["last_checkcode"], rec.calls[0][1])
self.assertEqual(rec.outcomes[-1][1:], ("ok", "ui"))
self.assertIn("ui.captcha", _all_text(out))
def test_ui_captcha_bad_length_clicks_for_new_image(self):
"""识别位数不对:真实点击验证码图片换一张再识别,没拿错结果去提交。"""
_, url = self.flaky()
mock(captcha=True)
rec = FakeRecognizer("short", "ok")
c = self._ui_captcha_cfg(url, rec, captcha_max_retries=3)
self.capture(c, DmsSession(c))
self.assertEqual(len(rec.calls), 2)
self.assertNotEqual(rec.calls[0][1], rec.calls[1][1]) # 第二次识别的是新的一张
self.assertEqual(logins(), 1)
def test_ui_captcha_wrong_not_paused(self):
"""填错验证码:CaptchaWrong(计入每日上限),不按「账号被拒」暂停自动登录。"""
_, url = self.flaky()
mock(captcha=True)
rec = FakeRecognizer("swap")
c = self._ui_captcha_cfg(url, rec)
s = DmsSession(c)
with self.assertRaises(ScreenshotError) as cm:
self.capture(c, s)
self.assertIn("验证码", str(cm.exception))
self.assertEqual(logins(), 1)
self.assertFalse(s.login_state()["paused"])
self.assertEqual(s.stats["captcha_wrong_today"], 1)
self.assertEqual(rec.outcomes[-1][1:], ("captcha_wrong", "ui"))
def test_ui_blocked_by_overlay_stops_and_dumps_scene(self):
"""用户名框被整页遮挡层盖住:不点、不输入、不提交;报错说出挡着的是谁,现场 json + 截图留在结果目录。"""
_, url = self.flaky()
mock(overlay="cover")
c = self.cfg(auth_api=url, runtime={"strategies": ["ui"], "ui_confirm": False, "ui_typing_delay_ms": 0})
out = tempfile.mkdtemp(prefix="shot_", dir=self.tmp)
with self.assertRaises(ScreenshotError) as cm:
screenshot.capture(c, DmsSession(c), [("po_list.png", screenshot.po_list_url(c), [])], out)
self.assertIn("div.loginMainBg", str(cm.exception))
self.assertEqual(logins(), 0)
scene = json.load(open(os.path.join(out, "ui_blocked_j_username.json"), encoding="utf-8"))
self.assertEqual(scene["stack_at_point"][0]["cls"], "loginMainBg")
self.assertTrue(scene["inputs_and_buttons"] and scene["target_ancestors"] and scene["window"]["innerW"])
audit = [json.loads(l) for l in open(os.path.join(out, "audit.jsonl"), encoding="utf-8")]
self.assertTrue(any(a["kind"] == "ui.blocked" and a.get("file") for a in audit))
def test_ui_picks_the_clickable_one_among_duplicate_ids(self):
"""页面里有两个 #j_username,第一个被遮住:应选中真正可点的那个,正常登录。"""
_, url = self.flaky()
mock(overlay="dup")
c = self.cfg(auth_api=url, runtime={"strategies": ["ui"], "ui_confirm": False, "ui_typing_delay_ms": 0})
self.capture(c, DmsSession(c))
self.assertEqual(logins(), 1)
def test_ui_login_works_with_css_zoom_container(self):
"""登录框祖先带 CSS zoom:0.85(真站 div.loginBox):getBoundingClientRect 坐标和屏幕上不一致,要校正;
密码框上还盖着占位文字层(div.passwordLayer):点它(和真人一样)并正常输入;密码只提交 1 次。"""
_, url = self.flaky()
mock(overlay="zoom")
c = self.cfg(auth_api=url, runtime={"strategies": ["ui"], "ui_confirm": False, "ui_typing_delay_ms": 0})
self.capture(c, DmsSession(c))
self.assertEqual(logins(), 1)
def test_watch_flow_no_api_login_before_browser(self):
"""菜单 12 的流程(actions.screenshot_po + 只用 ui):本地存的接口 token 已失效时,不先做接口登录,
浏览器登录 1 次后用浏览器的 token 查最新采购单。关掉代发:token 只能从 localStorage 的 "Bearer ..." 读
(真站就是这样,3.2.4 在这里读错格式 → 调接口 401)。"""
c = self.cfg(runtime={"strategies": ["ui"], "ui_confirm": False, "ui_typing_delay_ms": 0,
"browser_relay": False, "login_min_interval": 60})
s = DmsSession(c)
s.login() # 之前(别的进程、很久以前)的接口登录……
s._last_attempt = 0
mock(expire_tokens=True) # ……已经失效
before, seen = logins(), []
orig = s.po_page
s.po_page = lambda *a, **k: seen.append((logins(), s.stats.get("how"))) or orig(*a, **k)
t0 = time.time()
r = actions.screenshot_po(c, s)
self.assertEqual(logins() - before, 1) # 只有浏览器那 1 次密码登录
self.assertEqual(seen, [(before + 1, "浏览器模拟人工登录")]) # 查采购单发生在浏览器登录之后
self.assertLess(time.time() - t0, 50) # 没有「距上次登录不到 60 秒」的等待
self.assertTrue(r["order_no"] and all(os.path.getsize(f) > 5000 for f in r["files"]))
s.stock_page(1, 1) # 浏览器的 token 接口也能用
def test_ui_abort_before_submit_not_counted(self):
"""确认面板第 1 步就取消:没提交密码,不算一次密码登录,紧接着再跑不触发登录间隔等待。"""
_, url = self.flaky()
c = self.ui_cfg(url, login_min_interval=60)
s = DmsSession(c)
for _ in range(2):
clicker = AutoConfirm("no", limit=1)
clicker.start()
t0 = time.time()
try:
with self.assertRaises(ScreenshotError):
self.capture(c, s)
finally:
clicker.stop()
self.assertLess(time.time() - t0, 40)
self.assertEqual(s.login_state()["today_logins"], 0)
self.assertEqual(logins(), 0)
def test_ui_skipped_when_no_desktop(self):
_, url = self.flaky()
c = self.ui_cfg(url)
old = ui_login.need_visible, ui_login.interactive_desktop
ui_login.need_visible, ui_login.interactive_desktop = (lambda cfg: True), (lambda: False)
try:
with self.assertRaises(ScreenshotError) as cm:
self.capture(c, DmsSession(c))
finally:
ui_login.need_visible, ui_login.interactive_desktop = old
self.assertIn("以服务在后台运行时跳过", str(cm.exception))
self.assertEqual(logins(), 0)
# ---------------- 代发 / 截图 ----------------
def test_sso_screenshot_survives_flaky_auth_api(self):
"""sso 方式:DMS 前端在浏览器里调 iam-oauth / perms,auth-api 30% 断连 + 前 2 个必断,代发重试后截图成功。"""
p, url = self.flaky(rate=0.3, first=2)
c = self.cfg(auth_api=url, runtime={"strategies": ["sso"]})
s = DmsSession(c)
s.login()
out, files = self.capture(c, s)
self.assertTrue(os.path.getsize(files[0]) > 5000)
self.assertGreater(p.stats["dropped"], 0)
page = open(os.path.join(out, "audit.html"), encoding="utf-8").read()
self.assertIn("relay.summary", page)
self.assertNotIn(PWD, _all_text(out))
http_har = json.load(open(os.path.join(out, "http.har"), encoding="utf-8"))
self.assertTrue(http_har["log"]["entries"])
def test_http_login_falls_back_to_ui(self):
c = self.cfg(runtime={"strategies": ["token", "ui"], "ui_confirm": False})
s = DmsSession(c)
calls = []
old_login, old_fb = gtmc_auth.login, screenshot.ui_fallback_login
def bad_login(client, cfg):
raise LoginError("换 token 请求网络失败(模拟)")
gtmc_auth.login = bad_login
screenshot.ui_fallback_login = lambda cfg, sess: calls.append(1) or ui_login.to_token("tok_from_browser_123")
try:
tok = s.login()
finally:
gtmc_auth.login, screenshot.ui_fallback_login = old_login, old_fb
self.assertEqual(calls, [1])
self.assertEqual(tok.value, "tok_from_browser_123")
# ---------------- 连接追踪 ----------------
def test_connection_tracing_ip_phase_and_net_events(self):
p = FlakyProxy(PORT, 0, first=1).start()
self.proxies.append(p)
c = self.cfg()
cl = Client(c)
r = cl.request("GET", "http://localhost:%d/dms/" % p.port, retries=0)
self.assertEqual(r.status, 0)
self.assertIn("请求发出后", r.error)
self.assertIn(cl.trace[-1]["ip"], ("127.0.0.1", "::1"))
r = cl.request("GET", "http://localhost:%d/dms/" % p.port, retries=0)
self.assertEqual(r.status, 200)
self.assertIsNotNone(cl.trace[-1]["tcp_ms"])
lines = open(NET_EVENTS["path"], encoding="utf-8").read().splitlines()
self.assertEqual(json.loads(lines[-1])["phase"], "request")
# ---------------- 等人工确认时暂停步骤计时 ----------------
def test_human_wait_pauses_step_timer(self):
cc = FakeCC()
ctx = TaskContext(self.cfg(), None, cc, Outbox(tempfile.mkdtemp(dir=self.tmp)),
{"id": "t7", "type": "x", "params": {"_steps": {"screenshot": 0.6}}})
with ctx.step("screenshot"):
with ctx.human_wait("点击登录", 30):
time.sleep(1.2) # 比步骤超时长,但在等人确认
time.sleep(0.2)
self.assertEqual([x[1:3] for x in cc.calls],
[("screenshot", "start"), ("confirm", "start"), ("confirm", "ok"), ("screenshot", "ok")])
self.assertFalse(ctx.timed_out)
# ---------------- 收集诊断 ----------------
def test_collect_diag_packs_without_secrets(self):
from edgeclient.core.tasks import NullSteps
from edgeclient.plugins import sys_tasks
c = self.cfg()
uploaded = {}
class Ctx(NullSteps):
cfg = c
task_id = "diag1"
def upload(self, path, kind="file"):
uploaded["names"] = zipfile.ZipFile(path).namelist()
uploaded["text"] = "".join(zipfile.ZipFile(path).read(n).decode("utf-8", "replace")
for n in uploaded["names"] if n.endswith((".json", ".txt")))
return 42
r = sys_tasks.collect_diag(Ctx(), {"rounds": 1, "browser_probe": False, "days": 1, "recent_tasks": 3})
self.assertEqual(r["evidence"], [42])
self.assertIn("取数端版本", r["env"])
self.assertTrue(any(x["name"] == "Python 直连" for x in r["probes"]))
self.assertIn("diag/env.json", uploaded["names"])
self.assertIn("diag/config_effective.json", uploaded["names"])
self.assertNotIn(PWD, uploaded["text"])
def test_upload_logs_includes_task_scenes(self):
"""拉取日志:除了文本日志,还带上当天每次任务的现场(审计 / 截图 / 遮挡诊断 json),且不含密码。"""
import datetime
from edgeclient.core.tasks import NullSteps
from edgeclient.plugins import sys_tasks
from edgeclient.infra.logutil import add_secret
add_secret(PWD)
c = self.cfg()
run = os.path.join(c.data_dir, datetime.date.today().strftime("%Y%m%d"), "120000_screenshot_po")
os.makedirs(run, exist_ok=True)
for name, body in (("audit.html", "<html>审计</html>"), ("ui_blocked_j_username.json", '{"stack_at_point": []}'),
("ui_03_blocked.png", "png"), ("summary.json", '{"ok": false, "note": "%s"}' % PWD)):
with open(os.path.join(run, name), "w", encoding="utf-8") as f:
f.write(body)
for name in ("shot_a.png", "shot_b.png"): # 内容完全相同的大截图只存一份
with open(os.path.join(run, name), "wb") as f:
f.write(b"x" * (150 * 1024))
with open(os.path.join(run, "big.har"), "wb") as f: # 4~5 MB 的 browser.har:文本类放宽,照常打包
f.write(b"{}" + b" " * sys_tasks.UPLOAD_FILE_LIMIT)
with open(os.path.join(run, "huge.png"), "wb") as f: # 超大截图仍跳过
f.truncate(sys_tasks.UPLOAD_FILE_LIMIT + 1)
with open(os.path.join(run, "huge.har"), "wb") as f:
f.truncate(sys_tasks.UPLOAD_TEXT_LIMIT + 1)
got = {}
class Ctx(NullSteps):
cfg = c
task_id = "up1"
def upload(self, path, kind="file"):
z = zipfile.ZipFile(path)
got["names"] = z.namelist()
got["text"] = "".join(z.read(n).decode("utf-8", "replace") for n in got["names"] if n.endswith((".json", ".txt", ".html")))
return 7
r = sys_tasks.upload_logs(Ctx(), {})
self.assertTrue(r["ok"] and r["evidence"] == [7] and r["runs"] >= 1)
rel = "edge_data/%s/120000_screenshot_po/" % datetime.date.today().strftime("%Y%m%d")
for n in ("audit.html", "ui_blocked_j_username.json", "ui_03_blocked.png", "summary.json"):
self.assertIn(rel + n, got["names"])
self.assertIn(rel + "big.har", got["names"])
for n in ("huge.har", "huge.png"):
self.assertNotIn(rel + n, got["names"])
self.assertTrue(any(n in x for x in r["skipped"]))
for n in ("meta/version.json", "meta/config_effective.json", "MANIFEST.txt"):
self.assertIn(n, got["names"])
self.assertEqual(len([n for n in got["names"] if n.startswith(rel + "shot_")]), 1)
self.assertIn("没有重复打包", got["text"])
self.assertNotIn(PWD, got["text"])
if __name__ == "__main__":
unittest.main()