import io import sys import contextlib import traceback class CodeExecutor: def __init__(self): pass def run_code(self, code: str): stdout = io.StringIO() stderr = io.StringIO() local_vars = {} try: with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): exec(code, {}, local_vars) return {"output": stdout.getvalue(), "error": stderr.getvalue()} except Exception: return {"output": stdout.getvalue(), "error": traceback.format_exc()} def test_function(self, code: str, test_code: str): combined = code + "\n" + test_code return self.run_code(combined)