oracle7-slim / workbench /program_examples.py
psiloceyeben's picture
Release 12.0 (slim): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 5)
6e2225f verified
Raw History Blame Contribute Delete
4.04 kB
"""Read back a received program's behavior in fresh fixture directories."""
import contextlib
import importlib.util
import io
import json
import math
from pathlib import Path
import sys
import tempfile
def same(actual, expected):
if isinstance(actual, bool) or isinstance(expected, bool):
return type(actual) is type(expected) and actual == expected
if isinstance(actual, (int, float)) and isinstance(expected, (int, float)):
return math.isfinite(actual) and math.isfinite(expected) and actual == expected
if type(actual) is not type(expected):
return False
if isinstance(actual, dict):
return actual.keys() == expected.keys() and all(same(actual[k], expected[k]) for k in actual)
if isinstance(actual, list):
return len(actual) == len(expected) and all(same(a, b) for a, b in zip(actual, expected))
return actual == expected
def check(request):
import os
source = Path(request['source']).read_bytes()
received = request['examples']
if not received:
raise ValueError('receive at least one input and its expected result')
old = Path.cwd()
active = {'root': None}
def guard(event, args):
root = active['root']
if root is None:
return
if event.startswith(('socket.', 'subprocess.', 'os.exec', 'os.spawn')) or event in ('os.system', 'os.fork'):
raise PermissionError('behavior examples do not authorize outside effects')
if event == 'open' and isinstance(args[0], (str, bytes, os.PathLike)):
path = Path(os.fsdecode(args[0])).resolve()
mode, flags = args[1], args[2]
writing = (isinstance(mode, str) and any(c in mode for c in 'wax+')) or flags & (os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_TRUNC)
if path != root and root not in path.parents and (writing or path.suffix not in ('.py', '.pyc', '.pyd')):
raise PermissionError('behavior examples may access only their received fixture files')
if event in ('os.remove', 'os.rename', 'os.mkdir', 'os.rmdir', 'os.link', 'os.symlink'):
raise PermissionError('behavior examples do not authorize filesystem structure changes')
sys.addaudithook(guard)
try:
for number, example in enumerate(received):
with tempfile.TemporaryDirectory(prefix='oracle7-program-example-') as directory:
root = Path(directory)
for name, contents in example.get('files', {}).items():
path = (root / name).resolve()
if root not in path.parents or not isinstance(contents, str):
raise ValueError('example files must be relative text files')
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(contents, encoding='utf-8')
os.chdir(root)
path = root / '_received_program.py'
path.write_bytes(source)
spec = importlib.util.spec_from_file_location('_received_program_' + str(number), path)
module = importlib.util.module_from_spec(spec)
with contextlib.redirect_stdout(io.StringIO()):
active['root'] = root
try:
exec(compile(source, str(path), 'exec'), module.__dict__)
module._SHOW = False
actual = module.run(example.get('input'))
finally:
active['root'] = None
if not same(actual, example['expected']):
raise AssertionError('example %d expected %r, received %r' % (number + 1, example['expected'], actual))
os.chdir(old)
finally:
os.chdir(old)
return {'ok': True, 'examples': len(received), 'basis': 'received inputs and expected values; separate execution'}
if __name__ == '__main__':
print(json.dumps(check(json.loads(Path(sys.argv[1]).read_text(encoding='utf-8')))))