Files
windows-fenjian/tools/_test_cls_model_sync.py
T
Ubuntu 4966345424 feat(1.0.75): 同步秤端 v1.0.75 源码(UI 抖动修复 + 严格入库/分拣样本)
来自 入库分拣工作站_源代码_v1.0.75:点商品名抖动的中间帧修复、ui/osk/tablet 调整、严格入库校验、分拣场景样本(review_queue station=picking);版本/安装包/说明同步 1.0.75。注意:本版 confirm_before_submit 恒 True、submit_on_remove 恒 False,1.0.71 的 inbound_auto_submit 账号开关被移除;models/cls 与 data/ 未入库。EXE 由用户侧打包分发,本次只推源码。
2026-12-03 16:26:17 +08:00

292 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""回归测试:本地模型自动更新(模型分发 + 校验 + 替换,不需要秤/相机/真库)。
盯的是五件事,每一件现场都会发生:
1. 服务器有新版本 → 下载、校验、替换、写 model.json;
2. 版本没变 → 一个字节都不下(现场十来台秤同时开机,别把带宽吃满);
3. 清单 sha256 对不上 → 拒绝替换,本地保持旧版;
4. 服务器给的是「端上读不了」的 onnx → 拒绝替换(半个/坏模型比没有更坏);
5. 两个文件换到一半失败(第二个 os.replace 失败)→ 回滚,磁盘回到旧版完整
状态,不留「新 onnx + 旧 classes + 旧 manifest」混合态(红队 B-2)。
用本机 HTTP 服务模拟后台,走的是真 `ApiClient`(含真实 multipart 之外的
流式下载与 sha256 校验),不 mock 掉被测代码。第 5 条是唯一打桩的用例:
它只验回滚,不验加载,所以把 LocalClassifier 换成永远可用的假类。
"""
import hashlib
import io
import json
import os
import shutil
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, HERE)
from core.api.client import ApiClient # noqa: E402
from core.recognition.local_cls import LocalClassifier # noqa: E402
from core.recognition.model_sync import ModelSync # noqa: E402
REAL_ONNX = os.path.join(HERE, 'models', 'cls', 'product_cls.onnx')
REAL_CLASSES = os.path.join(HERE, 'models', 'cls', 'classes.json')
SRV = {'manifest': None, 'files': {}, 'hits': {}}
class Handler(BaseHTTPRequestHandler):
"""只实现两个只读接口,形状与 mobileWeighModelRoutes 一致。"""
def log_message(self, *args): # 别把测试输出刷满
return
def _json(self, code, payload):
body = json.dumps(payload, ensure_ascii=False).encode('utf-8')
self.send_response(code)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self): # noqa: N802 http.server 的命名
path = self.path.split('?')[0]
SRV['hits'][path] = SRV['hits'].get(path, 0) + 1
if path == '/api/mobile/weigh/cls-model/manifest':
if not SRV.get('manifest'):
return self._json(404, {'error': 'model_not_installed'})
return self._json(200, {'success': True, 'data': SRV['manifest']})
prefix = '/api/mobile/weigh/cls-model/file/'
if path.startswith(prefix):
name = path[len(prefix):]
data = (SRV.get('files') or {}).get(name)
if data is None:
return self._json(404, {'error': 'model_not_installed'})
self.send_response(200)
self.send_header('Content-Type', 'application/octet-stream')
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
return
return self._json(404, {'error': 'unknown'})
def publish(version, files, corrupt_sha=False, drop_file=''):
"""在「服务器」上发布一版:files = {name: bytes}。"""
SRV['files'] = dict(files)
rows = []
for name, data in files.items():
rows.append({'name': name,
'sha256': hashlib.sha256(data).hexdigest(),
'size': len(data),
'url': '/api/mobile/weigh/cls-model/file/' + name})
if corrupt_sha and rows:
rows[0]['sha256'] = 'f' * 64
if drop_file:
rows = [r for r in rows if r['name'] != drop_file]
SRV['manifest'] = {'schema': 1, 'version': version,
'created_at': '2026-12-01T20:00:00+08:00',
'imgsz': 320, 'class_count': 875, 'notes': '',
'files': rows}
SRV['hits'] = {}
def unpublish():
SRV['manifest'] = None
SRV['files'] = {}
SRV['hits'] = {}
def main():
ok_n, bad_n = [0], [0]
def ok(name, cond, extra=''):
if cond:
ok_n[0] += 1
print(' [ok] %s' % name)
else:
bad_n[0] += 1
print(' [x ] %s %s' % (name, extra))
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = 'http://127.0.0.1:%d/api' % server.server_address[1]
work = tempfile.mkdtemp(prefix='cls_sync_')
old_cwd = os.getcwd()
os.chdir(work)
try:
os.makedirs('models/cls', exist_ok=True)
cfg = {'server': {'base_url': base, 'mock': False},
'account': {'username': 't'},
'vision': {'assist': {
'model': 'models/cls/product_cls.onnx',
'classes': 'models/cls/classes.json',
'auto_update': True, 'update_timeout': 60}}}
api = ApiClient(cfg)
api.token = 'test-token' # 跳过登录:本测试只验下载链路
ms = ModelSync(cfg)
# 1) 服务器还没发布模型 → skipped,且不动本地目录
unpublish()
r = ms.run(api, force=True)
ok('未发布模型 → skipped', r['status'] == 'skipped', r)
ok('未发布时没有下载请求',
not any('/file/' in k for k in SRV['hits']), SRV['hits'])
ok('未发布时不生成 model.json',
not os.path.exists('models/cls/model.json'))
# 2) 服务器版本清单不完整(少了 classes.json)→ failed,不下载
publish('v-broken', {'product_cls.onnx': b'whatever'},
drop_file='classes.json')
r = ms.run(api, force=True)
ok('清单缺文件 → failed', r['status'] == 'failed', r)
ok('清单缺文件时不下载',
not any('/file/' in k for k in SRV['hits']), SRV['hits'])
# 3) 坏 onnx(sha 对得上但 cv2 读不了)→ failed,本地不变
publish('v-junk', {'product_cls.onnx': b'\x08\x01not-onnx',
'classes.json': b'{"names":["a"],"imgsz":320}'})
r = ms.run(api, force=True)
ok('坏模型 → failed', r['status'] == 'failed', r)
ok('坏模型没有被换上去',
not os.path.exists('models/cls/product_cls.onnx'))
ok('坏模型没留下 .incoming',
not os.path.isdir('models/cls/.incoming'))
# 4) 真模型:发布 → 下载 → 替换
if os.path.isfile(REAL_ONNX) and os.path.isfile(REAL_CLASSES):
with open(REAL_ONNX, 'rb') as f:
onnx_bytes = f.read()
with open(REAL_CLASSES, 'rb') as f:
classes_bytes = f.read()
good = {'product_cls.onnx': onnx_bytes,
'classes.json': classes_bytes}
publish('v1', good)
r = ms.run(api, force=True)
ok('新版本 → updated', r['status'] == 'updated', r)
ok('版本号写进 model.json', ms.local_version() == 'v1',
ms.local_version())
with open('models/cls/product_cls.onnx', 'rb') as f:
got = hashlib.sha256(f.read()).hexdigest()
ok('落盘字节与清单一致',
got == hashlib.sha256(onnx_bytes).hexdigest())
lc = LocalClassifier({'assist': {
'model': 'models/cls/product_cls.onnx',
'classes': 'models/cls/classes.json'}})
ok('换上去的模型端上能加载', lc.available(), lc.reason())
# 5) 同版本再跑 → current,一个字节都不下
before = SRV['hits'].get(
'/api/mobile/weigh/cls-model/file/product_cls.onnx', 0)
r = ms.run(api, force=True)
after = SRV['hits'].get(
'/api/mobile/weigh/cls-model/file/product_cls.onnx', 0)
ok('同版本 → current', r['status'] == 'current', r)
ok('同版本不重复下载', before == after, SRV['hits'])
# 6) 清单 sha256 对不上 → failed,本地保留 v1
publish('v2', good, corrupt_sha=True)
r = ms.run(api, force=True)
ok('sha256 不符 → failed', r['status'] == 'failed', r)
ok('sha256 不符时版本仍是 v1', ms.local_version() == 'v1',
ms.local_version())
with open('models/cls/product_cls.onnx', 'rb') as f:
still = hashlib.sha256(f.read()).hexdigest()
ok('sha256 不符时文件没被动过',
still == hashlib.sha256(onnx_bytes).hexdigest())
# 7) 新版本(同字节不同版本号)→ 正常换版
publish('v3', good)
r = ms.run(api, force=True)
ok('换到 v3', r['status'] == 'updated' and ms.local_version() == 'v3',
r)
# 7.5) 同版本但文件被删(人为清目录 / 上次拷一半)→ 自动补装
os.remove('models/cls/product_cls.onnx')
r = ms.run(api, force=True)
ok('同版本但文件缺失 → 重新安装',
r['status'] == 'updated'
and os.path.isfile('models/cls/product_cls.onnx'), r)
# 7.6) 两个 os.replace 只成功第一个:第二个失败 → 必须回滚,不能留下
# 「新 onnx + 旧 classes + 旧 manifest」混合态(红队 B-2)。
# 真模型只有一份,这里打桩成「永远能加载」,只为让替换走到一半。
import core.recognition.model_sync as MS
with open('models/cls/product_cls.onnx', 'rb') as f:
old_onnx = f.read()
with open('models/cls/classes.json', 'rb') as f:
old_classes = f.read()
old_manifest = ms.local_manifest()
publish('v4', {'product_cls.onnx': b'\x08fake-new-onnx-b2',
'classes.json': b'{"names":["x"],"imgsz":320}'})
class _AlwaysLoadable: # 只测回滚,加载用例在上面 4)
def __init__(self, cfg=None):
pass
def available(self):
return True
def reason(self):
return ''
real_replace = os.replace
calls = {'n': 0}
def flaky_replace(src, dst):
calls['n'] += 1
if calls['n'] == 2: # 第 1 个文件已换、第 2 个换不动
raise OSError('模拟第二个文件替换失败')
return real_replace(src, dst)
saved_probe = MS.LocalClassifier
MS.LocalClassifier = _AlwaysLoadable
os.replace = flaky_replace
try:
r = ms.run(api, force=True)
finally:
os.replace = real_replace
MS.LocalClassifier = saved_probe
ok('第二个文件替换失败 → failed', r['status'] == 'failed', r)
with open('models/cls/product_cls.onnx', 'rb') as f:
b2_onnx = f.read()
with open('models/cls/classes.json', 'rb') as f:
b2_classes = f.read()
ok('失败后 onnx 回滚成旧版', b2_onnx == old_onnx)
ok('失败后 classes 仍是旧版', b2_classes == old_classes)
ok('失败后 model.json 仍是旧版', ms.local_manifest() == old_manifest,
ms.local_manifest())
ok('失败后不留 .incoming', not os.path.isdir('models/cls/.incoming'))
else:
print(' [--] 缺 %s 或 %s,跳过真实模型用例' % (REAL_ONNX, REAL_CLASSES))
# 8) auto_update=false → 不发请求
off = json.loads(json.dumps(cfg))
off['vision']['assist']['auto_update'] = False
unpublish()
r = ModelSync(off).run(api, force=True)
ok('auto_update=false → skipped', r['status'] == 'skipped', r)
ok('auto_update=false 时没有请求', SRV['hits'] == {}, SRV['hits'])
# 9) mock 模式 → skipped
mock_cfg = json.loads(json.dumps(cfg))
mock_cfg['server']['mock'] = True
r = ModelSync(mock_cfg).run(ApiClient(mock_cfg), force=True)
ok('mock → skipped', r['status'] == 'skipped', r)
finally:
os.chdir(old_cwd)
server.shutdown()
shutil.rmtree(work, ignore_errors=True)
print()
print('通过 %d 项,失败 %d 项' % (ok_n[0], bad_n[0]))
return 1 if bad_n[0] else 0
if __name__ == '__main__':
sys.exit(main())