from hopx_ai import Sandbox
import os
import json
from typing import Dict, Any
class APITestRunner:
def __init__(self, api_key: str):
self.api_key = api_key
self.sandbox = None
def initialize(self):
"""Initialize test sandbox"""
self.sandbox = Sandbox.create(
template="code-interpreter",
api_key=self.api_key,
timeout_seconds=600
)
# Install requests library
self.sandbox.commands.run("pip install requests", timeout=30)
def run_test(self, test_code: str, env_vars: Dict[str, str] = None) -> Dict[str, Any]:
"""Execute API test"""
try:
# Set environment variables
if env_vars:
self.sandbox.env.set_all(env_vars)
# Execute test
result = self.sandbox.run_code(test_code, timeout=30)
# Parse test results
test_results = self._parse_test_results(result.stdout)
return {
"success": result.success and test_results.get("all_passed", False),
"stdout": result.stdout,
"stderr": result.stderr,
"test_results": test_results,
"execution_time": result.execution_time
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
def _parse_test_results(self, output: str) -> Dict[str, Any]:
"""Parse test output"""
# Simple parsing - in production, use proper test framework
passed = output.count("PASS") or output.count("✓")
failed = output.count("FAIL") or output.count("✗")
return {
"all_passed": failed == 0 and passed > 0,
"passed": passed,
"failed": failed
}
def cleanup(self):
"""Clean up test resources"""
if self.sandbox:
self.sandbox.kill()
self.sandbox = None
# Usage
runner = APITestRunner(api_key=os.getenv("HOPX_API_KEY"))
runner.initialize()
test_code = """
import requests
import json
# Test GET endpoint
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
assert response.status_code == 200, f"Expected 200, got {response.status_code}"
data = response.json()
assert 'userId' in data, "Missing userId field"
print("PASS: GET test")
"""
result = runner.run_test(test_code)
print(json.dumps(result, indent=2))
runner.cleanup()