test_full_schema_and_intake.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import copy
  2. import json
  3. from pathlib import Path
  4. import sqlite3
  5. import tempfile
  6. import unittest
  7. import subprocess
  8. import sys
  9. import agent_batch
  10. import intake_contract
  11. import retrieval
  12. import schema_catalog
  13. import structured_batch
  14. import update_library
  15. import voc_db
  16. class FullSchemaAndIntakeTests(unittest.TestCase):
  17. def setUp(self):
  18. self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
  19. self.root=Path(self.tmp.name);(self.root/'raw').mkdir();self.raw=self.root/'raw/response.json'
  20. self.payload={
  21. 'product':{'id':'123','title':'康师傅香辣拌面110g*5袋'},
  22. 'review':{'item':'123','id':'r1','text':'一包吃不饱,味道不错','default':False,'sku':'香辣拌面'},
  23. 'price':{'item':'123','amount':'19.90','basis':'search_listing_snapshot','time':'2026-11-06T10:00:00+08:00'},
  24. 'spec':{'item':'123','text':'每袋净含量110克,共5袋','weight':110,'count':5,'basis':'包装标示每袋净含量110克','verification':'source_attribute'},
  25. 'post':{'id':'p1','title':'康师傅拌面体验','text':'面条有嚼劲','likes':0},
  26. 'doc':{'id':'standard-1','title':'营养标签示例标准','text':'第1条:标签应标示净含量。','status':'current','asOf':'2026-11-06'},
  27. 'clause':{'doc':'standard-1','position':'第1条','text':'标签应标示净含量。','note':'核对产品包装标签'},
  28. 'ranking':{'item':'123','rank':2,'scope':'detail_page_badge_not_complete_ranking'},
  29. 'coverage':{'item':'123','status':'partial','available':1,'complete':False}}
  30. self.raw.write_text(json.dumps(self.payload,ensure_ascii=False),encoding='utf-8')
  31. self.batch={'schema':intake_contract.VERSION,'batchId':'full-batch','producer':'test-agent/1',
  32. 'sources':[{'id':'ecom','path':'raw/response.json','sha256':agent_batch.digest(self.raw),'platform':'jd','marketplace':'jd','requestItemId':'123'},
  33. {'id':'social','path':'raw/response.json','sha256':agent_batch.digest(self.raw),'platform':'xiaohongshu'},
  34. {'id':'policy','path':'raw/response.json','sha256':agent_batch.digest(self.raw),'platform':'web'}]}
  35. mappings={
  36. 'products':('ecom','product',{'itemId':'id','title':'title'}),
  37. 'reviews':('ecom','review',{'itemId':'item','reviewId':'id','content':'text','isDefault':'default','purchasedSku':'sku'}),
  38. 'prices':('ecom','price',{'itemId':'item','amount':'amount','priceBasis':'basis','sourceTime':'time'}),
  39. 'specs':('ecom','spec',{'itemId':'item','specText':'text','netWeightG':'weight','packCount':'count','basis':'basis','verification':'verification'}),
  40. 'social':('social','post',{'postId':'id','title':'title','content':'text','likes':'likes'}),
  41. 'documents':('policy','doc',{'documentId':'id','title':'title','fullText':'text','declaredStatus':'status','statusAsOf':'asOf'}),
  42. 'clauses':('policy','clause',{'documentId':'doc','clause':'position','excerpt':'text','applicationNote':'note'}),
  43. 'rankings':('ecom','ranking',{'itemId':'item','rankNumber':'rank','scope':'scope'}),
  44. 'coverage':('ecom','coverage',{'itemId':'item','status':'status','availableReviews':'available','historicalTotalComplete':'complete'})}
  45. for entity,(sid,loc,fields) in mappings.items():self.batch[entity]=[{'sourceId':sid,'pointer':'/'+loc,'fields':{k:'/'+v for k,v in fields.items()}}]
  46. self.path=self.root/'batch.json';self.output=self.root/'new.sqlite';self.save()
  47. def save(self):self.path.write_text(json.dumps(self.batch,ensure_ascii=False),encoding='utf-8')
  48. def test_all_domain_entities_build_publish_and_query_exact_sources(self):
  49. before={p.name:(p.stat().st_mtime_ns,agent_batch.digest(p)) for p in self.root.rglob('*') if p.is_file()}
  50. dry=agent_batch.build_batch(self.path,self.output)
  51. self.assertTrue(dry['readOnly']);self.assertEqual(set(dry['counts']),set(intake_contract.ENTITIES))
  52. self.assertEqual(before,{p.name:(p.stat().st_mtime_ns,agent_batch.digest(p)) for p in self.root.rglob('*') if p.is_file()})
  53. built=agent_batch.build_batch(self.path,self.output,True)
  54. with voc_db.readonly(self.output) as c:
  55. for entity,table in retrieval.ENTITIES.items():
  56. self.assertGreater(c.execute('SELECT count(*) FROM '+table).fetchone()[0],0,entity)
  57. row=c.execute('SELECT source_record_id FROM '+table+' LIMIT 1').fetchone()
  58. citation=voc_db.get_source(c,row[0]);self.assertTrue(citation['ok'])
  59. doc=c.execute('SELECT full_text,status_as_of FROM policy_documents').fetchone()
  60. self.assertEqual(tuple(doc),('第1条:标签应标示净含量。','2026-11-06'))
  61. self.assertEqual(c.execute('SELECT likes,comment_count FROM social_posts').fetchone()[1],None)
  62. self.assertEqual(c.execute('SELECT amount_minor FROM prices').fetchone()[0],1990)
  63. self.assertEqual(c.execute("SELECT net_weight_g FROM specs WHERE verification='source_attribute'").fetchone()[0],110)
  64. registry=self.root/'registry';first=update_library.publish(self.output,registry,True)
  65. self.assertTrue(first['applied']);self.assertFalse(update_library.publish(self.output,registry,True)['applied'])
  66. pointer=(registry/'current.json').read_bytes()
  67. with self.assertRaisesRegex(voc_db.LibraryError,'LIBRARY_GENERATION_CHANGED'):
  68. update_library.publish(self.output,registry,True,expected_generation='stale')
  69. self.assertEqual(pointer,(registry/'current.json').read_bytes())
  70. with voc_db.readonly(registry/first['file']) as c:
  71. result=schema_catalog.catalog(c)
  72. self.assertTrue(result['complete']);self.assertEqual(result['tableCount'],len(c.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()))
  73. self.assertFalse(built['activeLibraryModified'])
  74. def test_all_schema_fields_profile_and_future_column_drift(self):
  75. agent_batch.build_batch(self.path,self.output,True);before=agent_batch.digest(self.output)
  76. with voc_db.readonly(self.output) as c:
  77. r=schema_catalog.catalog(c,'social_posts',True);table=r['tables'][0]
  78. self.assertEqual(table['recordCount'],1)
  79. comments=next(f for f in table['fields'] if f['name']=='comment_count')
  80. self.assertEqual(comments['profile']['nullCount'],1)
  81. self.assertTrue(all(f['meaning'] for t in schema_catalog.catalog(c)['tables'] for f in t['fields']))
  82. with self.assertRaises(voc_db.LibraryError):schema_catalog.catalog(c,'products; DROP TABLE reviews')
  83. self.assertEqual(before,agent_batch.digest(self.output))
  84. c=sqlite3.connect(self.output);c.execute('ALTER TABLE products ADD COLUMN future_attribute TEXT');c.commit();c.close()
  85. with voc_db.readonly(self.output) as c:
  86. r=schema_catalog.catalog(c,'products');self.assertFalse(r['complete'])
  87. self.assertIsNone(next(f for f in r['tables'][0]['fields'] if f['name']=='future_attribute')['meaning'])
  88. def test_invalid_association_policy_time_and_invented_field_rejected(self):
  89. original=copy.deepcopy(self.batch)
  90. cases=[lambda:self.batch.pop('products'),lambda:self.batch.pop('documents'),
  91. lambda:self.batch['documents'][0]['fields'].pop('statusAsOf'),
  92. lambda:self.batch['specs'][0]['fields'].pop('basis'),
  93. lambda:self.batch['prices'][0]['fields'].update(invented='/amount')]
  94. for mutate in cases:
  95. self.batch=copy.deepcopy(original);mutate();self.save()
  96. with self.assertRaises(voc_db.LibraryError):agent_batch.build_batch(self.path,self.output,True)
  97. self.assertFalse(self.output.exists());self.assertFalse(self.output.with_suffix('.source.zip').exists())
  98. def test_social_and_policy_only_batches_do_not_require_fake_products(self):
  99. self.batch={k:x for k,x in self.batch.items() if k in ('schema','batchId','producer','sources','social','documents','clauses')};self.save()
  100. agent_batch.build_batch(self.path,self.output,True)
  101. with voc_db.readonly(self.output) as c:
  102. self.assertEqual(c.execute('SELECT count(*) FROM products').fetchone()[0],0)
  103. self.assertEqual(c.execute('SELECT count(*) FROM policy_clauses').fetchone()[0],1)
  104. def test_packaged_cli_describes_installed_columns_and_guards_generation(self):
  105. built=agent_batch.build_batch(self.path,self.output,True)
  106. root=Path(__file__).resolve().parents[2]
  107. cli=[sys.executable,'-B','-X','utf8',str(root/'skills/ksf-voc-library/scripts/query_voc.py'),'schema','--db',str(self.output)]
  108. before=agent_batch.digest(self.output)
  109. run=subprocess.run(cli+['--table','prices','--profile','--generation',built['generation']],capture_output=True,text=True,encoding='utf-8',check=True)
  110. result=json.loads(run.stdout);self.assertEqual(result['generation'],built['generation'])
  111. field=next(f for f in result['tables'][0]['fields'] if f['name']=='amount_minor')
  112. self.assertEqual(field['unit'],'CNY分');self.assertEqual(field['profile']['nonNullCount'],1)
  113. self.assertNotIn('payload_json',run.stdout)
  114. failed=subprocess.run(cli+['--generation','old-generation'],capture_output=True,text=True,encoding='utf-8')
  115. self.assertNotEqual(failed.returncode,0);self.assertIn('LIBRARY_GENERATION_CHANGED',failed.stdout+failed.stderr)
  116. self.assertEqual(before,agent_batch.digest(self.output))
  117. def test_original_policy_attachment_is_hash_checked_linked_and_packed(self):
  118. pdf=self.root/'raw/standard.pdf';pdf.write_bytes(b'%PDF-fixture-original-bytes')
  119. self.payload['doc'].update(pdf='raw/standard.pdf',sha=agent_batch.digest(pdf))
  120. self.raw.write_text(json.dumps(self.payload,ensure_ascii=False),encoding='utf-8')
  121. for s in self.batch['sources']:s['sha256']=agent_batch.digest(self.raw)
  122. self.batch['attachments']=[{'path':'raw/standard.pdf','sha256':agent_batch.digest(pdf)}]
  123. self.batch['documents'][0]['fields'].update(pdfFile='/pdf',expectedSha256='/sha');self.save()
  124. built=agent_batch.build_batch(self.path,self.output,True)
  125. with voc_db.readonly(self.output) as c:
  126. r=c.execute('SELECT attachment_hash_state,hash_basis,source_record_id FROM policy_documents').fetchone()
  127. self.assertEqual(r[0],'matched');self.assertTrue(r[1].endswith('raw/standard.pdf#bytes'))
  128. citation=voc_db.get_source(c,r[2]);self.assertIn('raw/standard.pdf',json.dumps(citation))
  129. import zipfile
  130. with zipfile.ZipFile(built['sourceArchive']) as z:self.assertEqual(z.read('agent-batch/02_采集档案/raw/standard.pdf'),pdf.read_bytes())
  131. def test_brand_attribute_maps_to_dictionary_without_guessing_from_shop(self):
  132. self.payload['product'].update(title='香辣拌面110g',brand='康师傅')
  133. self.raw.write_text(json.dumps(self.payload,ensure_ascii=False),encoding='utf-8')
  134. for s in self.batch['sources']:s['sha256']=agent_batch.digest(self.raw)
  135. self.batch['products'][0]['fields']['brandName']='/brand';self.save()
  136. agent_batch.build_batch(self.path,self.output,True)
  137. with voc_db.readonly(self.output) as c:
  138. self.assertEqual(tuple(c.execute('SELECT brand_code,brand_basis FROM products').fetchone()),('ksf','source_attribute'))
  139. self.assertEqual(c.execute("SELECT evidence_field FROM classification_assertions WHERE dimension='brand'").fetchone()[0],'brand_name')
  140. if __name__=='__main__':unittest.main()