File size: 4,043 Bytes
d9b105f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | """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')))))
|