#!/usr/bin/env python3 import hashlib import importlib.util from pathlib import Path import tempfile spec = importlib.util.spec_from_file_location('prefix', Path(__file__).resolve().parents[2] / 'web/prefix.py') p = importlib.util.module_from_spec(spec) spec.loader.exec_module(p) prefix = '/sites/fixture' original = ''' go externalexternal fragment relative
href="/example" ''' rewritten = p.html(original, prefix) assert 'srcset=" /sites/fixture/a.png 1x, /sites/fixture/b.png 2x"' in p.html('', prefix) assert 'url("/sites/fixture/a.png")' in p.html('
', prefix) assert p.srcset('data:image/svg+xml,/untouched 1x, /a.png 2x', prefix) == 'data:image/svg+xml,/untouched 1x, /sites/fixture/a.png 2x' for piece in ['href="/sites/fixture/blog/post?q=1&x=2#part"', 'srcset="/sites/fixture/one.png 1x, /sites/fixture/two.png 2x"', 'url(/sites/fixture/fonts/a.woff2)', 'a[href="/sites/fixture/blog/"]', '@import "/sites/fixture/main.css"']: assert piece in rewritten, piece for piece in ['/* url(/comment) */', 'content:"/ordinary"', 'href="/example"', "fetch('/api/pokes')", "const s = '/assets/unmodified.js'", '{"url":"/unmodified"}', '', 'href="../page.html"', 'href="#part"', 'href="//elsewhere/foo"', 'href="https://other/x"', 'src="data:image/png;base64,abcd"', 'url("data:image/svg+xml,%3Csvg viewBox=\'0 0 10 10\'%3E")']: assert piece in rewritten, piece for invalid in ['', '/', '//host', '/a/../b', '/a?b', '/a#b', 'http://a']: try: p.check_prefix(invalid) raise AssertionError(invalid) except ValueError: pass with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) source, out = root/'normal', root/'preview' source.mkdir() (source/'index.html').write_text(original) (source/'app.js').write_text("fetch('/api/pokes')") def hashes(): return {str(f.relative_to(source)): hashlib.sha256(f.read_bytes()).hexdigest() for f in source.rglob('*') if f.is_file()} before = hashes() p.publish(source, out, prefix) assert hashes() == before assert out.is_symlink() and (out/'index.html').read_text() == rewritten assert (out/'app.js').read_bytes() == (source/'app.js').read_bytes() previous = out.resolve() (source/'app.js').unlink() p.publish(source, out, prefix) assert out.resolve() != previous and previous.exists() assert not (out/'app.js').exists(), 'stale files must not leak into next generation' (source/'escape').symlink_to('/etc/hostname') current = out.resolve() try: p.publish(source, out, prefix) raise AssertionError('symlink accepted') except ValueError: pass assert out.resolve() == current, 'failed generation changed published output' print('prefix: scoped HTML/CSS, unchanged JS/text/source, atomic publication and failure preservation passed')