Kaydet (Commit) b1c3fa57 authored tarafından Gokberk Yaltirakli's avatar Gokberk Yaltirakli Kaydeden (comit) Batuhan Taşkaya

Refactor executor and write tests (#2)

* Refactor executor

* test: Executor tests
üst 728ac35f
......@@ -6,34 +6,24 @@ from contextlib import redirect_stderr, redirect_stdout
from http.server import HTTPServer, SimpleHTTPRequestHandler
from io import StringIO
from namekeeper import NameKeeper
from .namekeeper import NameKeeper
MARSHAL_RAISES = (KeyError, ValueError, TypeError, EOFError)
nk = NameKeeper()
def execute(code):
global nk
class Executor:
def __init__(self, host="", port=18888, handler=SimpleHTTPRequestHandler):
self._httpd = HTTPServer((host, port), handler)
self._httpd.serve_forever()
@staticmethod
def execute(self, code):
global nk
out = StringIO()
err = StringIO()
with redirect_stdout(out), redirect_stderr(err):
_exec = exec
with nk.secure_scope():
_exec(code)
return {"out": out.getvalue(), "err": err.getvalue()}
out = StringIO()
err = StringIO()
with redirect_stdout(out), redirect_stderr(err):
_exec = exec
with nk.secure_scope():
_exec(code)
return {"out": out.getvalue(), "err": err.getvalue()}
class Handler(SimpleHTTPRequestHandler):
execute = Executor.execute
def do_POST(self, *args, **kwargs):
content_length = int(self.headers["Content-Length"])
raw_body = self.rfile.read(content_length).decode()
......@@ -55,6 +45,11 @@ class Handler(SimpleHTTPRequestHandler):
self.end_headers()
self.wfile.write(json.dumps({"result": result}).encode())
class Executor:
def __init__(self, host="", port=18888, handler=Handler):
self._httpd = HTTPServer((host, port), handler)
self._httpd.serve_forever()
if __name__ == "__main__":
executor = Executor(port=os.environ.get("EXECUTOR_PORT", 18888), handler=Handler)
......@@ -4,7 +4,7 @@ import types
from collections import defaultdict
from contextlib import contextmanager
from sww import get_members
from .sww import get_members
FORBID_ACCESS = ["open", "exec", "eval", "compile", "input"]
FORBID_BY_TYPE_ACCESS = {
......
#!/usr/bin/env python3
import sys
sys.path.append('.')
from evality.executor import execute
from testsimple import *
plan(tests=10)
ok(execute, 'Execute method exists')
diag('Basic contract')
res = execute('')
ok(res)
ok('out' in res)
ok('err' in res)
ok(not res['out'])
ok(not res['err'])
diag('Getting stdout')
res = execute('print("Test message")')
ok(res['out'] == 'Test message\n')
ok(not res['err'])
diag('Multiline test')
res = execute('''
result = "Hello, "
for c in "World!":
result += c
print(result)
''')
ok(res['out'] == 'Hello, World!\n')
ok(not res['err'])
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment