CodeReviewEnv-Elite / validate_env.py
Krsnapriya's picture
Upload folder using huggingface_hub
e8d92f9 verified
Raw History Blame Contribute Delete
10.8 kB
"""
OpenEnv Validation Script for CodeReviewEnv-RX.
Tests all endpoints, determinism, step-based interactions,
inspect-before-flag, time budget, multi-file navigation, and edge cases.
"""
import requests
import sys
import json
BASE = "http://localhost:8000"
passed = 0
failed = 0
def check(name, condition, detail=""):
global passed, failed
if condition:
print(f" βœ… {name}")
passed += 1
else:
print(f" ❌ {name} β€” {detail}")
failed += 1
def test_health():
print("\nπŸ” Health Check")
r = requests.get(f"{BASE}/health")
check("GET /health returns 200", r.status_code == 200)
data = r.json()
check("Status is 'ok'", data.get("status") == "ok")
check("Version is 2.0.0", data.get("version") == "2.0.0")
def test_tasks():
print("\nπŸ” Task Listing")
r = requests.get(f"{BASE}/tasks")
check("GET /tasks returns 200", r.status_code == 200)
data = r.json()
tasks = data.get("tasks", [])
check("At least 6 tasks registered", len(tasks) >= 6, f"Found {len(tasks)}")
for task in tasks:
check(f"Task '{task['name']}' has required fields",
all(k in task for k in ("name", "level", "description", "num_files", "num_required_issues")))
def test_reset():
print("\nπŸ” Reset Endpoint")
for level in ["easy", "medium", "hard", "hard_rx"]:
r = requests.post(f"{BASE}/reset?task_level={level}&seed=42")
check(f"POST /reset?task_level={level} returns 200", r.status_code == 200)
data = r.json()
check(f" Observation has 'available_files'", "available_files" in data)
check(f" Observation has 'visible_code'", "visible_code" in data)
check(f" Progress starts at 0.0", data.get("progress") == 0.0)
check(f" Time left > 0", data.get("time_left", 0) > 0)
check(f" Steps left > 0", data.get("steps_left", 0) > 0)
# Invalid task level
r = requests.post(f"{BASE}/reset?task_level=invalid")
check("Invalid task_level returns 400", r.status_code == 400)
def test_open_file():
print("\nπŸ” Open File Action")
requests.post(f"{BASE}/reset?task_level=easy&seed=42")
# Valid file
r = requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
check("Open valid file returns 200", r.status_code == 200)
data = r.json()
check("Current file is 'main.py'", data["observation"].get("current_file") == "main.py")
check("File in visited_files", "main.py" in data["observation"].get("visited_files", []))
check("Open file gives positive reward", data["reward"]["reward"] > 0)
# Invalid file
r = requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "nonexistent.py"})
check("Open invalid file gives negative reward", r.json()["reward"]["reward"] < 0)
def test_inspect():
print("\nπŸ” Inspect Action")
requests.post(f"{BASE}/reset?task_level=easy&seed=42")
requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
# Valid inspect
r = requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": 5})
check("Inspect returns 200", r.status_code == 200)
data = r.json()
check("Inspect reveals line content", data["observation"].get("last_line") is not None)
check("Line visible in visible_code", "main.py" in data["observation"].get("visible_code", {}))
check("Inspect gives positive reward", data["reward"]["reward"] > 0)
# Repeat inspect (anti-repeat penalty)
r = requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": 5})
check("Repeat inspect gives negative reward", r.json()["reward"]["reward"] < 0)
# Invalid line
r = requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": 999})
check("Invalid line gives negative reward", r.json()["reward"]["reward"] < 0)
def test_inspect_before_flag():
print("\nπŸ” Inspect-Before-Flag Enforcement")
requests.post(f"{BASE}/reset?task_level=easy&seed=42")
requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
# Flag without inspecting = heavy penalty
r = requests.post(f"{BASE}/step", json={
"action_type": "flag", "line_number": 5, "issue_type": "bug", "suggestion": "test"
})
data = r.json()
check("Flag without inspect gives -1.0 penalty", data["reward"]["reward"] == -1.0)
check("Error says 'not_inspected'", data["reward"]["info"].get("error") == "not_inspected")
# Now inspect then flag
requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": 5})
r = requests.post(f"{BASE}/step", json={
"action_type": "flag", "line_number": 5, "issue_type": "bug", "suggestion": "Wrong operator used"
})
data = r.json()
check("Flag after inspect gives positive reward", data["reward"]["reward"] > 0)
check("Result is 'correct'", data["reward"]["info"].get("result") == "correct")
def test_trace():
print("\nπŸ” Call Tracing")
requests.post(f"{BASE}/reset?task_level=medium&seed=42")
requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
# Inspect a line with a function call
requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": 19})
# Trace the call
r = requests.post(f"{BASE}/step", json={"action_type": "trace", "line_number": 19})
check("Trace returns 200", r.status_code == 200)
data = r.json()
trace = data["reward"]["info"].get("call_trace", [])
check("Trace returns call chain", len(trace) > 0, f"Got: {trace}")
def test_time_budget():
print("\nπŸ” Time Budget")
requests.post(f"{BASE}/reset?task_level=easy&seed=42")
r = requests.get(f"{BASE}/state")
state = r.json()
check("Initial time_left is TIME_BUDGET", state.get("time_left", 0) > 0)
# Open file costs 5 time units
requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
r = requests.get(f"{BASE}/state")
state = r.json()
check("Opening file costs time", state.get("time_used", 0) == 5)
def test_multi_file():
print("\nπŸ” Multi-File Navigation")
requests.post(f"{BASE}/reset?task_level=hard_rx&seed=42")
r = requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
data = r.json()
check("hard_rx has multiple files", len(data["observation"].get("available_files", [])) >= 4)
# Navigate to a different file
r = requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "processor.py"})
data = r.json()
check("Can switch files", data["observation"].get("current_file") == "processor.py")
check("Both files in visited_files", len(data["observation"].get("visited_files", [])) == 2)
def test_grader():
print("\nπŸ” Grader Endpoint")
requests.post(f"{BASE}/reset?task_level=easy&seed=42")
requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
# Find both bugs
for line in [5, 10]:
requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": line})
requests.post(f"{BASE}/step", json={
"action_type": "flag", "line_number": line, "issue_type": "bug",
"suggestion": "Fix this bug for correctness"
})
r = requests.get(f"{BASE}/grader")
check("GET /grader returns 200", r.status_code == 200)
data = r.json()
score = data.get("score", -1)
check("Score is between 0.0 and 1.0", 0.0 <= score <= 1.0, f"Got {score}")
check("Correctness is 1.0", data.get("breakdown", {}).get("correctness") == 1.0)
check("Exploration is 1.0", data.get("breakdown", {}).get("exploration") == 1.0)
def test_determinism():
print("\nπŸ” Determinism Check")
scores = []
for _ in range(3):
requests.post(f"{BASE}/reset?task_level=hard&seed=42")
requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": 7})
requests.post(f"{BASE}/step", json={
"action_type": "flag", "line_number": 7, "issue_type": "bug", "suggestion": "fix"
})
r = requests.get(f"{BASE}/grader")
scores.append(r.json()["score"])
check("3 identical runs produce identical scores",
all(s == scores[0] for s in scores), f"Scores: {scores}")
def test_baseline():
print("\nπŸ” Baseline Endpoint")
r = requests.post(f"{BASE}/baseline")
check("POST /baseline returns 200", r.status_code == 200)
data = r.json()
check("Response has 'baseline_scores'", "baseline_scores" in data)
def test_partial_rewards():
print("\nπŸ” Partial Reward Signals")
requests.post(f"{BASE}/reset?task_level=easy&seed=42")
requests.post(f"{BASE}/step", json={"action_type": "open_file", "file_name": "main.py"})
# Inspect + correct flag
requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": 5})
r1 = requests.post(f"{BASE}/step", json={
"action_type": "flag", "line_number": 5, "issue_type": "bug",
"suggestion": "Fix the operator to subtraction"
})
reward1 = r1.json()["reward"]["reward"]
check("Correct flag gives positive reward", reward1 > 0, f"Got {reward1}")
# Inspect + false positive
requests.post(f"{BASE}/step", json={"action_type": "inspect", "line_number": 1})
r2 = requests.post(f"{BASE}/step", json={
"action_type": "flag", "line_number": 1, "issue_type": "bug", "suggestion": "bad"
})
reward2 = r2.json()["reward"]["reward"]
check("False positive gives negative reward", reward2 < 0, f"Got {reward2}")
if __name__ == "__main__":
print("=" * 60)
print(" πŸ§ͺ CodeReviewEnv-RX β€” OpenEnv Validation Suite v2")
print("=" * 60)
try:
requests.get(f"{BASE}/health", timeout=3)
except requests.ConnectionError:
print(f"\n❌ Server not running at {BASE}")
print(" Start it with: uvicorn server.app:app --port 8000")
sys.exit(1)
test_health()
test_tasks()
test_reset()
test_open_file()
test_inspect()
test_inspect_before_flag()
test_trace()
test_time_budget()
test_multi_file()
test_grader()
test_determinism()
test_baseline()
test_partial_rewards()
print("\n" + "=" * 60)
print(f" Results: {passed} passed, {failed} failed")
print("=" * 60)
if failed == 0:
print("\nπŸ† ALL TESTS PASSED β€” Ready for submission!")
else:
print(f"\n⚠️ {failed} test(s) failed β€” fix before submitting!")
sys.exit(1 if failed > 0 else 0)