883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
165 lines
10 KiB
Python
165 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Small extracted DBC fixtures: no archive reader, client or database access."""
|
|
from copy import deepcopy
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import struct
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
|
|
import octo_client_data as octo
|
|
|
|
|
|
class CandidateBatchTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name)
|
|
(self.root/'runtime').mkdir();self.extracted=self.root/'extracted';self.extracted.mkdir()
|
|
self.dbd=self.root/'Spell.dbd';self.dbd.write_text('reviewed test provenance input\n')
|
|
self.scan=dict(source_installation='/test/Octowow',reader_source_sha256='c'*64,effective_patch_order_verified=False,
|
|
archives=[dict(file='patch-A.mpq',bytes=10000,open_result=0,sha256='a'*64),dict(file='patch-Z.mpq',bytes=10000,open_result=0,sha256='b'*64)],candidates=[])
|
|
self.path=self.root/'scan.json';self.output=self.root/'runtime/batch'
|
|
self.guard=patch.object(octo,'ROOT',self.root);self.guard.start()
|
|
self.no_reader=patch.object(octo,'build_reader',side_effect=AssertionError('Must not build/extract'))
|
|
self.no_reader.start()
|
|
self.no_scan=patch.object(octo,'scan',side_effect=AssertionError('Must not scan client archives'));self.no_scan.start()
|
|
|
|
def tearDown(self):
|
|
self.no_scan.stop();self.no_reader.stop();self.guard.stop();self.temp.cleanup()
|
|
|
|
def candidate(self,table,fields,rows,archive='patch-A.mpq',strings=b'\0'):
|
|
raw=struct.pack('<4s4I',b'WDBC',len(rows),fields,fields*4,len(strings))+b''.join(struct.pack('<'+str(fields)+'I',*r) for r in rows)+strings
|
|
path=self.extracted/archive/(table+'.dbc');path.parent.mkdir(exist_ok=True);path.write_bytes(raw)
|
|
row=dict(table=table,archive=archive,sha256=hashlib.sha256(raw).hexdigest(),rows=len(rows),fields=fields,bytes=len(raw))
|
|
self.scan['candidates'].append(row);return path
|
|
|
|
def run_batch(self,output=None):
|
|
self.path.write_text(json.dumps(self.scan))
|
|
return octo.inventory_manifest(self.path,self.extracted,output or self.output,expected_client='/test/Octowow',spell_dbd=self.dbd)
|
|
|
|
def assert_incomplete(self):
|
|
staging=self.output.with_name(self.output.name+'.staging')
|
|
self.assertTrue(staging.is_dir());self.assertFalse((self.output/'manifest.json').exists())
|
|
return staging
|
|
|
|
def test_complete_independent_batch_has_no_effective_winner(self):
|
|
spell=[0]*173;spell[0]=10;spell[109]=11
|
|
self.candidate('Spell',173,[spell]);spell[109]=12;self.candidate('Spell',173,[spell],archive='patch-Z.mpq')
|
|
talent=[0]*21;talent[0]=1;talent[4]=10;self.candidate('Talent',21,[talent])
|
|
result=self.run_batch()
|
|
self.assertEqual(result['source_candidates'],3);self.assertEqual(result['record_count'],3)
|
|
self.assertEqual(result['reference_count'],3)
|
|
self.assertEqual(result['client_identity'],dict(client_sha256=None,client_build=None,locale=None))
|
|
spell_rows=[r for r in result['candidates'] if r['table']=='Spell']
|
|
self.assertTrue(all(r['selection_status']=='blocked-ambiguous-candidates' for r in spell_rows))
|
|
datasets=[]
|
|
for row in result['candidates']:
|
|
path=self.output/row['path'];raw=path.read_bytes();value=json.loads(raw)
|
|
self.assertEqual(hashlib.sha256(raw).hexdigest(),row['output_sha256']);self.assertEqual(len(raw),row['output_bytes'])
|
|
self.assertEqual(value['candidate_sha256'],row['candidate_sha256']);self.assertFalse(value['runtime_effective_verified'])
|
|
datasets.append(value['source_identity']['dataset'])
|
|
self.assertEqual(raw.count(b'\n'),1)
|
|
self.assertEqual(len(set(datasets)),3)
|
|
self.assertFalse(result['verification']['original_archives_rehashed']);self.assertFalse(result['verification']['client_executable_rehashed'])
|
|
self.assertFalse(result['runtime_effective_verified']);self.assertFalse(result['converted']);self.assertFalse(result['engine_loaded'])
|
|
self.assertEqual(json.loads((self.output/'manifest.json').read_text()),result)
|
|
self.assertTrue(result['publication']['directory_appearance_is_not_completion'])
|
|
self.assertTrue(self.output.with_name('batch.staging').is_dir())
|
|
|
|
def test_unchanged_inputs_produce_identical_outputs(self):
|
|
self.candidate('SpellIcon',2,[[3,0],[1,0]])
|
|
one=self.run_batch();other=self.root/'runtime/second';two=self.run_batch(other)
|
|
self.assertEqual(one,two)
|
|
self.assertEqual((self.output/'manifest.json').read_bytes(),(other/'manifest.json').read_bytes())
|
|
for row in one['candidates']:self.assertEqual((self.output/row['path']).read_bytes(),(other/row['path']).read_bytes())
|
|
|
|
def test_unknown_shape_is_retained_and_blocked(self):
|
|
self.candidate('Spell',162,[[1]+[0]*161])
|
|
result=self.run_batch();row=result['candidates'][0]
|
|
self.assertEqual(row['schema_status'],'blocked-unreviewed-schema');self.assertEqual(row['blocked_records'],1);self.assertEqual(row['references'],0)
|
|
inventory=json.loads((self.output/row['path']).read_text());self.assertEqual(len(inventory['records'][0]['raw_fields']),162)
|
|
|
|
def test_initial_hash_drift_preserves_failed_staging(self):
|
|
self.candidate('Talent',21,[[1]+[0]*20]);self.scan['candidates'][0]['sha256']='d'*64
|
|
with self.assertRaisesRegex(ValueError,'hash/schema/count/size'):self.run_batch()
|
|
staging=self.assert_incomplete();self.assertFalse((staging/'manifest.json').exists())
|
|
|
|
def test_declared_schema_drift_is_rejected(self):
|
|
self.candidate('Talent',21,[[1]+[0]*20]);self.scan['candidates'][0]['fields']=20
|
|
with self.assertRaisesRegex(ValueError,'hash/schema/count/size'):self.run_batch()
|
|
self.assert_incomplete()
|
|
|
|
def test_second_pass_catches_candidate_drift(self):
|
|
path=self.candidate('SpellIcon',2,[[1,0]])
|
|
original=octo.inventory_table
|
|
def mutate(*args):
|
|
result=original(*args);raw=bytearray(path.read_bytes());raw[24]=2;path.write_bytes(raw);return result
|
|
with patch.object(octo,'inventory_table',side_effect=mutate),self.assertRaisesRegex(ValueError,'hash/schema/count/size'):self.run_batch()
|
|
staging=self.assert_incomplete();self.assertTrue((staging/'patch-A.mpq/SpellIcon.inventory.json').exists())
|
|
|
|
def test_converter_changes_abort_publication(self):
|
|
self.candidate('SpellIcon',2,[[1,0]])
|
|
original=octo.inventory_table
|
|
def mutate(*args):
|
|
result=original(*args);self.dbd.write_text('changed DBD\n');return result
|
|
with patch.object(octo,'inventory_table',side_effect=mutate),self.assertRaisesRegex(ValueError,'converter inputs changed'):self.run_batch()
|
|
self.assert_incomplete()
|
|
|
|
def test_scan_file_drift_aborts_publication(self):
|
|
self.candidate('SpellIcon',2,[[1,0]])
|
|
original=octo.inventory_table
|
|
def mutate(*args):
|
|
result=original(*args);changed=deepcopy(self.scan);changed['locale']='deDE';self.path.write_text(json.dumps(changed));return result
|
|
with patch.object(octo,'inventory_table',side_effect=mutate),self.assertRaisesRegex(ValueError,'converter inputs changed'):self.run_batch()
|
|
self.assert_incomplete()
|
|
|
|
def test_staged_report_corruption_aborts_publication(self):
|
|
self.candidate('SpellIcon',2,[[1,0]])
|
|
original=octo.digest
|
|
def corrupt(path):
|
|
if path.name.endswith('.inventory.json'):
|
|
raw=bytearray(path.read_bytes());raw[0]=ord('[');path.write_bytes(raw)
|
|
return original(path)
|
|
with patch.object(octo,'digest',side_effect=corrupt),self.assertRaisesRegex(ValueError,'Staged candidate report changed'):self.run_batch()
|
|
self.assert_incomplete()
|
|
|
|
def test_unsafe_paths_and_symlinks_are_rejected(self):
|
|
path=self.candidate('SpellIcon',2,[[1,0]])
|
|
original=deepcopy(self.scan)
|
|
self.scan['candidates'][0]['path']='../escape.dbc'
|
|
with self.assertRaisesRegex(ValueError,'safe archive/table'):self.run_batch()
|
|
self.assertFalse(self.output.with_name('batch.staging').exists())
|
|
self.scan=original;outside=self.root/'outside.dbc';path.rename(outside);path.symlink_to(outside)
|
|
with self.assertRaisesRegex(ValueError,'without symlinks'):self.run_batch()
|
|
self.assert_incomplete()
|
|
|
|
def test_existing_output_or_failed_staging_is_not_overwritten(self):
|
|
self.candidate('SpellIcon',2,[[1,0]]);self.output.mkdir();sentinel=self.output/'keep';sentinel.write_text('preserve')
|
|
with self.assertRaisesRegex(ValueError,'new runtime output'):self.run_batch()
|
|
self.assertEqual(sentinel.read_text(),'preserve')
|
|
other=self.root/'runtime/other';staging=other.with_name('other.staging');staging.mkdir();(staging/'keep').write_text('unfinished')
|
|
with self.assertRaisesRegex(ValueError,'new runtime output'):self.run_batch(other)
|
|
self.assertEqual((staging/'keep').read_text(),'unfinished')
|
|
|
|
def test_final_publication_uses_exclusive_directory_and_marker_last(self):
|
|
self.candidate('SpellIcon',2,[[1,0]])
|
|
original=octo.os.link
|
|
def fail_data(source,target):
|
|
self.assertFalse((self.output/'manifest.json').exists())
|
|
if str(target).endswith('.inventory.json'):raise OSError('simulated linking failure')
|
|
return original(source,target)
|
|
with patch.object(octo.os,'link',side_effect=fail_data),self.assertRaisesRegex(OSError,'simulated linking'):self.run_batch()
|
|
staging=self.assert_incomplete();self.assertTrue((staging/'manifest.json').exists())
|
|
self.assertTrue((staging/'patch-A.mpq/SpellIcon.inventory.json').is_file())
|
|
|
|
def test_incomplete_archive_provenance_is_not_upgraded_by_extracted_files(self):
|
|
self.candidate('SpellIcon',2,[[1,0]]);del self.scan['archives'][0]['sha256']
|
|
with self.assertRaisesRegex(ValueError,'archive provenance'):self.run_batch()
|
|
self.assertFalse(self.output.with_name('batch.staging').exists())
|
|
|
|
|
|
if __name__=='__main__':unittest.main()
|