Files
windows-fenjian/tools/_test_label_layout.py

279 lines
12 KiB
Python
Raw Permalink 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 -*-
"""标签版面不变量回归(v1.0.69)
背景:v1.0.68 起「有二维码时文字块贴顶」(左右布局)。改的只是起始 y,
但必须证明:**任何纸型 / 任何字段长度下,文字都不会越出纸边、不会丢内容、
不会压到二维码**——现场以前从没出现过「打一半」「少一行」。
检查项(对每组纸型 × 字段组合):
① 每一行都在纸内:x≥左留白、x+w≤右边界
② 有二维码时文字不压码(x+w ≤ 码左沿-4)
③ 垂直不越界:首行 y≥上留白、末行 y+字号≤纸高-下留白
④ 内容完整:所有行文字拼起来 == 原始输入(除非明确提示“已截断”)
⑤ 二维码整块在纸内
⑥ 贴顶规则:有码时首行 y==上留白;无码时垂直居中
不需要打印机/网络。
"""
import sys
import io
import os
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core.printing import label as L
ok = fail = 0
def check(name, cond, extra=''):
global ok, fail
if cond:
ok += 1
else:
fail += 1
print(' ✘ %s %s' % (name, extra))
SIZES = [(50, 50), (60, 40), (40, 60), (35, 25), (70, 50), (80, 30),
(80, 60), (76, 60)]
FIELDS = {
'分拣-短': ('分拣标签', ['客户: 王记饭店', '品名: 红富士苹果',
'重量: 5.62 斤', '日期: 11-22 18:30']),
'分拣-长': ('分拣标签', ['客户: 张三水果批发市场配送中心',
'品名: 农夫山泉饮用天然水 550ml×24 整箱',
'重量: 1234.56 斤', '日期: 2026-11-22 18:30']),
'入库-6行': ('验收标签', ['订单: ORD_WEB_20261122_BR003_0017',
'品名: 精瘦肉', '数量: 15.00 斤',
'供应商: 演示供应商名称比较长', '时间: 2026-11-22 18:30']),
'空值': ('分拣标签', ['客户: ', '品名: ', '重量: 0.00 斤', '日期: ']),
}
QRS = {'短码': 'CT2026112200001',
'长码': 'CT-WEB-20261122-BR003-000123456789',
'无码': ''}
def fail_reasons(p, cfg, qr):
g = p['geom']
w, h, dpm = g['w'], g['h'], g['dots_per_mm']
mx = max(int(round(2 * dpm)), 8)
my = max(int(round(1.5 * dpm)),
min(int(round(5 * dpm)), int(round(h * 0.10))))
q = p['qr']
out = []
gap = int(round(2 * dpm)) if q else 0
for ln in p['lines']:
if ln['x'] < mx - 1:
out.append('行越左边界 x=%d' % ln['x'])
if ln['x'] + ln['w'] > w:
out.append('行越右纸边 x+w=%d > %d' % (ln['x'] + ln['w'], w))
if q and ln['x'] + ln['w'] > q['x'] - gap:
out.append('行离码不足 %dmm x+w=%d, 码左沿=%d'
% (gap // int(round(dpm)), ln['x'] + ln['w'], q['x']))
if p['lines']:
y0 = p['lines'][0]['y']
yl = p['lines'][-1]['y'] + p['font']
if y0 < my - 1:
out.append('首行越上边界 y=%d' % y0)
if yl > h - my + 2:
out.append('末行越下边界 y+字=%d > %d' % (yl, h - my))
if q and y0 != my:
out.append('有码却未贴顶 y0=%d my=%d' % (y0, my))
if q:
if q['x'] + q['size'] > w - mx + 1:
out.append('二维码越右边界')
if q['y'] + q['size'] > h - my + 1:
out.append('二维码越下边界')
if q['y'] < my - 1:
out.append('二维码越上边界')
if q['size'] > int(round(w * 0.40)) + 2:
out.append('二维码超过纸宽 40%%(%d 点)' % q['size'])
# 二维码底边和最后一行底边对齐(参考图版式)
if p['lines']:
last_bottom = p['lines'][-1]['y'] + p['font']
if abs((q['y'] + q['size']) - last_bottom) > 1:
out.append('二维码底边未与末行对齐 码底=%d 末行=%d'
% (q['y'] + q['size'], last_bottom))
block_h = last_bottom - p['lines'][0]['y']
if q['size'] > block_h + 2:
out.append('二维码比文字块还高 码=%d 块=%d'
% (q['size'], block_h))
return out
def content_ok(p, title, fields):
"""内容必须一字不少地打出来:不允许任何形式的截断"""
src = L._safe_text(title or '') + ''.join(
L._safe_text(f or '') for f in fields)
got = ''.join(ln['text'] for ln in p['lines'])
return got == src, src, got
def no_truncate(p):
return not any('截断' in str(x) for x in (p.get('warnings') or [])), \
str(p.get('warnings'))
for (wmm, hmm) in SIZES:
for fname, (title, fields) in FIELDS.items():
for qname, qr in QRS.items():
cfg = {'width_mm': wmm, 'height_mm': hmm, 'dpi': 203,
'gap_mm': 2}
p = L.plan_label(cfg, title, fields, qr_data=qr)
tag = '%gx%g/%s/%s' % (wmm, hmm, fname, qname)
bad = fail_reasons(p, cfg, qr)
check('%s 版面' % tag, not bad, '; '.join(bad))
good, src, got = content_ok(p, title, fields)
check('%s 内容完整' % tag, good,
'源=%r 得=%r' % (src, got))
nt, ww = no_truncate(p)
check('%s 无截断' % tag, nt, ww)
check('%s 有码必打出整块' % tag, bool(p['qr']) == bool(qr),
'qr=%r' % (p['qr'],))
print('版面不变量:%d 通过,%d 失败' % (ok, fail))
# ---- 宽度模型:GBK 双字节字符必须是全角(×、·、— 这些不是汉字但仍是双字节)----
print('=== 宽度模型(GBK 双字节 = 全角)===')
check('× 按全角算', L._text_width('×', 24) == 24, str(L._text_width('×', 24)))
check('· 按全角算', L._text_width('·', 24) == 24, str(L._text_width('·', 24)))
check('— 按全角算', L._text_width('—', 24) == 24, str(L._text_width('—', 24)))
check('ASCII 仍按半角', abs(L._text_width('A', 24) - 24 * 0.56) < 0.01,
str(L._text_width('A', 24)))
# ---- 设置页预览那组数据:文字右缘离码至少 2mm(二维码静区) ----
print('=== 预览示例不压码 ===')
_p = L.plan_label({'width_mm': 60, 'height_mm': 40, 'dpi': 203}, '分拣标签',
['客户: 张三水果批发店',
'品名: 农夫山泉饮用天然水 550ml×24',
'数量: 1.00 桶', '日期: 11-04 19:02'],
qr_data='CT2026110400001234')
_q = _p['qr']
_gap = min(_q['x'] - (ln['x'] + ln['w']) for ln in _p['lines'])
check('示例文字离码 ≥2mm(16 dots)', _gap >= 16, 'gap=%d' % _gap)
check('示例字没被截断', not any('截断' in str(x) for x in _p['warnings']),
str(_p['warnings']))
# ---- 再验一遍真正的 TSPL 字节:坐标在纸内、文字一个字不少 ----
print('=== 实际 TSPL 指令校验 ===')
for (wmm, hmm) in ((50, 50), (60, 40)):
cfg = {'width_mm': wmm, 'height_mm': hmm, 'dpi': 203, 'gap_mm': 2}
data = L.build_picking_label_tspl(
cfg, '张三水果批发市场', '农夫山泉 550ml×24', 15.0, '斤',
'2026-11-22 18:30', 'CT-WEB-20261122-BR003-000123456789')
s = data.decode('gbk', errors='replace')
tag = 'TSPL %gx%g' % (wmm, hmm)
# 长文字会折成多条 TEXT,拼起来才是完整内容(不能按整段子串找)
import re
payloads = re.findall(r'TEXT \d+,\d+,"TSS\d+\.BF2",0,1,1,"([^"]*)"', s)
payloads += re.findall(r'QRCODE \d+,\d+,\w,\d,\w,\d,M2,S1,"([^"]*)"', s)
joined = ''.join(payloads)
for need in ('张三水果批发市场', '农夫山泉 550ml×24', '15.00',
'2026-11-22 18:30', 'CT-WEB-20261122-BR003-000123456789'):
check('%s 含 %s' % (tag, need[:10]), need in joined,
'内容丢了:%r' % joined)
# TEXT x,y,"font",0,1,1,"..." → 坐标都在纸内
import re
for m in re.finditer(r'TEXT (\d+),(\d+),"TSS(\d+)', s):
x, y, f = int(m.group(1)), int(m.group(2)), int(m.group(3))
check('%s TEXT 坐标' % tag,
x >= 0 and y >= 0 and x < wmm * 8 and y + f <= hmm * 8,
'x=%d y=%d f=%d' % (x, y, f))
for m in re.finditer(r'QRCODE (\d+),(\d+),H,(\d+)', s):
x, y, cell = int(m.group(1)), int(m.group(2)), int(m.group(3))
mods = L._qr_modules(len('CT-WEB-20261122-BR003-000123456789'.encode('gbk')))
check('%s QR 坐标' % tag,
x + mods * cell <= wmm * 8 and y + mods * cell <= hmm * 8,
'x=%d y=%d size=%d' % (x, y, mods * cell))
print('总计:%d 通过,%d 失败' % (ok, fail))
# ---- 随机长文本压力:真实前缀 + 随机长度,4 种常用纸型 ----
print('=== 随机长文本压力(不截断 / 不缺码) ===')
import random
random.seed(20261123)
POOL = ('红富士苹果蔬菜水果批发市场配送中心农夫山泉饮用天然水'
'上海青小棠菜土豆白萝卜冬瓜南瓜青椒黄果柑蒜苗菠菜'
'abcABC0123456789 -_/().:×·()')
STRESS_SIZES = [(60, 40), (76, 60), (80, 60), (50, 50), (70, 50)]
def _rand_txt(n):
return ''.join(random.choice(POOL) for _ in range(n))
for i in range(120):
wmm, hmm = STRESS_SIZES[i % len(STRESS_SIZES)]
cfg = {'width_mm': wmm, 'height_mm': hmm, 'dpi': 203, 'gap_mm': 2}
title = '分拣标签'
fields = ['客户: ' + _rand_txt(random.randint(4, 20)),
'品名: ' + _rand_txt(random.randint(4, 24)),
'数量: %.2f 桶' % (random.random() * 999),
'日期: 11-23 12:29']
qr = 'CT' + ''.join(random.choice('0123456789ABCDEF') for _ in range(18))
p = L.plan_label(cfg, title, fields, qr_data=qr)
src = L._safe_text(title) + ''.join(L._safe_text(f) for f in fields)
got = ''.join(ln['text'] for ln in p['lines'])
q = p['qr']
g = p['geom']
bad = []
if p.get('overflow'):
bad.append('overflow=%s' % (p['warnings'],))
if got != src:
bad.append('内容不完整')
for ln in p['lines']:
if ln['x'] + ln['w'] > g['w'] or ln['y'] + ln['font'] > g['h']:
bad.append('行越纸')
if q and ln['x'] + ln['w'] > q['x']:
bad.append('文字压码')
if not q:
bad.append('缺码')
elif (q['x'] < 0 or q['y'] < 0 or q['x'] + q['size'] > g['w']
or q['y'] + q['size'] > g['h']):
bad.append('码越纸')
check('压力 #%d %dx%d' % (i, wmm, hmm), not bad,
'%s | %r' % ('; '.join(sorted(set(bad))), fields))
# ---- 打不出来时坚决不发数据:排不下 / 容器码过长 ----
print('=== 排不下就拒打(不发半张) ===')
sent = []
class _FakePrinter(L.LabelPrinter):
def _send(self, data, doc_name='标签'):
sent.append(data)
return True, 'fake'
pr = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 35, 'height_mm': 25,
'gap_mm': 2, 'dpi': 203}})
ok_bad, msg_bad = pr.print_picking('客' * 120, '品' * 120, 1.0, '斤', 'CT1')
check('排不下时返回失败', ok_bad is False, str((ok_bad, msg_bad)))
check('排不下时一个字节都不发', not sent, str(len(sent)))
pr2 = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 60,
'height_mm': 40, 'gap_mm': 2, 'dpi': 203}})
ok_ok, msg_ok = pr2.print_picking('王记饭店', '红富士苹果', 5.62, '斤',
'CT-OK-1')
check('正常数据能打', ok_ok is True and bool(sent), str((ok_ok, msg_ok)))
if sent:
_s = sent[-1].decode('gbk', errors='replace')
check('正常数据带整块码',
'QRCODE ' in _s and '"CT-OK-1"' in _s, _s[:160])
pr3 = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 60,
'height_mm': 40, 'gap_mm': 2, 'dpi': 203}})
sent[:] = []
ok_long, msg_long = pr3.print_picking('王记饭店', '红富士苹果', 5.62, '斤',
'C' * 1300)
check('容器码超长时拒打', ok_long is False and not sent,
str((ok_long, msg_long, len(sent))))
check('QR 容量表:1273 字节 = 177 模块',
L._qr_modules(1273) == 177, str(L._qr_modules(1273)))
print('总计:%d 通过,%d 失败' % (ok, fail))
sys.exit(1 if fail else 0)