test_outbound.py
9.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
# -*- coding: utf-8 -*-
"""出库明细解析 / 全局限速器 / DMS 接口流水 / 截图兜底页面(不需要模拟 DMS 和浏览器)。
edge\\vendor\\python38\\python.exe -m unittest tests.test_outbound -v (在 edge 目录下)
"""
import gzip
import json
import os
import subprocess
import sys
import tempfile
import threading
import time
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
EDGE = os.path.dirname(HERE)
sys.path.insert(0, EDGE)
from edgeclient import actions # noqa: E402
from edgeclient.browser import fallback_page # noqa: E402
from edgeclient.infra.apitrace import ApiTrace # noqa: E402
from edgeclient.infra.ratelimit import RateLimiter, RatePaused # noqa: E402
def ship(i, date, part="90915YZZM3", qty="1.000000", mfr="纯牌", wo="P44BH0008454", amount=39.0):
"""与 HAR 里 page-parts-shipmen-detailed 的明细行同结构。"""
return {"id": "21171498534262%05d" % i, "shipmentDate": date, "workOrderNo": wo, "shipmentBatchNo": "44BH0%d" % i,
"licensePlateNumber": None, "mfr": mfr, "partNo": part, "partName": "机油滤清器滤芯", "settlStatus": "1",
"reqQty": qty, "partUnitPrice": 39.0, "totalAmount": amount, "costPrice": 20.0, "totalCostPrice": 20.0}
def subtotal(wo):
return {"id": None, "partNo": None, "shipmentDate": None, "mfr": None, "partName": "小计(%s)" % wo,
"workOrderNo": wo, "reqQty": "2.000000", "totalAmount": 78.0}
class Cfg(object):
request_interval = 0.2
rate_floor = 0
rate_cooldown = 0
rate_pause_after = 3
rate_pause_seconds = 60
class OutboundTests(unittest.TestCase):
def test_subtotal_rows(self):
self.assertTrue(actions.is_subtotal(subtotal("W1")))
self.assertFalse(actions.is_subtotal(ship(1, "2026-10-28 09:00:00")))
def test_window_pure_net_quantities(self):
rows = [
ship(1, "2026-10-27 14:59:59"), # 窗口前一秒:不算
ship(2, "2026-10-27 15:00:00", qty="3.000000"), # 窗口起点:算
ship(3, "2026-10-28 09:03:18", qty="2.000000"),
ship(4, "2026-10-28 10:00:00", qty="-1.000000"), # 退货冲销:按净额
ship(5, "2026-10-28 11:00:00", part="ZCT0001", mfr="非纯"), # 非纯:不参与
ship(6, "2026-10-28 12:00:00", part="8713906140", qty="-1.000000"), # 只有冲销:净额 <= 0
ship(7, "2026-10-28 15:00:00", qty="9.000000"), # 窗口终点(不含):算到第二天
ship(8, "bad date"),
ship(9, "2026-10-28 13:00:00", part="A1", mfr="纯 牌"), # 未知厂家分类:告警
]
r = actions.summarize_outbound(rows, "2026-10-27 15:00:00", "2026-10-28 15:00:00")
st = r["stats"]
parts = {p["part_no"]: p for p in r["parts"]}
self.assertEqual(parts["90915YZZM3"]["qty"], 4)
self.assertEqual(parts["90915YZZM3"]["rows"], 3)
self.assertEqual(parts["8713906140"]["qty"], -1)
self.assertNotIn("ZCT0001", parts)
self.assertEqual((st["window_rows"], st["pure_rows"], st["nonpure_rows"]), (6, 4, 2))
self.assertEqual((st["negative_rows"], st["bad_date_rows"], st["candidates"]), (2, 1, 1))
self.assertEqual(st["nonpositive_parts"], ["8713906140"])
self.assertEqual(st["unknown_mfr"], ["纯 牌"])
self.assertEqual(len(r["window_rows"]), 6) # 窗口内所有厂家分类原样回传(审计)
def test_fetch_pages_by_work_order(self):
"""pageSize 按工单计数:每页返回 size 个工单的明细 + 小计行;页数 × size >= total 即停;去重。"""
groups = [[ship(g * 10 + j, "2026-10-28 09:00:00", wo="W%d" % g) for j in range(1 + g % 3)] for g in range(5)]
calls = []
class Sess(object):
def shipment_page(self, d1, d2, page, size):
calls.append(page)
out = []
for grp in groups[(page - 1) * size: page * size]:
out += grp + [subtotal(grp[0]["workOrderNo"])]
if page == 2:
out.insert(0, dict(groups[0][0])) # 跨页重复的一行:去重
return len(groups), out
rows, st = actions.fetch_outbound(Sess(), "2026-10-27", "2026-10-28", size=2)
self.assertEqual(calls, [1, 2, 3])
self.assertEqual(len(rows), sum(len(g) for g in groups))
self.assertEqual((st["work_orders"], st["subtotal_rows"], st["dup_rows"]), (5, 5, 1))
def test_fetch_stops_when_page_ignored(self):
class Sess(object):
n = 0
def shipment_page(self, d1, d2, page, size):
self.n += 1
return 100, [ship(1, "2026-10-28 09:00:00"), subtotal("W")]
s = Sess()
rows, st = actions.fetch_outbound(s, "2026-10-27", "2026-10-28", size=1)
self.assertEqual((s.n, len(rows)), (2, 1))
class RateLimiterTests(unittest.TestCase):
def test_interval_across_threads(self):
lim = RateLimiter()
stamps = []
def work():
for _ in range(3):
lim.wait(Cfg)
stamps.append(time.time())
ts = [threading.Thread(target=work) for _ in range(3)]
for t in ts:
t.start()
for t in ts:
t.join()
stamps.sort()
gaps = [b - a for a, b in zip(stamps, stamps[1:])]
self.assertEqual(len(stamps), 9)
self.assertGreaterEqual(min(gaps), 0.19) # 不并发:任意两次间隔 >= 节拍
def test_floor_clamps_interval(self):
c = type("C", (), {"request_interval": 0.1, "rate_floor": 0.3})
self.assertEqual(RateLimiter().interval(c), 0.3)
def test_penalty_backoff_and_pause(self):
lim = RateLimiter()
lim.penalize("HTTP 503", Cfg)
self.assertAlmostEqual(lim.interval(Cfg), 0.4)
lim.reward(Cfg) # cooldown=0:恢复一档
self.assertAlmostEqual(lim.interval(Cfg), 0.2)
lim.penalize("HTTP 429", Cfg)
self.assertEqual(lim.snapshot(Cfg)["paused_seconds"], 0)
lim.penalize("HTTP 429", Cfg) # 10 分钟内第 3 次:暂停
self.assertGreater(lim.snapshot(Cfg)["paused_seconds"], 50)
with self.assertRaises(RatePaused):
lim.wait(Cfg)
def test_interval_across_processes(self):
"""服务进程和 tool.bat 菜单进程共用 run/dms_rate.lock:两个进程交替发请求也不会挤在一起。"""
run = tempfile.mkdtemp(prefix="rate_")
code = ("import sys,time;sys.path.insert(0,%r);from edgeclient.infra.ratelimit import RateLimiter\n"
"l=RateLimiter();l.configure(%r)\nC=type('C',(),{'request_interval':0.2,'rate_floor':0})\n"
"for _ in range(4):\n l.wait(C);print(repr(time.time()),flush=True)\n") % (EDGE, run)
procs = [subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE) for _ in range(2)]
stamps = sorted(float(x) for p in procs for x in p.communicate()[0].decode().split())
gaps = [b - a for a, b in zip(stamps, stamps[1:])]
self.assertEqual(len(stamps), 8)
self.assertGreaterEqual(min(gaps), 0.18)
class TraceTests(unittest.TestCase):
def test_trace_summary_and_file(self):
t = ApiTrace()
t.add("queryByPage", "POST", "https://x/a?v=1", {"partNo": "A"}, 200, 0.1, {"code": 10000000}, {"content": []},
'{"body":{}}', "", True)
t.start("tid1")
t.add("queryByPage", "POST", "https://x/a?v=1", {"partNo": "A"}, 200, 0.12,
{"code": 10000000, "traceId": "abc", "message": "成功"}, {"content": [1, 2]}, '{"body":{"content":[1,2]}}',
"", True)
t.add("page-national-inventory", "POST", "https://x/b", {}, 0, 3.0, None, None, "", "NetworkError: x", False)
calls = t.stop()
self.assertEqual([c["seq"] for c in calls], [1, 2]) # start 之前的不记
self.assertEqual((calls[0]["rows"], calls[0]["trace_id"], calls[0]["url"]), (2, "abc", "https://x/a"))
summ = ApiTrace.summary(calls)
self.assertNotIn("response", summ[0])
path = ApiTrace.write(calls, os.path.join(tempfile.mkdtemp(), "t.jsonl.gz"))
with gzip.open(path, "rt", encoding="utf-8") as f:
back = [json.loads(x) for x in f]
self.assertEqual(back[0]["request"], {"partNo": "A"})
self.assertFalse(t.active())
class FallbackPageTests(unittest.TestCase):
def test_pages_carry_notice_and_data(self):
row = {"orderNo": "S20261028015", "orderType": "S", "orderStatus": "1", "supplierCode": "APC40",
"itemNum": "2", "totalAmount": 3842.6, "createTime": "2026-10-28 15:03:00"}
details = [{"itemNo": "1", "partNo": "90915YZZM3", "partName": "机油滤清器滤芯<b>", "purchaseQty": 18,
"unitPrice": 39, "totalPriceSum": 702}]
lst = fallback_page.list_html(row, "截图超时")
det = fallback_page.detail_html(row, details, "截图超时")
for page in (lst, det):
self.assertIn(fallback_page.NOTICE, page)
self.assertIn("截图超时", page)
self.assertIn("S20261028015", page)
self.assertIn("SO/库存补充订单", lst)
self.assertIn("90915YZZM3", det)
self.assertIn("<b>", det) # 接口数据要转义
if __name__ == "__main__":
unittest.main()