883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
178 lines
12 KiB
Python
178 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
"""Mock-only complete public-item export: no actual DB, Git, client or services."""
|
||
from copy import deepcopy
|
||
import hashlib
|
||
import json
|
||
from pathlib import Path
|
||
import re
|
||
import struct
|
||
import sys
|
||
import tempfile
|
||
from unittest.mock import patch
|
||
|
||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
|
||
import item_template_snapshot as m
|
||
|
||
REV='a'*40
|
||
DATA=[dict(entry=i,name='Item '+str(i)+' é\\line\n"quote"',description=None if i==17 else 'NULL') for i in (1,5,17,900,4294967295)]
|
||
|
||
def hex_rows(rows):return '\n'.join(json.dumps(row,ensure_ascii=False).encode().hex() for row in rows)
|
||
class PublicDB:
|
||
def __init__(self,mode=None,data=None,table='item_template'):
|
||
self.table=table
|
||
self.mode=mode;self.queries=[];self.row_queries=0;self.inventory_pass=0;self.schema_calls=0;self.version_calls=0
|
||
self.data=deepcopy(DATA if data is None else data)
|
||
def __call__(self,sql):
|
||
self.queries.append(sql)
|
||
if self.table=='spell_template':
|
||
assert 'tw_world.item_template'not in sql
|
||
sql=sql.replace('tw_world.spell_template','tw_world.item_template')
|
||
if sql=='SHOW COLUMNS FROM tw_world.item_template;':
|
||
self.schema_calls+=1
|
||
kind='varchar(256)' if self.mode=='schema-drift' and self.schema_calls>1 else 'varchar(255)'
|
||
return ('entry\tint(10) unsigned\tNO\tPRI\t0\t\nname\t'+kind+'\tNO\t\t\t\ndescription\ttext\tYES\t\tNULL\t').strip()
|
||
if sql=='SHOW CREATE TABLE tw_world.item_template;':return self.table+'\tCREATE TABLE `'+self.table+'` (`entry` int unsigned PRIMARY KEY, `name` varchar(255), `description` text) ENGINE=MyISAM'
|
||
if sql=='SELECT VERSION();':
|
||
self.version_calls+=1
|
||
return '10.6.23-MariaDB' if self.mode=='version-drift' and self.version_calls>1 else '10.6.22-MariaDB'
|
||
if sql=="SHOW TABLES FROM tw_world LIKE 'migrations';":return '' if self.mode=='no-migrations' else 'migrations'
|
||
if sql=="SELECT HEX(JSON_OBJECT('Id',Id,'Name',Name,'Hash',Hash,'AppliedAt',AppliedAt)) FROM tw_world.migrations ORDER BY Id LIMIT 100001;":
|
||
return hex_rows([dict(Id=1,Name='public-schema',Hash='migration-hash',AppliedAt='2026-10-17 00:00:00')])
|
||
found=re.fullmatch(r'SELECT entry FROM tw_world.item_template(?: WHERE entry>([0-9]+))? ORDER BY entry LIMIT ([0-9]+);',sql)
|
||
if found:
|
||
last,bound=found.groups();bound=int(bound)
|
||
if last is None:self.inventory_pass+=1
|
||
values=[row['entry'] for row in self.data]
|
||
if self.mode=='empty':values=[]
|
||
if self.mode=='range':values=[-1]+values
|
||
if self.mode=='id-drift' and self.inventory_pass>1:values=sorted(values+[77])
|
||
values=[value for value in values if last is None or value>int(last)][:bound]
|
||
if self.mode=='duplicate-id' and last is None:values=[1,1]
|
||
return '\n'.join(map(str,values))
|
||
found=re.fullmatch(r"SELECT HEX\(JSON_OBJECT\('entry',`entry`,'name',`name`,'description',`description`\)\) FROM tw_world.item_template WHERE entry IN \(([0-9,]+)\) ORDER BY entry;",sql)
|
||
if found:
|
||
self.row_queries+=1;ids=list(map(int,found.group(1).split(',')))
|
||
assert 1<=len(ids)<=2 # Test chunk size is a query bound, not just a file boundary.
|
||
rows=[deepcopy(row) for row in self.data if row['entry'] in ids]
|
||
if self.mode=='missing':rows=rows[:-1]
|
||
if self.mode=='duplicate-row' and rows:rows.append(deepcopy(rows[0]))
|
||
if self.mode=='missing-column' and rows:del rows[0]['description']
|
||
if self.mode=='content-drift' and self.row_queries>3 and rows:rows[0]['name']='changed after first pass'
|
||
if self.mode=='duplicate-field':return b'{"entry":1,"name":"a","name":"b","description":null}'.hex()
|
||
return hex_rows(rows)
|
||
raise AssertionError('Unexpected query; no account/character access, writes, locks, or transactions allowed: '+sql)
|
||
|
||
def reject(call):
|
||
try:call()
|
||
except ValueError:return
|
||
raise AssertionError('Incomplete/unsafe bulk export was accepted')
|
||
|
||
with patch.object(m,'db',side_effect=AssertionError('Tests must never call actual DB')), \
|
||
patch.object(m,'server_git_revision',side_effect=AssertionError('Tests must inject source revision')):
|
||
with tempfile.TemporaryDirectory(dir=m.ROOT/'runtime') as directory:
|
||
root=Path(directory);source=PublicDB()
|
||
first=m.snapshot_all(root/'first',2,query=source,revision=lambda:REV)
|
||
second=m.snapshot_all(root/'second',2,query=PublicDB(),revision=lambda:REV)
|
||
assert first==second
|
||
assert first['item_count']==5 and first['first_id']==1 and first['last_id']==4294967295
|
||
assert first['server_source_git_revision']==REV and not first['running_server_binary_revision_verified']
|
||
assert first['database_provenance']['world_migrations'][0]['Name']=='public-schema'
|
||
assert not first['consistency']['transactional_snapshot']
|
||
assert first['consistency']['second_content_pass_verified']
|
||
assert first['schema']['columns'][2]['default_batch_text']=='NULL'
|
||
assert first['schema_sha256']==hashlib.sha256(m._encoded(first['schema'])).hexdigest()
|
||
combined=[];content=hashlib.sha256()
|
||
for chunk in first['chunks']:
|
||
raw=(root/'first'/chunk['path']).read_bytes()
|
||
assert hashlib.sha256(raw).hexdigest()==chunk['sha256'] and len(raw)==chunk['bytes']
|
||
rows=json.loads(raw);assert len(rows)==chunk['count']
|
||
combined+=rows
|
||
for row in rows:content.update((json.dumps(row,ensure_ascii=False,sort_keys=True,separators=(',',':'))+'\n').encode())
|
||
assert combined==DATA and content.hexdigest()==first['content_sha256']
|
||
assert (root/'first'/'manifest.json').read_bytes()==(root/'second'/'manifest.json').read_bytes()
|
||
assert source.row_queries==6 and source.inventory_pass==2
|
||
assert first['source_identity_classification']==dict(positive_uint32_rows=5,all_stored_rows_preserved=True,blocked=[])
|
||
assert json.loads((root/'first'/'manifest.json').read_text())==first
|
||
assert not (root/'first.staging').exists()
|
||
unknown=m.snapshot_all(root/'unknown',2,query=PublicDB('no-migrations'),revision=lambda:REV)
|
||
assert unknown['database_provenance']['world_migrations'] is None
|
||
assert unknown['database_provenance']['migration_version_status']=='table-absent/unknown'
|
||
spells=PublicDB(table='spell_template')
|
||
spell=m.snapshot_all(root/'spells',2,query=spells,revision=lambda:REV,table='spell_template')
|
||
assert spell['spell_count']==5 and 'item_count'not in spell
|
||
assert spell['kind']=='public-local-tortoise-spell-inventory'
|
||
assert spell['database_provenance']['table']=='spell_template'
|
||
assert all(c['path'].startswith('spells-')for c in spell['chunks'])
|
||
assert not any('tw_world.item_template'in q for q in spells.queries)
|
||
for table in ('account','characters','spell_template; DROP TABLE x','Spell_Template',None):
|
||
forbidden=PublicDB()
|
||
reject(lambda:m.snapshot_all(root/'forbidden',2,query=forbidden,revision=lambda:REV,table=table))
|
||
assert not forbidden.queries
|
||
sentinel=[dict(entry=0,name='stored sentinel',description=None)]+DATA
|
||
zero=m.snapshot_all(root/'with-zero',2,query=PublicDB(data=sentinel),revision=lambda:REV)
|
||
assert zero['item_count']==6 and zero['first_id']==0
|
||
assert zero['source_identity_classification']['positive_uint32_rows']==5
|
||
assert zero['source_identity_classification']['blocked'][0]['entry']==0
|
||
assert zero['source_identity_classification']['blocked'][0]['status']=='blocked-non-wire-identity'
|
||
preserved=[]
|
||
for chunk in zero['chunks']:preserved+=json.loads((root/'with-zero'/chunk['path']).read_text())
|
||
assert preserved==sentinel # No silent omission or invented usable identity.
|
||
reject(lambda:m.identities('0')) # Bounded usable-item snapshots stay positive-only.
|
||
for mode in ('schema-drift','version-drift','id-drift','content-drift','missing','duplicate-id','duplicate-row','missing-column','duplicate-field','range','empty'):
|
||
target=root/mode
|
||
reject(lambda:m.snapshot_all(target,2,query=PublicDB(mode),revision=lambda:REV))
|
||
assert not target.exists() and not (root/(mode+'.staging')/'manifest.json').exists(),mode
|
||
changed=iter([REV,'b'*40]);target=root/'revision-drift'
|
||
reject(lambda:m.snapshot_all(target,2,query=PublicDB(),revision=lambda:next(changed)))
|
||
assert not target.exists() and not (root/'revision-drift.staging'/'manifest.json').exists()
|
||
target=root/'preserved';target.mkdir();(target/'keep').write_text('original')
|
||
reject(lambda:m.snapshot_all(target,2,query=PublicDB(),revision=lambda:REV))
|
||
assert (target/'keep').read_text()=='original'
|
||
target=root/'staged';target.with_name('staged.staging').mkdir()
|
||
reject(lambda:m.snapshot_all(target,2,query=PublicDB(),revision=lambda:REV))
|
||
for size in (0,4097,True):reject(lambda:m.snapshot_all(root/'bound',size,query=PublicDB(),revision=lambda:REV))
|
||
reject(lambda:m.snapshot_all(root/'bad-revision',2,query=PublicDB(),revision=lambda:'unknown'))
|
||
rename=Path.rename
|
||
def fail_publication(path,target):
|
||
if path.name=='publication.staging':raise OSError('Controlled publication failure')
|
||
return rename(path,target)
|
||
with patch.object(Path,'rename',fail_publication):
|
||
try:m.snapshot_all(root/'publication',2,query=PublicDB(),revision=lambda:REV)
|
||
except OSError:pass
|
||
else:raise AssertionError('Controlled publication failure disappeared')
|
||
assert not (root/'publication').exists()
|
||
assert not (root/'publication.staging'/'manifest.json').exists()
|
||
assert (root/'publication.staging'/'manifest.unpublished.json').is_file()
|
||
|
||
with tempfile.TemporaryDirectory()as directory:
|
||
path=Path(directory)/'itemcache.wdb'
|
||
fields=[6430,2,0,0,0,18,0xffffffff,0xffffffff,60,0,0,0,0,0,0,0,0,0,1,36]
|
||
body=struct.pack('<II',1,0)+b'Fixture bag\0\0\0\0'+struct.pack('<20I',*fields)+b'opaque-unparsed-tail'
|
||
header=struct.pack('<4sI4sII',b'BDIW',5875,b'BGne',468,5)
|
||
raw=header+struct.pack('<II',500001,len(body))+body+bytes(8)
|
||
path.write_bytes(raw);cache=m.read_item_cache_prefix(path);row=cache['records'][0]
|
||
assert row['entry']==500001 and row['class']==1 and row['inventory_type']==18 and row['container_slots']==36
|
||
assert row['allowable_race']==-1 and row['cached_payload_sha256']==hashlib.sha256(body).hexdigest()
|
||
assert not cache['full_item_template_decoded']and not cache['live_server_equality_verified']
|
||
local={k:v for k,v in row.items()if not k.startswith('cached_payload_')}
|
||
public=dict(row,name='Prospector’s Magnifying Lens')
|
||
local['name']=public['name'].encode('utf-8').decode('cp1252')
|
||
namecache=dict(cache,records=[public])
|
||
correction=m.cached_name_corrections([local],namecache)
|
||
assert len(correction)==1 and correction[0]['display_name']=='Prospector’s Magnifying Lens'
|
||
assert correction[0]['original_name']==local['name']
|
||
different=dict(local,name='An unrelated item')
|
||
assert m.cached_name_corrections([different],namecache)==[]
|
||
assert m.cached_name_corrections([dict(local,inventory_type=12)],namecache)==[]
|
||
for bad in (raw[:-12],b'WRNG'+raw[4:],header+struct.pack('<II',500001,65537)+body,
|
||
header+struct.pack('<II',500001,len(body))+body+struct.pack('<II',500001,len(body))+body+bytes(8)):
|
||
path.write_bytes(bad);reject(lambda:m.read_item_cache_prefix(path))
|
||
|
||
with patch.object(m.subprocess,'check_output',return_value=REV+'\n') as git:
|
||
assert m.server_git_revision()==REV
|
||
assert git.call_args.args[0]==['git','-C',str(m.SERVER),'rev-parse','HEAD']
|
||
print('PASS: mock-only bulk public item export: bounded chunks, complete schema/provenance, '
|
||
'deterministic bytes/hashes, missing/duplicate/range/content/schema/version/revision drift '
|
||
'rejection and incomplete staging preservation without final manifest. '
|
||
'Separate queries are explicitly nontransactional; no actual DB/Git/client actions.')
|