import json
from sandbox import run_actions, run_sandboxed

cases = {
 'normal': (['x=21','print(x*2)'], 'ok', '42'),
 'host_file': (["print(open('/mnt/c/Windows/win.ini').read())"], 'error', 'FileNotFoundError'),
 'network': (["import socket; socket.socket()"], 'error', 'PermissionError'),
 'process': (["import os; os.fork()"], 'error', 'PermissionError'),
 'memory': (["x=bytearray(200*1024*1024)"], 'error', 'MemoryError'),
 'bounded': (["print('x'*10000)"], 'ok', 'x'),
}
report={}
for name,(actions,expected,fragment) in cases.items():
    got=run_actions(actions,timeout=45)
    assert got['status']=='ok', (name,got)
    result=got['result']['actions'][-1]
    assert result['status']==expected and fragment in result['output'],(name,result)
    if name=='bounded':assert result['truncated'] and len(result['output'])==4096
    report[name]=({'status':result['status'],'output_length':len(result['output']),
                   'truncated':result['truncated']} if name=='bounded' else result)
result=run_sandboxed("import os\nos.write(1,b'started')\nos.close(1)\nos.close(2)\nwhile True: pass",timeout=45)
assert result['status']=='timeout' and result['output']=='started',result
report['timeout']=result
result=run_sandboxed("import os\nwhile True: os.write(1,b'x'*4096)",timeout=45)
assert result['status']=='output_limit',result['status']
report['direct_output_limit']={'status':result['status'],'bytes':len(result['output'])}
print(json.dumps(report,ensure_ascii=False,indent=2))
