from hopx_ai import Sandbox
import os
import json
from typing import Dict, List, Any
from concurrent.futures import ThreadPoolExecutor, as_completed
class IsolatedTestExecutor:
def __init__(self, api_key: str):
self.api_key = api_key
def execute_test(self, test_code: str, test_framework: str = "pytest", timeout: int = 60) -> Dict[str, Any]:
"""Execute a single test in isolated sandbox"""
sandbox = None
try:
# Create fresh sandbox for each test
sandbox = Sandbox.create(
template="code-interpreter",
api_key=self.api_key,
timeout_seconds=timeout + 10
)
# Write test file
test_file = "/workspace/test_file.py"
sandbox.files.write(test_file, test_code)
# Install test framework if needed
if test_framework == "pytest":
sandbox.commands.run("pip install pytest", timeout=30)
# Execute test
result = sandbox.commands.run(f"pytest {test_file} -v", timeout=timeout)
elif test_framework == "unittest":
result = sandbox.commands.run(f"python -m unittest {test_file}", timeout=timeout)
else:
result = sandbox.run_code(test_code, timeout=timeout)
# Parse test results
test_results = self._parse_test_results(result.stdout, test_framework)
return {
"success": result.exit_code == 0,
"exit_code": result.exit_code,
"stdout": result.stdout,
"stderr": result.stderr,
"test_results": test_results,
"execution_time": getattr(result, 'execution_time', 0)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"stderr": str(e)
}
finally:
if sandbox:
sandbox.kill()
def _parse_test_results(self, output: str, framework: str) -> Dict[str, Any]:
"""Parse test framework output"""
if framework == "pytest":
# Parse pytest output
passed = output.count("PASSED")
failed = output.count("FAILED")
return {
"passed": passed,
"failed": failed,
"total": passed + failed
}
else:
return {
"passed": 0,
"failed": 0,
"total": 0
}
# Usage
executor = IsolatedTestExecutor(api_key=os.getenv("HOPX_API_KEY"))
test_code = """
def test_addition():
assert 1 + 1 == 2
def test_subtraction():
assert 5 - 3 == 2
"""
result = executor.execute_test(test_code, test_framework="pytest")
print(json.dumps(result, indent=2))