dsp-smoke.py
17.1 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""模拟下级平台(红山区平台 CF-HS)向本平台上报数据,验证批 1 + 批 2 的接入链路。
覆盖:
1. 车场基本信息 3 条(路侧 1 + 封闭 2)
2. 封闭车场车位汇总 1 条
3. 路侧泊位 100 条
4. 批 2:设备 20 台、出入口 6 条、收费 2 条、设备-泊位关联 10 条
5. 批 2 错误路径:泊位冲突 4002、解绑缺时间 4003、收费改挂 5001、字段非法 5002、
撤回 6002;出入口条数与 5.1 不一致 → 告警 2004
6. 同 requestId 重复提交 → 幂等回放(响应逐字节一致)
7. 签名用了别的路径 → 401 + 9003
用法:
python3 scripts/dsp-smoke.py # 默认 http://127.0.0.1:48083
python3 scripts/dsp-smoke.py http://host:port
密钥只在进程内存里流转,不打印、不落盘。脚本可重复执行:
平台已存在时走一次「重置密钥」拿到新密钥,旧密钥保留 7 天双轨期。
"""
import base64
import hashlib
import hmac
import json
import sys
import time
import uuid
import urllib.error
import urllib.request
BASE = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:48083").rstrip("/")
ADMIN = BASE + "/admin-api"
PREFIX = "/open-api/dsp/v1"
PLATFORM_CODE = "CF-HS"
PLATFORM_NAME = "红山区停车平台"
def http(method, url, body=None, headers=None, timeout=20):
data = None
hdrs = dict(headers or {})
if body is not None:
data = body if isinstance(body, bytes) else json.dumps(body, ensure_ascii=False).encode("utf-8")
hdrs.setdefault("Content-Type", "application/json")
req = urllib.request.Request(url, data=data, headers=hdrs, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.status, resp.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def admin_call(method, path, token=None, body=None):
headers = {"Authorization": "Bearer " + token} if token else {}
status, raw = http(method, ADMIN + path, body, headers)
payload = json.loads(raw.decode("utf-8")) if raw else {}
if status != 200 or payload.get("code") != 0:
raise SystemExit(f"管理端调用失败 {method} {path}: http={status} {payload.get('msg')}")
return payload.get("data")
def login():
data = admin_call("POST", "/system/auth/login",
body={"username": "admin", "password": "admin123"})
return data["accessToken"]
def ensure_platform(token):
page = admin_call("GET", "/park/dsp-platform/page?platformCode=" + PLATFORM_CODE + "&pageSize=10",
token)
rows = page.get("list") or []
if rows:
platform_id = rows[0]["id"]
secret = admin_call("PUT", f"/park/dsp-platform/reset-key?id={platform_id}", token)["secretKey"]
print(f" 平台已存在(id={platform_id}),已重置密钥取得双轨期新密钥")
return platform_id, secret
created = admin_call("POST", "/park/dsp-platform/create", token, {
"platformCode": PLATFORM_CODE,
"platformName": PLATFORM_NAME,
"platformType": 1,
"contactName": "红山区联系人",
"contactPhone": "0476-0000000",
"ipWhitelist": "127.0.0.1",
"dataScope": "150402",
"remark": "冒烟脚本创建",
})
print(f" 已创建平台 id={created['id']}")
return created["id"], created["secretKey"]
def sign(secret, method, path, platform_code, timestamp, nonce, body_bytes):
source = "\n".join([method, path, platform_code, timestamp, nonce,
hashlib.sha256(body_bytes).hexdigest()])
key = base64.b64decode(secret)
return hmac.new(key, source.encode("utf-8"), hashlib.sha256).hexdigest()
def post_object(secret, path, request_id, items, sign_path=None):
envelope = {
"platformCode": PLATFORM_CODE,
"requestId": request_id,
"version": "1.1",
"list": items,
}
body = json.dumps(envelope, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
ts = str(int(time.time() * 1000))
nonce = uuid.uuid4().hex
signed_path = sign_path or (PREFIX + path)
signature = sign(secret, "POST", signed_path, PLATFORM_CODE, ts, nonce, body)
status, raw = http("POST", BASE + PREFIX + path, body, {
"X-Platform-Code": PLATFORM_CODE,
"X-Timestamp": ts,
"X-Nonce": nonce,
"X-Sign": signature,
})
return status, raw
def parks():
now = time.strftime("%Y-%m-%d %H:%M:%S")
base = {
"districtCode": "150402",
"streetName": "西屯街道",
"coordType": "WGS84",
"availableBerthNum": 20,
"specificBerthNum": 0,
"shareBerthNum": 0,
"deformBerthNum": 2,
"chargePileNum": 4,
"entranceNum": 1,
"exitNum": 1,
"openTime": "07:00-21:30",
"serviceType": 1,
"manageUnitName": "红山区智慧停车运营有限公司",
"manageUnitCode": "91150402MA0XXXXXX1",
"maintainUnit": "红山区城管局",
"ownerName": "红山区人民政府",
"ownType": 1,
"staffNum": 6,
"dataSource": 1,
"infoServiceName": "赤峰中智",
"infoServiceCode": "91150400MA0YYYYYY2",
"updateTime": now,
}
park1 = dict(base, parkSn="HS-PL-0001", parkName="钢铁街路侧停车场", parkType=1,
address="红山区钢铁街北侧", roadName="钢铁街", lon=118.887712, lat=42.267845,
berthNum=100, contact="张三", contactPhone="13800000001",
servicePhone="0476-1111111", feeSn="HS-FEE-01")
park2 = dict(base, parkSn="HS-PL-0002", parkName="赤峰万达广场地下停车场", parkType=2,
address="红山区迎宾大街 1 号", lon=118.901233, lat=42.269911,
berthNum=300, contact="李四", contactPhone="13800000002",
feeSn="HS-FEE-02", pictureUrl="https://park.example.com/p2.jpg")
park3 = dict(base, parkSn="HS-PL-0003", parkName="红山区医院配建停车场", parkType=3,
address="红山区解放街 9 号", lon=118.895001, lat=42.271002,
berthNum=120, contact="王五", contactPhone="13800000003",
ownType=2, rentEndDate="2029-12-31")
return [park1, park2, park3]
def summary():
return {
"parkSn": "HS-PL-0002",
"surfacePlaneNum": 100,
"landPlaneNum": 180,
"surfaceMechanicNum": 0,
"landMechanicNum": 0,
"selfWalkNum": 0,
"operationalNum": 20,
"berthNum": 300,
"smallCarNum": 280,
"largeCarNum": 20,
"disabledBerthNum": 4,
"newEnergyNum": 20,
"chargePileNum": 10,
"quickChargePileNum": 4,
"slowChargePileNum": 6,
"chargePileOperationUnit": "国网赤峰",
"updateTime": time.strftime("%Y-%m-%d %H:%M:%S"),
}
def berths():
now = time.strftime("%Y-%m-%d %H:%M:%S")
items = []
for i in range(1, 101):
items.append({
"parkSn": "HS-PL-0001",
"berthSn": f"GTB-{i:03d}",
"areaCode": "HS-PL-0001-A01",
"areaName": "钢铁街北侧 001-020",
"berthType": 1 if i % 10 else 2,
"berthStatus": 1,
"roadPosition": "北侧",
"direction": "车头朝东",
"parkMode": "平行",
"lon": 118.887700 + i * 0.00001,
"lat": 42.267845,
"isCharge": 1,
"updateTime": now,
})
return items
def devices():
now = time.strftime("%Y-%m-%d %H:%M:%S")
items = []
# 路侧 15 台地磁(不直接挂泊位,绑定关系走 5.7)
for i in range(1, 16):
items.append({
"parkSn": "HS-PL-0001",
"deviceSn": f"HS-DV-{i:04d}",
"deviceType": 1,
"vendorName": "深圳中磁",
"deviceName": f"钢铁街地磁 {i:02d}",
"deviceModel": "DC-200",
"installPosition": f"GTB-{i:03d} 车位中央",
"relateStatus": 1,
"workStatus": 1,
"workTemperature": 26.5,
"uploadInterval": 30,
"threshold": 20,
"reconnectInterval": 60,
"reconnectNum": 3,
"version": "1.2.3",
"onlineTime": now,
"updateTime": now,
})
# 封闭车场 5 台高位视频(视频类必须有安装高度)
for i in range(1, 6):
items.append({
"parkSn": "HS-PL-0002",
"deviceSn": f"HS-DV-01{i:02d}",
"deviceType": 6,
"vendorName": "杭州海康",
"deviceName": f"万达地库高位视频 {i}",
"deviceModel": "HK-V400",
"installPosition": "B1 层入口通道",
"installHeight": 4.5,
"relateStatus": 1,
"workStatus": 1,
"version": "2.0.1",
"updateTime": now,
})
return items
def entrances():
now = time.strftime("%Y-%m-%d %H:%M:%S")
items = [
{"parkSn": "HS-PL-0002", "crSn": "CR-E01", "crName": "万达广场北入口",
"crType": 1, "relateRoad": "迎宾大街", "lon": 118.901200, "lat": 42.269900,
"deviceSn": "HS-DV-0101", "updateTime": now},
{"parkSn": "HS-PL-0002", "crSn": "CR-E02", "crName": "万达广场南出口",
"crType": 2, "relateRoad": "迎宾大街", "lon": 118.901260, "lat": 42.269880,
"deviceSn": "HS-DV-0102", "updateTime": now},
]
# HS-PL-0003 报文入口/出口各报 1 个(合计 2),这里报 4 条 → 一致性告警 2004
for i in range(1, 5):
items.append({
"parkSn": "HS-PL-0003", "crSn": f"CR-N{i:02d}", "crName": f"医院出入口 {i}",
"crType": 3, "relateRoad": "解放街", "lon": 118.895000, "lat": 42.271000,
"updateTime": now,
})
return items
def rates():
now = time.strftime("%Y-%m-%d %H:%M:%S")
return [
{"parkSn": "HS-PL-0001", "feeSn": "HS-FEE-01", "feeStandardType": "政府定价",
"billingPeriod": "07:00-21:30,21:30-07:00", "timingUnit": "元/30分钟",
"smallCarPrice": 2, "bigCarPrice": 3, "countPrice": 1, "freeMinutes": 15,
"capDay": 20, "capOnce": 20, "singlePayDuration": 0, "singlePayPrice": 0,
"detailed": "首 15 分钟免费,日间 2 元/30 分钟", "updateTime": now},
{"parkSn": "HS-PL-0002", "feeSn": "HS-FEE-02", "feeStandardType": "市场调节价",
"billingPeriod": "00:00-24:00", "timingUnit": "元/小时",
"smallCarPrice": 5, "bigCarPrice": 8, "freeMinutes": 30,
"capDay": 50, "updateTime": now},
]
def device_berths():
now = time.strftime("%Y-%m-%d %H:%M:%S")
items = []
for i in range(1, 11):
items.append({
"parkSn": "HS-PL-0001",
"deviceSn": f"HS-DV-{i:04d}",
"berthSn": f"GTB-{i:03d}",
"bindStatus": 1,
"bindTime": now,
"updateTime": now,
})
return items
def report(name, secret, path, request_id, items):
status, raw = post_object(secret, path, request_id, items)
payload = json.loads(raw.decode("utf-8"))
data = payload.get("data") or {}
print(f" {name:<14} http={status} code={payload.get('code')} "
f"total={data.get('total')} success={data.get('success')} failed={data.get('failed')}")
if payload.get("code") != 0:
print(" msg:", payload.get("msg"))
for item in (data.get("items") or [])[:5]:
if item.get("code") != 0:
print(f" ⚠ {item.get('bizKey')}: {item.get('code')} {item.get('msg')}")
return status, raw, payload
def main():
print("== 1. 登录与平台准入 ==")
token = login()
platform_id, secret = ensure_platform(token)
stamp = time.strftime("%Y%m%d-%H%M%S")
park_items = parks()
park_request_id = f"hs-{stamp}-park-001"
print("== 2. 上报静态数据 ==")
report("车场 3 条", secret, "/park", park_request_id, park_items)
report("车位汇总 1 条", secret, "/park-berth-summary", f"hs-{stamp}-summary-001", [summary()])
report("泊位 100 条", secret, "/berth", f"hs-{stamp}-berth-001", berths())
print("== 3. 批 2:设备 / 出入口 / 收费 / 关联 / 撤回 ==")
report("设备 20 台", secret, "/device", f"hs-{stamp}-device-001", devices())
report("出入口 6 条", secret, "/entrance", f"hs-{stamp}-entrance-001", entrances())
report("收费 2 条", secret, "/rate", f"hs-{stamp}-rate-001", rates())
report("关联 10 条", secret, "/device-berth", f"hs-{stamp}-rel-001", device_berths())
# 冲突:GTB-001 已被 HS-DV-0001 占用,再绑 HS-DV-0011 → 4002
_, _, conflict = report("泊位冲突", secret, "/device-berth",
f"hs-{stamp}-rel-conflict-001", [{
"parkSn": "HS-PL-0001", "deviceSn": "HS-DV-0011",
"berthSn": "GTB-001", "bindStatus": 1,
"updateTime": time.strftime("%Y-%m-%d %H:%M:%S"),
}])
conflict_code = ((conflict.get("data") or {}).get("items") or [{}])[0].get("code")
# 解绑缺 unbindTime → 4003
_, _, unbind_bad = report("解绑缺时间", secret, "/device-berth",
f"hs-{stamp}-rel-unbind-bad-001", [{
"parkSn": "HS-PL-0001", "deviceSn": "HS-DV-0010",
"berthSn": "GTB-010", "bindStatus": 0,
"updateTime": time.strftime("%Y-%m-%d %H:%M:%S"),
}])
unbind_bad_code = ((unbind_bad.get("data") or {}).get("items") or [{}])[0].get("code")
# feeSn 改挂别的车场 → 5001
_, _, rate_mismatch = report("收费改挂", secret, "/rate",
f"hs-{stamp}-rate-mismatch-001", [{
"parkSn": "HS-PL-0002", "feeSn": "HS-FEE-01",
"smallCarPrice": 2, "freeMinutes": 15,
"updateTime": time.strftime("%Y-%m-%d %H:%M:%S"),
}])
rate_mismatch_code = ((rate_mismatch.get("data") or {}).get("items") or [{}])[0].get("code")
# capDay < smallCarPrice → 5002
_, _, rate_invalid = report("收费字段非法", secret, "/rate",
f"hs-{stamp}-rate-invalid-001", [{
"parkSn": "HS-PL-0001", "feeSn": "HS-FEE-03",
"smallCarPrice": 5, "capDay": 1, "freeMinutes": 0,
"updateTime": time.strftime("%Y-%m-%d %H:%M:%S"),
}])
rate_invalid_code = ((rate_invalid.get("data") or {}).get("items") or [{}])[0].get("code")
today = time.strftime("%Y-%m-%d")
_, _, withdraw_ok = report("撤回车场", secret, "/park/withdraw",
f"hs-{stamp}-withdraw-001", [{
"parkSn": "HS-PL-0003", "reason": "车场改造停运",
"effectiveDate": today,
"updateTime": time.strftime("%Y-%m-%d %H:%M:%S"),
}])
withdraw_ok_code = ((withdraw_ok.get("data") or {}).get("items") or [{}])[0].get("code")
_, _, withdraw_old = report("撤回日期过早", secret, "/park/withdraw",
f"hs-{stamp}-withdraw-old-001", [{
"parkSn": "HS-PL-0001", "reason": "测试",
"effectiveDate": "2026-01-01",
"updateTime": time.strftime("%Y-%m-%d %H:%M:%S"),
}])
withdraw_old_code = ((withdraw_old.get("data") or {}).get("items") or [{}])[0].get("code")
print("== 4. 幂等回放 ==")
first = post_object(secret, "/park", park_request_id, park_items)
second = post_object(secret, "/park", park_request_id, park_items)
same = first[1] == second[1]
print(f" 同 requestId 两次响应一致:{same}(http={second[0]})")
print("== 5. 签名路径不一致 ==")
status, raw = post_object(secret, "/berth", f"hs-{stamp}-berth-bad-001", berths()[:1],
sign_path="/open-api/dsp/v1/park")
payload = json.loads(raw.decode("utf-8"))
print(f" 改路径后验签:http={status} code={payload.get('code')} msg={payload.get('msg')}")
print("== 6. 结论 ==")
expect = {
"泊位冲突 4002": (conflict_code, 4002),
"解绑缺时间 4003": (unbind_bad_code, 4003),
"收费改挂 5001": (rate_mismatch_code, 5001),
"收费字段非法 5002": (rate_invalid_code, 5002),
"撤回成功 0": (withdraw_ok_code, 0),
"撤回日期过早 6002": (withdraw_old_code, 6002),
}
ok = same and status == 401 and payload.get("code") == 9003
for name, (actual, want) in expect.items():
hit = actual == want
ok = ok and hit
print(f" {name:<16} {'✓' if hit else '✗'} 期望 {want},实际 {actual}")
print(" 幂等与签名行为符合预期" if ok else " ⚠️ 存在不符合预期的行为,请查 /tmp/yudao-server.log")
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())