| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145 |
- import copy
- import json
- from pathlib import Path
- import sqlite3
- import tempfile
- import unittest
- import subprocess
- import sys
- import agent_batch
- import intake_contract
- import retrieval
- import schema_catalog
- import structured_batch
- import update_library
- import voc_db
- class FullSchemaAndIntakeTests(unittest.TestCase):
- def setUp(self):
- self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
- self.root=Path(self.tmp.name);(self.root/'raw').mkdir();self.raw=self.root/'raw/response.json'
- self.payload={
- 'product':{'id':'123','title':'康师傅香辣拌面110g*5袋'},
- 'review':{'item':'123','id':'r1','text':'一包吃不饱,味道不错','default':False,'sku':'香辣拌面'},
- 'price':{'item':'123','amount':'19.90','basis':'search_listing_snapshot','time':'2026-11-06T10:00:00+08:00'},
- 'spec':{'item':'123','text':'每袋净含量110克,共5袋','weight':110,'count':5,'basis':'包装标示每袋净含量110克','verification':'source_attribute'},
- 'post':{'id':'p1','title':'康师傅拌面体验','text':'面条有嚼劲','likes':0},
- 'doc':{'id':'standard-1','title':'营养标签示例标准','text':'第1条:标签应标示净含量。','status':'current','asOf':'2026-11-06'},
- 'clause':{'doc':'standard-1','position':'第1条','text':'标签应标示净含量。','note':'核对产品包装标签'},
- 'ranking':{'item':'123','rank':2,'scope':'detail_page_badge_not_complete_ranking'},
- 'coverage':{'item':'123','status':'partial','available':1,'complete':False}}
- self.raw.write_text(json.dumps(self.payload,ensure_ascii=False),encoding='utf-8')
- self.batch={'schema':intake_contract.VERSION,'batchId':'full-batch','producer':'test-agent/1',
- 'sources':[{'id':'ecom','path':'raw/response.json','sha256':agent_batch.digest(self.raw),'platform':'jd','marketplace':'jd','requestItemId':'123'},
- {'id':'social','path':'raw/response.json','sha256':agent_batch.digest(self.raw),'platform':'xiaohongshu'},
- {'id':'policy','path':'raw/response.json','sha256':agent_batch.digest(self.raw),'platform':'web'}]}
- mappings={
- 'products':('ecom','product',{'itemId':'id','title':'title'}),
- 'reviews':('ecom','review',{'itemId':'item','reviewId':'id','content':'text','isDefault':'default','purchasedSku':'sku'}),
- 'prices':('ecom','price',{'itemId':'item','amount':'amount','priceBasis':'basis','sourceTime':'time'}),
- 'specs':('ecom','spec',{'itemId':'item','specText':'text','netWeightG':'weight','packCount':'count','basis':'basis','verification':'verification'}),
- 'social':('social','post',{'postId':'id','title':'title','content':'text','likes':'likes'}),
- 'documents':('policy','doc',{'documentId':'id','title':'title','fullText':'text','declaredStatus':'status','statusAsOf':'asOf'}),
- 'clauses':('policy','clause',{'documentId':'doc','clause':'position','excerpt':'text','applicationNote':'note'}),
- 'rankings':('ecom','ranking',{'itemId':'item','rankNumber':'rank','scope':'scope'}),
- 'coverage':('ecom','coverage',{'itemId':'item','status':'status','availableReviews':'available','historicalTotalComplete':'complete'})}
- for entity,(sid,loc,fields) in mappings.items():self.batch[entity]=[{'sourceId':sid,'pointer':'/'+loc,'fields':{k:'/'+v for k,v in fields.items()}}]
- self.path=self.root/'batch.json';self.output=self.root/'new.sqlite';self.save()
- def save(self):self.path.write_text(json.dumps(self.batch,ensure_ascii=False),encoding='utf-8')
- def test_all_domain_entities_build_publish_and_query_exact_sources(self):
- before={p.name:(p.stat().st_mtime_ns,agent_batch.digest(p)) for p in self.root.rglob('*') if p.is_file()}
- dry=agent_batch.build_batch(self.path,self.output)
- self.assertTrue(dry['readOnly']);self.assertEqual(set(dry['counts']),set(intake_contract.ENTITIES))
- self.assertEqual(before,{p.name:(p.stat().st_mtime_ns,agent_batch.digest(p)) for p in self.root.rglob('*') if p.is_file()})
- built=agent_batch.build_batch(self.path,self.output,True)
- with voc_db.readonly(self.output) as c:
- for entity,table in retrieval.ENTITIES.items():
- self.assertGreater(c.execute('SELECT count(*) FROM '+table).fetchone()[0],0,entity)
- row=c.execute('SELECT source_record_id FROM '+table+' LIMIT 1').fetchone()
- citation=voc_db.get_source(c,row[0]);self.assertTrue(citation['ok'])
- doc=c.execute('SELECT full_text,status_as_of FROM policy_documents').fetchone()
- self.assertEqual(tuple(doc),('第1条:标签应标示净含量。','2026-11-06'))
- self.assertEqual(c.execute('SELECT likes,comment_count FROM social_posts').fetchone()[1],None)
- self.assertEqual(c.execute('SELECT amount_minor FROM prices').fetchone()[0],1990)
- self.assertEqual(c.execute("SELECT net_weight_g FROM specs WHERE verification='source_attribute'").fetchone()[0],110)
- registry=self.root/'registry';first=update_library.publish(self.output,registry,True)
- self.assertTrue(first['applied']);self.assertFalse(update_library.publish(self.output,registry,True)['applied'])
- pointer=(registry/'current.json').read_bytes()
- with self.assertRaisesRegex(voc_db.LibraryError,'LIBRARY_GENERATION_CHANGED'):
- update_library.publish(self.output,registry,True,expected_generation='stale')
- self.assertEqual(pointer,(registry/'current.json').read_bytes())
- with voc_db.readonly(registry/first['file']) as c:
- result=schema_catalog.catalog(c)
- self.assertTrue(result['complete']);self.assertEqual(result['tableCount'],len(c.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()))
- self.assertFalse(built['activeLibraryModified'])
- def test_all_schema_fields_profile_and_future_column_drift(self):
- agent_batch.build_batch(self.path,self.output,True);before=agent_batch.digest(self.output)
- with voc_db.readonly(self.output) as c:
- r=schema_catalog.catalog(c,'social_posts',True);table=r['tables'][0]
- self.assertEqual(table['recordCount'],1)
- comments=next(f for f in table['fields'] if f['name']=='comment_count')
- self.assertEqual(comments['profile']['nullCount'],1)
- self.assertTrue(all(f['meaning'] for t in schema_catalog.catalog(c)['tables'] for f in t['fields']))
- with self.assertRaises(voc_db.LibraryError):schema_catalog.catalog(c,'products; DROP TABLE reviews')
- self.assertEqual(before,agent_batch.digest(self.output))
- c=sqlite3.connect(self.output);c.execute('ALTER TABLE products ADD COLUMN future_attribute TEXT');c.commit();c.close()
- with voc_db.readonly(self.output) as c:
- r=schema_catalog.catalog(c,'products');self.assertFalse(r['complete'])
- self.assertIsNone(next(f for f in r['tables'][0]['fields'] if f['name']=='future_attribute')['meaning'])
- def test_invalid_association_policy_time_and_invented_field_rejected(self):
- original=copy.deepcopy(self.batch)
- cases=[lambda:self.batch.pop('products'),lambda:self.batch.pop('documents'),
- lambda:self.batch['documents'][0]['fields'].pop('statusAsOf'),
- lambda:self.batch['specs'][0]['fields'].pop('basis'),
- lambda:self.batch['prices'][0]['fields'].update(invented='/amount')]
- for mutate in cases:
- self.batch=copy.deepcopy(original);mutate();self.save()
- with self.assertRaises(voc_db.LibraryError):agent_batch.build_batch(self.path,self.output,True)
- self.assertFalse(self.output.exists());self.assertFalse(self.output.with_suffix('.source.zip').exists())
- def test_social_and_policy_only_batches_do_not_require_fake_products(self):
- self.batch={k:x for k,x in self.batch.items() if k in ('schema','batchId','producer','sources','social','documents','clauses')};self.save()
- agent_batch.build_batch(self.path,self.output,True)
- with voc_db.readonly(self.output) as c:
- self.assertEqual(c.execute('SELECT count(*) FROM products').fetchone()[0],0)
- self.assertEqual(c.execute('SELECT count(*) FROM policy_clauses').fetchone()[0],1)
- def test_packaged_cli_describes_installed_columns_and_guards_generation(self):
- built=agent_batch.build_batch(self.path,self.output,True)
- root=Path(__file__).resolve().parents[2]
- cli=[sys.executable,'-B','-X','utf8',str(root/'skills/ksf-voc-library/scripts/query_voc.py'),'schema','--db',str(self.output)]
- before=agent_batch.digest(self.output)
- run=subprocess.run(cli+['--table','prices','--profile','--generation',built['generation']],capture_output=True,text=True,encoding='utf-8',check=True)
- result=json.loads(run.stdout);self.assertEqual(result['generation'],built['generation'])
- field=next(f for f in result['tables'][0]['fields'] if f['name']=='amount_minor')
- self.assertEqual(field['unit'],'CNY分');self.assertEqual(field['profile']['nonNullCount'],1)
- self.assertNotIn('payload_json',run.stdout)
- failed=subprocess.run(cli+['--generation','old-generation'],capture_output=True,text=True,encoding='utf-8')
- self.assertNotEqual(failed.returncode,0);self.assertIn('LIBRARY_GENERATION_CHANGED',failed.stdout+failed.stderr)
- self.assertEqual(before,agent_batch.digest(self.output))
- def test_original_policy_attachment_is_hash_checked_linked_and_packed(self):
- pdf=self.root/'raw/standard.pdf';pdf.write_bytes(b'%PDF-fixture-original-bytes')
- self.payload['doc'].update(pdf='raw/standard.pdf',sha=agent_batch.digest(pdf))
- self.raw.write_text(json.dumps(self.payload,ensure_ascii=False),encoding='utf-8')
- for s in self.batch['sources']:s['sha256']=agent_batch.digest(self.raw)
- self.batch['attachments']=[{'path':'raw/standard.pdf','sha256':agent_batch.digest(pdf)}]
- self.batch['documents'][0]['fields'].update(pdfFile='/pdf',expectedSha256='/sha');self.save()
- built=agent_batch.build_batch(self.path,self.output,True)
- with voc_db.readonly(self.output) as c:
- r=c.execute('SELECT attachment_hash_state,hash_basis,source_record_id FROM policy_documents').fetchone()
- self.assertEqual(r[0],'matched');self.assertTrue(r[1].endswith('raw/standard.pdf#bytes'))
- citation=voc_db.get_source(c,r[2]);self.assertIn('raw/standard.pdf',json.dumps(citation))
- import zipfile
- with zipfile.ZipFile(built['sourceArchive']) as z:self.assertEqual(z.read('agent-batch/02_采集档案/raw/standard.pdf'),pdf.read_bytes())
- def test_brand_attribute_maps_to_dictionary_without_guessing_from_shop(self):
- self.payload['product'].update(title='香辣拌面110g',brand='康师傅')
- self.raw.write_text(json.dumps(self.payload,ensure_ascii=False),encoding='utf-8')
- for s in self.batch['sources']:s['sha256']=agent_batch.digest(self.raw)
- self.batch['products'][0]['fields']['brandName']='/brand';self.save()
- agent_batch.build_batch(self.path,self.output,True)
- with voc_db.readonly(self.output) as c:
- self.assertEqual(tuple(c.execute('SELECT brand_code,brand_basis FROM products').fetchone()),('ksf','source_attribute'))
- self.assertEqual(c.execute("SELECT evidence_field FROM classification_assertions WHERE dimension='brand'").fetchone()[0],'brand_name')
- if __name__=='__main__':unittest.main()
|