Files
structured-media-builder-OPEN/tests/test_media_builder.py
T
2026-10-17 14:59:30 -06:00

244 lines
11 KiB
Python

import copy
import json
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
from jsonschema import Draft202012Validator
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'scripts'))
import media_builder as mb
class MediaBuilderTests(unittest.TestCase):
def setUp(self):
temp_root = ROOT / '.test-work'
temp_root.mkdir(exist_ok=True)
self.temp = tempfile.TemporaryDirectory(dir=temp_root)
self.work = Path(self.temp.name)
shutil.copytree(ROOT / 'examples', self.work / 'source')
self.folder = self.work / 'source' / 'example-webinar'
self.manifest = self.folder / 'media.json'
self.plan = self.folder / 'plan.json'
self.catalog = self.work / 'source' / 'catalog.json'
self.out = self.work / 'release'
def tearDown(self):
self.temp.cleanup()
def edit(self, path, change):
value = mb.load(path)
change(value)
mb.write(path, value)
def approve_fixture(self):
signature = mb.inputs(self.manifest, self.plan)[4]
self.edit(self.plan, lambda p: p['review'].update(input_sha256=signature))
def build(self):
return mb.build(self.catalog, self.out)
def test_all_schemas_valid(self):
for path in (ROOT / 'schemas').glob('*.schema.json'):
Draft202012Validator.check_schema(mb.load(path))
def test_audio_video_and_source_citations(self):
self.assertEqual(self.build()['media_count'], 2)
mb.verify_export(self.out)
video = self.out / 'media' / 'example-webinar'
data = mb.load(video / 'chunks.json')
self.assertEqual(data['chunks'][1]['content'],
'A conceptual chunk should cover one topic and preserve the words from its source cues. '
'Each answer needs a transcript citation with start and end times.')
self.assertEqual(data['chunks'][1]['citations'][1]['start_seconds'], 30)
self.assertEqual(mb.load(video / 'schema.jsonld')['@type'], 'VideoObject')
self.assertEqual(mb.load(self.out / 'media/example-audio/schema.jsonld')['@type'], 'AudioObject')
self.assertNotIn('transcripts', mb.load(video / 'media.json'))
self.assertEqual((video / 'transcript.vtt').read_bytes(), (self.folder / 'transcript.vtt').read_bytes())
self.assertFalse(mb.load(self.out / 'build-receipt.json')['deployment_verified'])
def test_deterministic_release(self):
self.build()
other = self.work / 'release-2'
mb.build(self.catalog, other)
self.assertEqual(mb.load(self.out / 'build-receipt.json'), mb.load(other / 'build-receipt.json'))
def test_search_returns_timed_cross_chunk_evidence(self):
self.build()
matches = mb.search(self.out, 'transcript citations', 10)
result = next(r for r in matches if r['id'] == 'example-webinar:qa:two')
self.assertEqual({c['chunk_id'] for c in result['citations']},
{'example-webinar:chunk:transcripts', 'example-webinar:chunk:citations'})
self.assertTrue(all(c['transcript_url'].endswith(c['cue_id']) for c in result['citations']))
self.assertEqual(mb.search(self.out, 'unmentionedword'), [])
def test_stale_approval_and_no_partial_output(self):
self.edit(self.manifest, lambda m: m.update(title='Changed title'))
with self.assertRaisesRegex(ValueError, 'stale'):
self.build()
self.assertFalse(self.out.exists())
def test_changed_plan_invalidates_approval(self):
self.edit(self.plan, lambda p: p['qa'][0].update(answer='Changed answer'))
with self.assertRaisesRegex(ValueError, 'stale'):
self.build()
def test_draft_cannot_build(self):
self.edit(self.plan, lambda p: p['review'].update(status='draft'))
with self.assertRaisesRegex(ValueError, 'Review missing'):
self.build()
def test_privacy_and_rights_gates(self):
original = mb.load(self.manifest)
for branch, field, value in [('publication', 'consent', 'pending'),
('publication', 'privacy_review', 'pending'),
('rights', 'redistribution_allowed', False)]:
media = copy.deepcopy(original)
media[branch][field] = value
mb.write(self.manifest, media)
self.approve_fixture()
with self.assertRaisesRegex(ValueError, 'cleared consent/privacy'):
self.build()
def test_exact_quote_required(self):
self.edit(self.plan, lambda p: p['qa'][0]['evidence'][0].update(quote='This was never said.'))
self.approve_fixture()
with self.assertRaisesRegex(ValueError, 'exact substring'):
self.build()
def test_quote_must_belong_to_cited_chunk(self):
self.edit(self.plan, lambda p: p['qa'][0]['evidence'][0].update(chunk_id='example-webinar:chunk:citations'))
self.approve_fixture()
with self.assertRaisesRegex(ValueError, 'does not belong'):
self.build()
def test_source_coverage_and_duplicate_identity(self):
original = mb.load(self.plan)
for mutation, error in [
(lambda p: p['chunks'][0]['cue_ids'].pop(), 'cover every cue'),
(lambda p: p['chunks'][1].update(chunk_id=p['chunks'][0]['chunk_id']), 'Duplicate chunk_id')]:
plan = copy.deepcopy(original)
mutation(plan)
mb.write(self.plan, plan)
self.approve_fixture()
with self.assertRaisesRegex(ValueError, error):
self.build()
def test_overlap_and_bad_duration_rejected(self):
for vtt, duration, error in [
('WEBVTT\n\n00:00.000 --> 00:02.000\na\n\n00:01.000 --> 00:03.000\nb\n', 4, 'Overlapping'),
('WEBVTT\n\n00:00.000 --> 00:02.000\na\n', 1, 'outside declared')]:
with self.assertRaisesRegex(ValueError, error):
mb.parse_vtt(vtt, duration)
def test_vtt_normalization_preserves_voice_unicode_and_entities(self):
text = '\ufeffWEBVTT\r\n\r\nNOTE example\r\n\r\noriginal\r\n00:00.000 --> 00:02.000 align:start\r\n<v Ana><b>Café</b> &amp; tea.\r\nSecond line.</v>\r\n'
cue = mb.parse_vtt(text, 2)[0]
self.assertEqual(cue['text'], 'Café & tea. Second line.')
self.assertEqual(cue['speaker'], 'Ana')
self.assertEqual(cue['source_cue_id'], 'original')
def test_unsupported_vtt_fails_explicitly(self):
for body in ['STYLE\n::cue {color:red}', '00:00.000 --> 00:02.000\n<00:01.000>word']:
with self.assertRaises(ValueError):
mb.parse_vtt('WEBVTT\n\n' + body, 2)
def test_txt_mismatch_rejected(self):
(self.folder / 'transcript.txt').write_text('Unrelated source.', encoding='utf-8')
with self.assertRaisesRegex(ValueError, 'TXT/VTT text differs'):
self.build()
def test_catalog_path_traversal_and_synthetic_gate(self):
original = mb.load(self.catalog)
self.edit(self.catalog, lambda c: c['items'][0].update(manifest='../escape.json'))
with self.assertRaisesRegex(ValueError, 'inside'):
self.build()
mb.write(self.catalog, original)
self.edit(self.catalog, lambda c: c.update(allow_synthetic=False))
with self.assertRaisesRegex(ValueError, 'Synthetic media blocked'):
self.build()
def test_duplicate_media_and_later_failure_leave_no_output(self):
self.edit(self.catalog, lambda c: c['items'].append(c['items'][0]))
with self.assertRaisesRegex(ValueError, 'Duplicate media_id'):
self.build()
self.assertFalse(self.out.exists())
def test_existing_output_preserved(self):
self.out.mkdir()
marker = self.out / 'keep.txt'
marker.write_text('keep', encoding='utf-8')
with self.assertRaisesRegex(ValueError, 'already exists'):
self.build()
self.assertEqual(marker.read_text(encoding='utf-8'), 'keep')
def test_failure_in_second_recording_does_not_write_first(self):
audio = self.work / 'source/example-audio/media.json'
self.edit(audio, lambda m: m.update(title='Unreviewed change'))
with self.assertRaisesRegex(ValueError, 'stale'):
self.build()
self.assertFalse(self.out.exists())
self.assertFalse(list(self.work.glob('.media-build-*')))
def test_export_tampering_blocks_search(self):
self.build()
with (self.out / 'media/example-webinar/qa.json').open('a', encoding='utf-8') as f:
f.write(' ')
with self.assertRaisesRegex(ValueError, 'differ from build receipt'):
mb.search(self.out, 'transcript')
def test_embed_only_does_not_claim_time_seeking(self):
self.edit(self.manifest, lambda m: m.update(content_url=None, embed_url='https://video.example.org/player/1'))
self.approve_fixture()
self.build()
folder = self.out / 'media/example-webinar'
self.assertNotIn('hasPart', mb.load(folder / 'schema.jsonld'))
self.assertIsNone(mb.load(folder / 'chunks.json')['chunks'][0]['citations'][0]['playback_url'])
def test_html_and_jsonld_escape_script_content(self):
self.edit(self.manifest, lambda m: m.update(title='</script><script>alert(1)</script>'))
self.approve_fixture()
self.build()
page = (self.out / 'media/example-webinar/index.html').read_text(encoding='utf-8')
self.assertNotIn('</script><script>alert(1)</script>', page)
self.assertIn('&lt;/script&gt;', page)
self.assertIn('\\u003c/script>', page)
def test_signed_url_rejected(self):
self.edit(self.manifest, lambda m: m.update(content_url='https://cdn.example.org/video?token=private'))
with self.assertRaisesRegex(ValueError, 'signed or credential'):
self.build()
def test_draft_is_blocked_and_does_not_replace_plan(self):
draft = self.folder / 'draft.json'
mb.draft(self.manifest, draft)
self.assertEqual(mb.load(draft)['review']['status'], 'draft')
with self.assertRaisesRegex(ValueError, 'Review missing'):
mb.artifacts(self.manifest, draft)
with self.assertRaisesRegex(ValueError, 'already exists'):
mb.draft(self.manifest, draft)
def test_unknown_contract_fields_rejected(self):
self.edit(self.manifest, lambda m: m.update(secret_note='should not export'))
with self.assertRaises(Exception):
self.build()
def test_empty_qa_is_valid(self):
self.edit(self.plan, lambda p: p.update(qa=[]))
self.approve_fixture()
self.build()
self.assertEqual(mb.load(self.out / 'media/example-webinar/qa.json')['qa'], [])
def test_chapter_range_reversed(self):
self.edit(self.plan, lambda p: p['chapters'][0].update(start_cue_id='cue-000002', end_cue_id='cue-000001'))
self.approve_fixture()
with self.assertRaisesRegex(ValueError, 'ordered and non-overlapping'):
self.build()
if __name__ == '__main__':
unittest.main()