feat: add gated CH5 quiver support and unified regression runner

This commit is contained in:
shen
2026-10-22 17:41:47 -07:00
parent 60ed66692e
commit 3784137b4f
39 changed files with 1617 additions and 23 deletions
+46
View File
@@ -0,0 +1,46 @@
# 限时箭筒候选数据生成
这是F19隔离测试数据生成器,不是安装器。只处理79502/79503/79504,79501因客户端/服务端及价格期限冲突排除。
先构建工具:
```sh
cmake --build build/port-gate/macos --target item_proto_patch eterpack_pack -j4
```
从当前注册资源包读取基线,按照用户确认的AVA2重建规则,明确覆盖三个限时型号:
```sh
python3 tools/server/ava2-items/make_quiver.py \
--ava ../AVA2 \
--reader ../metin2-server/src/server/db/src/ProtoReader.cpp \
--client-root Client \
--output build/ch5-quiver-candidate-01 \
--proto-tool build/port-gate/macos/src/port/item_proto_patch \
--packer build/port-gate/macos/src/port/eterpack_pack \
--replace-existing-quivers \
--expected-base-sha256 ea2a000cb33f5c9c94d3668a4e0b7840ada284c190281ac26dbe2ad05d3d402e
```
散列绑定本批当前基线;基线改变须重新审查差异,不要直接换成新散列绕过检查。输出目录必须不存在;复跑需使用新的目录名。没有覆盖参数时,现有定义不一致会被拒绝;覆盖只限三个型号,完整数值前后差异进入manifest。
生成内容:
- `items-server.tsv`:三个服务端文本行,GBK中文名称。
- `items-client.tsv`:匹配的客户端数值行。
- `quiver.eix/.epk`:`locale/zh`、`locale/newcibn`原型、物品清单与说明,以及私有图标,共7文件;打包后通过客户端读取器逐文件回读。
- `base-item-proto`、`manifest.json`:冻结的原型基线、实际Index/输入文件散列、两份归档来源散列、覆盖差异、产物散列和未完成门槛。
输入原型/清单/说明都通过原生`PackInitialize`和`GetFromPack`读取,支持当前标准/五区密钥回退,不从当前工作目录的松散文件取值。可选`--locale DIR`仅作额外一致性校验,三个文件中任何一个与有效资源不同就失败;不再将解包目录默认当作有效资源。
默认转换器仍锁定箭筒;只有专用生成器显式启用三个经过严格校验的限时型号。两份归档字段必须一致,不接受改变价格、期限、穿戴位置、效果或标志的输入。沿用当前四职业转换器,移除暂未启用的`ANTI_WOLFMAN`标志;其余职业/交易/丢弃限制保留。未来启用狼人前必须重新核对该限制,不能复用本批数据直接开放第五职业。
本轮接受的重建差异:五区客户端79502的买价字段550000改为AVA2两份服务端原型的0;7/15/30天REAL_TIME不变。0只是归档原型字段,**不是免费出售的授权**;本工具不添加任何商店库存、NPC售卖或物品获得途径。
不要直接将本输出安装到生产或优先挂载到正式客户端。仍须匹配的服务端构建、隔离服原型/角色生命周期验证、外观/弹道、Android构建与真机验收。生成器不会修改Client的Index、locale.cfg或包文件,也不会修改数据库、服务器配置或重启进程。
测试:
```sh
python3 -m unittest discover -s tools/server/ava2-items/tests
```
+25 -1
View File
@@ -126,10 +126,33 @@ def names():
for month in range(1,13):result[25149+month]='%d月战令票'%month
return result
def convert(cols,E,imported):
QUIVER_DURATIONS={79502:604800,79503:1296000,79504:2592000}
def validate_quiver(cols,E):
"""Only the three unambiguous archived timed variants; never enable 79501."""
if len(cols)<33:raise ValueError('truncated quiver row')
c=[x.strip() for x in cols[:33]]
v=int(c[0])
if v not in QUIVER_DURATIONS or c[2:5]!=['ITEM_WEAPON','WEAPON_QUIVER','1']:
raise ValueError('unsupported quiver variant')
if c[14:18]!=['REAL_TIME',str(QUIVER_DURATIONS[v]),'LIMIT_NONE','0']:
raise ValueError('quiver duration differs from verified archive')
if c[7]!='WEAR_ARROW' or c[8]!='NONE' or c[9:14]!=['0']*5:
raise ValueError('quiver wear/price/refine contract differs')
if c[18:24]!=['APPLY_NONE','0']*3 or c[24:33]!=['17','4','0','25','0','0','0','0','0']:
raise ValueError('quiver applies/values differ')
expected={'ANTI_MUSA','ANTI_SURA','ANTI_MUDANG','ANTI_WOLFMAN'}
expected |= {'ANTI_DROP','ANTI_GIVE','ANTI_MYSHOP','ANTI_SAFEBOX'} if v==79502 else {'ANTI_PKDROP'}
if set(tokens(c[5]))!=expected or set(tokens(c[6]))!={'ITEM_STACKABLE','ITEM_SLOW_QUERY'}:
raise ValueError('quiver flags differ')
if E['sub'][E['type'].index('ITEM_WEAPON')].index('WEAPON_QUIVER')!=9:
raise ValueError('quiver runtime subtype must be 9')
def convert(cols,E,imported,enable_quiver=False):
"""AVA2 item_proto.txt row (str columns) -> (server row columns, client numeric fields, kept?)."""
c=[x.strip() for x in cols[:33]]
t,st=c[2],c[3]
if enable_quiver:validate_quiver(cols,E)
kept=t in KEEP_TYPES or (t,st) in KEEP_SUBTYPES or ((t,st)==('ITEM_USE','USE_CHANGE_ATTRIBUTE') and
any(lo<=int(c[0])<=hi for lo,hi in ENCHANT_KEEP)) or (
(t,st) in (('ITEM_USE','USE_CHANGE_ATTRIBUTE'),('ITEM_USE','USE_ADD_ATTRIBUTE')) and int(c[0]) in PENDANT_SCROLLS) or (
@@ -139,6 +162,7 @@ def convert(cols,E,imported):
int(c[0]) in (70002,39063,39064) and (t,st)==('ITEM_USE','USE_SPECIAL'))
if t=='ITEM_COSTUME' and st in ('COSTUME_BODY','COSTUME_HAIR') and int(c[0]) in (41119,41120,41121,41122,45005,45006,45057,45058):kept=True
if stone_lock_reason(c,E):kept=False
if enable_quiver:kept=True
anti=tokens(c[5]);flags=tokens(c[6])
if 'ITEM_STACKABLE' in anti:anti.remove('ITEM_STACKABLE');flags.append('ITEM_STACKABLE')
anti=[a for a in dict.fromkeys(anti) if a in E['anti']];flags=[f for f in dict.fromkeys(flags) if f in E['flag']]
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env python3
"""Build a private, opt-in timed-quiver proto/resource patch; never install it.
Both archived server configurations must agree. Nonmatching base vnums require
explicit hash-bound reconstruction. 79501 and server/shop files remain untouched.
"""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import tarfile
import tempfile
import make_items
import quiver_assets
IDS=set(make_items.QUIVER_DURATIONS)
MEMBERS=('home/srv1/db/item_proto.txt','home/srv1/share/conf/item_proto.txt')
def digest(data):
return hashlib.sha256(data).hexdigest()
def dump_proto(tool,raw):
# Read a frozen snapshot, never a base file another build can rewrite.
with tempfile.TemporaryDirectory(prefix='ch5-quiver-proto-') as folder:
path=Path(folder)/'item_proto';path.write_bytes(raw)
return subprocess.run([str(tool),'--dump',str(path)],capture_output=True,check=True).stdout
def selected(raw):
result={}
for line in raw.splitlines():
c=line.split(b'\t')
if not c[0].strip().isdigit() or int(c[0]) not in IDS:continue
v=int(c[0])
if v in result:raise ValueError('duplicate quiver row: '+str(v))
if len(c)<33:raise ValueError('truncated quiver row')
# Source name is replaced with a Chinese display name, never used as a rule.
result[v]=[x.decode('latin1' if i==1 else 'ascii').strip() for i,x in enumerate(c[:33])]
if set(result)!=IDS:raise ValueError('archive must contain all three timed quivers')
return result
def merge_text(raw,rows):
output=[]
for line in raw.splitlines():
key=line.split(b'\t',1)[0]
if not key.isdigit() or int(key) not in IDS:output.append(line)
return b'\n'.join(output+[rows[v] for v in sorted(rows)])+b'\n'
def dump_rows(raw):
rows={}
for line in raw.splitlines():
fields=line.split(b'\t',1)[0].split()
if len(fields)!=31:raise ValueError('invalid proto tool dump')
key=int(fields[0])
if key in rows:raise ValueError('duplicate proto dump row')
rows[key]=line
return rows
def verify_patch(before,after,expected):
before=dump_rows(before);after=dump_rows(after)
if set(after)!=set(before)|IDS:raise ValueError('proto patch changed unexpected IDs')
for v,line in before.items():
if v not in IDS and after[v]!=line:raise ValueError('unrelated proto changed: '+str(v))
for v in IDS:
if list(map(int,after[v].split(b'\t',1)[0].split()))!=expected[v]:
raise ValueError('patched client numeric fields differ: '+str(v))
return len(set(before)-IDS)
def validate_base(raw,expected,replace_existing=False,expected_base_sha256=None,base_sha256=None):
if expected_base_sha256 is not None and expected_base_sha256!=base_sha256:
raise ValueError('base proto SHA256 mismatch')
if replace_existing and not expected_base_sha256:
raise ValueError('replacing existing quivers requires expected base SHA256')
conflicts={}
for v,line in dump_rows(raw).items():
if v in IDS:
fields=list(map(int,line.split(b'\t',1)[0].split()))
if fields!=expected[v]:conflicts[v]={'before':fields,'after':expected[v]}
if conflicts and not replace_existing:
raise ValueError('base client vnum conflicts: '+','.join(map(str,sorted(conflicts))))
return conflicts
def client_inputs(client_root,packer):
config=(client_root/'locale.cfg').read_text().split()
if len(config)!=3 or config[2] not in ('zh','newcibn'):
raise ValueError('only verified zh/newcibn locale targets are supported')
index_hash=digest((client_root/'pack/Index').read_bytes())
verified={};files={}
with tempfile.TemporaryDirectory(prefix='ch5-quiver-effective-') as folder:
for name in ('item_proto','item_list.txt','itemdesc.txt'):
probe=Path(folder)/name;entry='locale/'+config[2]+'/'+name
subprocess.run([str(packer),'--read-client',str(client_root),entry,str(probe)],check=True,capture_output=True)
files[name]=probe.read_bytes();verified[entry]=digest(files[name])
if digest((client_root/'pack/Index').read_bytes())!=index_hash:
raise ValueError('client Index changed during generation')
return files,{'files':verified,'index_sha256':index_hash}
def build(ava,reader,locale,output,proto_tool,packer,replace_existing=False,expected_base_sha256=None,client_root=None,with_motion_assets=False):
output=output.resolve()
if output.exists():raise ValueError('output must be a new directory')
if client_root is None:raise ValueError('client root required to bind the effective catalogue')
source=ava/'2. Backup SF+SRC and SQL/FILES+SRC.tgz'
with tarfile.open(source,'r:gz') as archive:
sources={name:archive.extractfile(name).read() for name in MEMBERS}
sets=[selected(raw) for raw in sources.values()]
for v in sorted(IDS):
if sets[0][v][:1]+sets[0][v][2:]!=sets[1][v][:1]+sets[1][v][2:]:
raise ValueError('archived quiver rules conflict: '+str(v))
enums=make_items.enums(reader)
server_rows={};client_rows={};expected={};names={}
for v in sorted(IDS):
name='无限箭筒(%d天)'%(make_items.QUIVER_DURATIONS[v]//86400)
s,c,kept=make_items.convert(sets[0][v],enums,IDS,enable_quiver=True)
assert kept
s[1]=name;names[v]=name
server_rows[v]='\t'.join(s).encode('gbk')
client_rows[v]=('\t'.join(map(str,c))+'\t'+name).encode('gbk')
expected[v]=c
# By default reject replacements. An explicit, hash-bound AVA2 reconstruction
# may replace only these three IDs, recording their complete numeric delta.
files,effective=client_inputs(client_root,packer)
if locale is not None:
for name,raw in files.items():
if digest((locale/name).read_bytes())!=digest(raw):
raise ValueError('locale source does not match effective client pack: '+name)
base_bytes=files['item_proto'];base_hash=digest(base_bytes)
raw_text={name:files[name] for name in ('item_list.txt','itemdesc.txt')}
dumped=dump_proto(proto_tool,base_bytes)
conflicts=validate_base(dumped,expected,replace_existing,expected_base_sha256,base_hash)
pack_maker=ava/'1. Client DEV/pack_maker'
assets_index=make_items.pack_index(pack_maker)
source_icon='icon/item/79501.tga'
if source_icon not in assets_index or not assets_index[source_icon].is_file():
raise ValueError('verified quiver icon missing')
motion_files={};motion_records={}
if with_motion_assets:
with tempfile.TemporaryDirectory(prefix='ch5-quiver-motion-') as folder:
def current(path):
probe=Path(folder)/'entry'
if probe.exists():probe.unlink()
result=subprocess.run([str(packer),'--read-client',str(client_root),path,str(probe)],capture_output=True)
return probe.read_bytes() if result.returncode==0 else None
def reference(path):
source=assets_index.get(path)
return source.read_bytes() if source and source.is_file() else None
motion_files,motion_records=quiver_assets.collect(current,reference)
if digest((client_root/'pack/Index').read_bytes())!=effective['index_sha256']:
raise ValueError('client Index changed during motion discovery')
output.mkdir(parents=True,exist_ok=False)
frozen=output/'base-item-proto';frozen.write_bytes(base_bytes)
(output/'items-server.tsv').write_bytes(b'\n'.join(server_rows.values())+b'\n')
(output/'items-client.tsv').write_bytes(b'\n'.join(client_rows.values())+b'\n')
assets=output/'assets'
for name,raw in motion_files.items():
dest=assets/name;dest.parent.mkdir(parents=True,exist_ok=True);dest.write_bytes(raw)
# Private path: updating three variants must not change 79501's shared icon.
icon='icon/ch5_quiver/79501.tga'
(assets/icon).parent.mkdir(parents=True)
shutil.copy2(assets_index[source_icon],assets/icon)
for code in ('zh','newcibn'):
target=assets/'locale'/code;target.mkdir(parents=True)
subprocess.run([str(proto_tool),str(frozen),str(output/'items-client.tsv'),str(target/'item_proto')],check=True)
after=dump_proto(proto_tool,(target/'item_proto').read_bytes())
unchanged=verify_patch(dumped,after,expected)
listing={v:('%d\tETC\t%s'%(v,icon)).encode() for v in sorted(IDS)}
descriptions={v:('%d\t%s\t弓手箭槽弹药,射击不消耗数量;获得后按实时期限到期,离线也计时。'%
(v,names[v])).encode('gbk') for v in sorted(IDS)}
(target/'item_list.txt').write_bytes(merge_text(raw_text['item_list.txt'],listing))
(target/'itemdesc.txt').write_bytes(merge_text(raw_text['itemdesc.txt'],descriptions))
subprocess.run([str(packer),str(output/'quiver'),str(assets),''],check=True)
report={'version':1,'items':sorted(IDS),'excluded':[79501],'installed':False,
'verified_unchanged_proto_records':unchanged,
'source_sha256':{p:digest(raw) for p,raw in sources.items()},
'base_proto_sha256':base_hash,'proto_reader_sha256':digest(reader.read_bytes()),
'effective_client_base':effective,
'explicit_replacements':conflicts,
'motion_assets':motion_records,
'differences':['ANTI_WOLFMAN omitted like existing converter: Wolfman disabled; re-evaluate before enabling fifth job',
'Chinese names/descriptions; no price/duration invention'],
'requires':['matched client/server build','verified test-only proto install','live item lifecycle and Android acceptance'],
'files':{p.relative_to(output).as_posix():digest(p.read_bytes()) for p in sorted(output.rglob('*')) if p.is_file()}}
(output/'manifest.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
return report
def main():
parser=argparse.ArgumentParser(description=__doc__)
for name in ('ava','reader','output','proto_tool','packer'):
parser.add_argument('--'+name.replace('_','-'),type=Path,required=True)
parser.add_argument('--locale',type=Path,help='optional reference folder; every file must equal the effective runtime bytes')
parser.add_argument('--replace-existing-quivers',action='store_true',help='replace only three timed variants using the verified AVA2 rules')
parser.add_argument('--expected-base-sha256',help='required with replacement; must match the exact base proto')
parser.add_argument('--client-root',type=Path,required=True,help='bind proto/list/description to actual registered runtime packs')
parser.add_argument('--with-motion-assets',action='store_true',help='resolve quiver motion/effect closure; stage only files missing from registered packs')
args=parser.parse_args()
result=build(args.ava,args.reader,args.locale,args.output,args.proto_tool.resolve(),args.packer.resolve(),
args.replace_existing_quivers,args.expected_base_sha256,args.client_root,args.with_motion_assets)
print(json.dumps({'items':result['items'],'installed':False,'output':str(args.output)}))
if __name__=='__main__':main()
+40
View File
@@ -0,0 +1,40 @@
"""Resolve quiver motion/effect dependencies without replacing existing artwork."""
import hashlib
import posixpath
import re
TEXT_EXTENSIONS=('.msa','.msf','.mse','.mde','.mss')
REFERENCE=re.compile(rb'["\']([^"\'\r\n]+\.(?:msa|msf|mse|mde|mss|gr2|dds|tga|jpg|png|wav|mp3))["\']',re.I)
MOTIONS=('wait.msa','wait_1.msa','walk.msa','run.msa','damage.msa',
'damage_1.msa','damage_2.msa','damage_3.msa','attack_special.msa')
def dependencies(path,raw):
out=[]
for value in REFERENCE.findall(raw):
name=value.decode('ascii').lower().replace('\\','/')
if not name.startswith(('d:/','sound/','icon/')):
name=posixpath.dirname(path)+'/'+name
name=posixpath.normpath(name)
if not name.startswith(('d:/ymir work/','sound/','icon/')):
raise ValueError('invalid quiver dependency: '+name)
out.append(name)
return out
def collect(read_current,read_reference,maximum=256):
queue=['d:/ymir work/%s/assassin/bow/%s'%(sex,name)
for sex in ('pc','pc2') for name in MOTIONS]
records={};missing={}
while queue:
path=queue.pop()
if path in records:continue
if len(records)>=maximum:raise ValueError('quiver resource closure exceeds limit')
raw=read_current(path);origin='registered_client'
if raw is None:
raw=read_reference(path);origin='ava2_reference'
if raw is None:raise ValueError('missing quiver dependency: '+path)
missing[path]=raw
records[path]={'origin':origin,'sha256':hashlib.sha256(raw).hexdigest(),'bytes':len(raw)}
if path.endswith(TEXT_EXTENSIONS):queue.extend(dependencies(path,raw))
return missing,records
@@ -0,0 +1,114 @@
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
HERE=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(HERE))
import make_items as m
import make_quiver as q
READER=HERE.parents[3]/'metin2-server/src/server/db/src/ProtoReader.cpp'
PACKER=HERE.parents[2]/'build/port-gate/macos/src/port/eterpack_pack'
def row(v=79502):
anti='ANTI_MUSA | ANTI_SURA | ANTI_MUDANG | ANTI_WOLFMAN'
anti+=' | ANTI_DROP | ANTI_GIVE | ANTI_MYSHOP | ANTI_SAFEBOX' if v==79502 else ' | ANTI_PKDROP'
return [str(v),'original','ITEM_WEAPON','WEAPON_QUIVER','1',anti,
'ITEM_STACKABLE | ITEM_SLOW_QUERY','WEAR_ARROW','NONE',*(['0']*5),
'REAL_TIME',str(m.QUIVER_DURATIONS.get(v,0)),'LIMIT_NONE','0',
*(['APPLY_NONE','0']*3),'17','4','0','25','0','0','0','0','0']
class QuiverDataTests(unittest.TestCase):
def setUp(self):self.enums=m.enums(READER)
def test_default_is_locked_and_opt_in_preserves_both_sides(self):
for v in sorted(q.IDS):
self.assertFalse(m.convert(row(v),self.enums,q.IDS)[2])
server,client,kept=m.convert(row(v),self.enums,q.IDS,enable_quiver=True)
self.assertTrue(kept)
self.assertEqual(server[2:4],['ITEM_WEAPON','WEAPON_QUIVER'])
self.assertEqual(client[1:3],[1,9])
self.assertEqual(server[14:18],['REAL_TIME',str(m.QUIVER_DURATIONS[v]),'LIMIT_NONE','0'])
self.assertEqual(client[13:17],[self.enums['limit'].index('REAL_TIME'),m.QUIVER_DURATIONS[v],0,0])
self.assertEqual(server[7],'WEAR_ARROW')
self.assertEqual(client[6],1<<self.enums['wear'].index('WEAR_ARROW'))
self.assertNotIn('ANTI_WOLFMAN',server[5])
self.assertEqual(client[4],sum(1<<self.enums['anti'].index(x) for x in m.tokens(server[5])))
def test_excluded_and_altered_rules_fail_closed(self):
bad=[row(79501),row()[:-1]]
for index,value in ((3,'WEAPON_ARROW'),(7,'WEAR_WEAPON'),(9,'1'),(14,'LIMIT_NONE'),
(15,'86400'),(5,'ANTI_MUSA'),(24,'18'),(6,'ITEM_STACKABLE')):
changed=row();changed[index]=value;bad.append(changed)
for changed in bad:
with self.assertRaises(ValueError):m.convert(changed,self.enums,q.IDS,enable_quiver=True)
def test_archive_rows_reject_duplicates_partial_and_bad_encoding(self):
raw=b'\n'.join('\t'.join(row(v)).encode() for v in sorted(q.IDS))
self.assertEqual(set(q.selected(raw)),q.IDS)
for value in (raw.split(b'\n')[0],raw+b'\n'+raw.split(b'\n')[0],raw.replace(b'REAL_TIME',b'\xff',1)):
with self.assertRaises((ValueError,UnicodeError)):q.selected(value)
def test_text_merge_preserves_unrelated_and_excluded_model(self):
raw=b'#header\r\n79501\tkeep\r\n79502\told\r\n80000\tother\r\n'
result=q.merge_text(raw,{79502:b'79502\tnew'})
self.assertIn(b'79501\tkeep',result)
self.assertIn(b'80000\tother',result)
self.assertEqual(result.count(b'79502\t'),1)
self.assertIn(b'79502\tnew',result)
def test_proto_roundtrip_rejects_other_changes_and_wrong_numeric_data(self):
expected={v:m.convert(row(v),self.enums,q.IDS,enable_quiver=True)[1] for v in sorted(q.IDS)}
extra=b'79501 '+b'0 '*29+b'0\tunchanged'
before=extra+b'\n'
rows={v:(' '.join(map(str,fields))+'\tname').encode() for v,fields in expected.items()}
after=before+b'\n'.join(rows.values())+b'\n'
self.assertEqual(q.verify_patch(before,after,expected),1)
for value in (after.replace(b'unchanged',b'modified'),b'\n'.join(rows.values()),
after.replace(b'79502 1 9',b'79502 1 6')):
with self.assertRaises(ValueError):q.verify_patch(before,value,expected)
def test_reconstruction_override_is_explicit_hash_bound_and_audited(self):
expected={v:m.convert(row(v),self.enums,q.IDS,enable_quiver=True)[1] for v in sorted(q.IDS)}
old=expected[79502][:];old[8]=550000
raw=(' '.join(map(str,old))+'\toldname\n').encode()
with self.assertRaises(ValueError):q.validate_base(raw,expected)
with self.assertRaises(ValueError):q.validate_base(raw,expected,True)
with self.assertRaises(ValueError):q.validate_base(raw,expected,True,'stale','current')
changes=q.validate_base(raw,expected,True,'current','current')
self.assertEqual(changes[79502]['before'][8],550000)
self.assertEqual(changes[79502]['after'][8],0)
self.assertEqual(set(changes),{79502})
@unittest.skipUnless(PACKER.is_file(),'build eterpack_pack to run native pack probe')
class NativePackProbeTests(unittest.TestCase):
def test_runtime_precedence_pack_only_and_no_overwrite(self):
with tempfile.TemporaryDirectory(prefix='ch5-pack-probe-') as directory:
root=Path(directory);client=root/'client';pack=client/'pack';pack.mkdir(parents=True)
for name,payload in (('first',b'first wins'),('second',b'second loses')):
source=root/name;entry=source/'locale/zh/item_proto';entry.parent.mkdir(parents=True)
entry.write_bytes(payload)
subprocess.run([str(PACKER),str(pack/name),str(source),''],check=True,capture_output=True)
(pack/'Index').write_text('PACK\n*\nfirst\n*\nsecond\n')
loose=root/'locale/zh/item_proto';loose.parent.mkdir(parents=True);loose.write_bytes(b'loose loses')
output=root/'readback'
args=[str(PACKER),'--read-client',str(client),'locale/zh/item_proto',str(output)]
subprocess.run(args,cwd=root,check=True,capture_output=True)
self.assertEqual(output.read_bytes(),b'first wins')
self.assertNotEqual(subprocess.run(args,cwd=root,capture_output=True).returncode,0)
self.assertEqual(output.read_bytes(),b'first wins')
missing=root/'missing'
args[-2:] = ['locale/zh/absent',str(missing)]
self.assertNotEqual(subprocess.run(args,cwd=root,capture_output=True).returncode,0)
self.assertFalse(missing.exists())
invalid=[str(PACKER),'--read-client',str(client),'missing-output']
self.assertEqual(subprocess.run(invalid,cwd=root,capture_output=True).returncode,2)
self.assertFalse((root/'--read-client.eix').exists())
if __name__=='__main__':unittest.main()