Spaces:
Sleeping
Sleeping
File size: 17,665 Bytes
3b33bb3 9fbfa57 3b33bb3 9fbfa57 3b33bb3 7769e75 3b33bb3 7769e75 3b33bb3 7769e75 3b33bb3 7769e75 3b33bb3 7769e75 3b33bb3 7769e75 3b33bb3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
Unittestcasegenerator Environment Implementation.
An RL environment where an LLM agent writes JUnit 5 unit tests
for given Java classes. Tasks range from simple pure functions
to stateful classes requiring exception testing.
"""
import os
import re
import subprocess
import shutil
import tempfile
import textwrap
import json
from typing import Any, Optional
from uuid import uuid4
# from openenv.core.env_server.interfaces import Environment
# from openenv.core.env_server.types import State
try:
from openenv.core.env_server.interfaces import Environment
from openenv.core.env_server.types import State
except ImportError:
# Stub classes so the module can be imported without openenv installed
class Environment:
pass
class State:
def __init__(self, episode_id=None, step_count=0):
self.episode_id = episode_id
self.step_count = step_count
try:
from ..models import UnittestcasegeneratorAction, UnittestcasegeneratorObservation
except ImportError:
from models import UnittestcasegeneratorAction, UnittestcasegeneratorObservation
# βββββββββββββββββββββββββββββββββββββββββββββ
# TASKS
# βββββββββββββββββββββββββββββββββββββββββββββ
TASKS = {
"easy": {
"source_code": textwrap.dedent("""
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public boolean isPalindrome(String s) {
String clean = s.toLowerCase().replace(" ", "");
String reversed = new StringBuilder(clean).reverse().toString();
return clean.equals(reversed);
}
public double celsiusToFahrenheit(double c) {
return c * 9.0 / 5.0 + 32;
}
}
""").strip(),
"source_class": "Calculator",
"test_class": "CalculatorTest",
"task_hint": (
"Write JUnit 5 tests for Calculator class. "
"1) Class name MUST be CalculatorTest. "
"2) Use @Test annotation on every test method. "
"3) Import: import org.junit.jupiter.api.Test; "
"4) Import: import static org.junit.jupiter.api.Assertions.*; "
"5) Write at least 6 test methods. "
"6) Test add(), isPalindrome(), celsiusToFahrenheit(). "
"Reply with ONLY the Java code."
),
"expected_min_tests": 6,
"requires_edge_cases": False,
"requires_exception": False,
},
"medium": {
"source_code": textwrap.dedent("""
public class SafeMath {
public double safeDivide(double a, double b) {
if (b == 0)
throw new IllegalArgumentException("Cannot divide by zero");
return a / b;
}
public int getFirstElement(int[] arr) {
if (arr.length == 0)
throw new IndexOutOfBoundsException("Array is empty");
return arr[0];
}
public int parsePositiveInt(String s) {
int val = Integer.parseInt(s);
if (val <= 0)
throw new IllegalArgumentException("Must be positive");
return val;
}
}
""").strip(),
"source_class": "SafeMath",
"test_class": "SafeMathTest",
"task_hint": (
"Write JUnit 5 tests for SafeMath class. "
"1) Class name MUST be SafeMathTest. "
"2) Use @Test annotation on every test method. "
"3) Import: import org.junit.jupiter.api.Test; "
"4) Import: import static org.junit.jupiter.api.Assertions.*; "
"5) Use assertThrows() for exception testing. "
"6) Test edge cases: empty array, zero, negative. "
"7) Write at least 8 test methods. "
"Reply with ONLY the Java code."
),
"expected_min_tests": 8,
"requires_edge_cases": True,
"requires_exception": True,
},
"hard": {
"source_code": textwrap.dedent("""
import java.util.ArrayList;
import java.util.List;
public class BankAccount {
private String owner;
private double balance;
private List<String> transactions;
public BankAccount(String owner, double balance) {
this.owner = owner;
this.balance = balance;
this.transactions = new ArrayList<>();
}
public double deposit(double amount) {
if (amount <= 0)
throw new IllegalArgumentException("Deposit must be positive");
this.balance += amount;
this.transactions.add("deposit:" + amount);
return this.balance;
}
public double withdraw(double amount) {
if (amount <= 0)
throw new IllegalArgumentException("Withdrawal must be positive");
if (amount > this.balance)
throw new IllegalArgumentException("Insufficient funds");
this.balance -= amount;
this.transactions.add("withdraw:" + amount);
return this.balance;
}
public int getTransactionCount() { return this.transactions.size(); }
public double getBalance() { return this.balance; }
public String getOwner() { return this.owner; }
}
""").strip(),
"source_class": "BankAccount",
"test_class": "BankAccountTest",
"task_hint": (
"Write JUnit 5 tests for BankAccount class. "
"1) Class name MUST be BankAccountTest. "
"2) Use @Test annotation on every test method. "
"3) Import: import org.junit.jupiter.api.Test; "
"4) Import: import static org.junit.jupiter.api.Assertions.*; "
"5) Use assertThrows() for exception testing. "
"6) Test deposit, withdraw, getBalance, getTransactionCount, getOwner. "
"7) Test exceptions: negative deposit, withdraw, insufficient funds. "
"8) Write at least 10 test methods. "
"Reply with ONLY the Java code."
),
"expected_min_tests": 10,
"requires_edge_cases": True,
"requires_exception": True,
},
}
DIFFICULTIES = ("easy", "medium", "hard")
# βββββββββββββββββββββββββββββββββββββββββββββ
# JAVA DETECTION
# βββββββββββββββββββββββββββββββββββββββββββββ
def find_java():
for cmd in ["java", "/usr/bin/java", "/usr/local/bin/java"]:
try:
result = subprocess.run([cmd, "-version"], capture_output=True, text=True)
if result.returncode == 0:
print(json.dumps({"event": "debug", "type": "java_found", "path": cmd}), flush=True)
return cmd
except FileNotFoundError:
continue
return None
def find_javac():
for cmd in ["javac", "/usr/bin/javac", "/usr/local/bin/javac"]:
try:
result = subprocess.run([cmd, "-version"], capture_output=True, text=True)
if result.returncode == 0:
print(json.dumps({"event": "debug", "type": "javac_found", "path": cmd}), flush=True)
return cmd
except FileNotFoundError:
continue
return None
def find_junit_jar():
env_path = os.getenv("JUNIT_JAR")
if env_path and os.path.exists(env_path):
print(json.dumps({"event": "debug", "type": "junit_found", "path": env_path}), flush=True)
return env_path
candidates = [
"/app/junit-platform-console-standalone.jar",
"/app/env/junit-platform-console-standalone.jar",
os.path.join(os.path.dirname(__file__), "..", "junit-platform-console-standalone.jar"),
os.path.join(os.getcwd(), "junit-platform-console-standalone.jar"),
os.path.join(os.getcwd(), "libs", "junit-platform-console-standalone.jar"),
# "/Users/vidhikoul/Desktop/UnitTestCaseGenerator/tcgenerator/junit-platform-console-standalone.jar",
]
for path in candidates:
abs_path = os.path.abspath(path)
if os.path.exists(abs_path):
print(json.dumps({"event": "debug", "type": "junit_found", "path": abs_path}), flush=True)
return abs_path
print(json.dumps({"event": "debug", "type": "junit_not_found", "tried": candidates}), flush=True)
return None
# βββββββββββββββββββββββββββββββββββββββββββββ
# JUNIT SANDBOX
# βββββββββββββββββββββββββββββββββββββββββββββ
def run_junit_tests(source_code: str, test_code: str,
source_class: str, test_class: str,
timeout: int = 30):
java = find_java()
javac = find_javac()
junit = find_junit_jar()
if not java or not javac:
return 0, 0, 0, "Java not found!"
if not junit:
return 0, 0, 0, "JUnit jar not found!"
tmpdir = tempfile.mkdtemp()
try:
source_file = os.path.join(tmpdir, f"{source_class}.java")
test_file = os.path.join(tmpdir, f"{test_class}.java")
with open(source_file, "w") as f:
f.write(source_code)
with open(test_file, "w") as f:
f.write(test_code)
compile_result = subprocess.run(
[javac, "-cp", junit, source_file, test_file],
capture_output=True, text=True,
cwd=tmpdir, timeout=30,
)
if compile_result.returncode != 0:
err = compile_result.stderr[:500]
print(json.dumps({"event": "debug", "type": "compile_error", "message": err[:200]}), flush=True)
return 0, 0, 0, f"Compile error: {err}"
run_result = subprocess.run(
[java, "-jar", junit, "-cp", tmpdir,
"--select-class", test_class, "--details", "summary"],
capture_output=True, text=True,
cwd=tmpdir, timeout=timeout,
)
output = run_result.stdout + run_result.stderr
print(json.dumps({"event": "debug", "type": "junit_output", "message": output[:300]}), flush=True)
passed, failed = parse_junit_output(output)
total = passed + failed
error = None if passed > 0 else output[-400:]
return passed, failed, total, error
except subprocess.TimeoutExpired:
return 0, 0, 0, "Timeout"
except Exception as e:
return 0, 0, 0, str(e)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def parse_junit_output(output: str):
passed = failed = 0
p = re.findall(r'(\d+)\s+tests?\s+successful', output, re.IGNORECASE)
if p:
passed = int(p[0])
f = re.findall(r'(\d+)\s+tests?\s+failed', output, re.IGNORECASE)
if f:
failed = int(f[0])
if passed == 0 and failed == 0:
passed = len(re.findall(r'\[\s*OK\s*\]', output))
failed = len(re.findall(r'\[\s*FAILED\s*\]', output))
return passed, failed
def compute_reward(passed, total, test_code, task_cfg):
eps = 0.001
if total == 0:
return eps
base = (passed / total) * 0.7
quantity_bonus = 0.1 if total >= task_cfg["expected_min_tests"] else 0.0
edge_bonus = 0.0
if task_cfg["requires_edge_cases"]:
edge_keywords = ["empty", "zero", "null", "negative", "0", "[]", '""']
if any(kw in test_code.lower() for kw in edge_keywords):
edge_bonus = 0.1
exception_bonus = 0.0
if task_cfg["requires_exception"]:
if "assertthrows" in test_code.lower():
exception_bonus = 0.1
reward = base + quantity_bonus + edge_bonus + exception_bonus
reward = max(eps, min(reward, 1 - eps))
return reward
# βββββββββββββββββββββββββββββββββββββββββββββ
# ENVIRONMENT CLASS
# βββββββββββββββββββββββββββββββββββββββββββββ
class UnittestcasegeneratorEnvironment(Environment):
"""
JUnit Test Case Generator Environment.
An RL environment where an LLM agent learns to write JUnit 5 unit
tests for Java classes. The agent receives Java source code and must
produce test code that compiles and passes.
Difficulty levels:
easy: Simple pure functions β Calculator class (6+ tests)
medium: Exception handling β SafeMath class (8+ tests)
hard: Stateful class β BankAccount class (10+ tests)
Episode flow:
1. reset(difficulty="easy"|"medium"|"hard")
2. agent reads source_code + task_hint from observation
3. agent calls step(action) with JUnit test code
4. environment compiles + runs tests β returns reward (0.0β1.0)
5. repeat up to 6 steps or until reward >= 0.95
"""
SUPPORTS_CONCURRENT_SESSIONS: bool = True
def __init__(self):
"""Initialize the UnitTestCaseGenerator environment."""
self._state = State(episode_id=str(uuid4()), step_count=0)
self._episode_count = 0
self._step_count = 0
self._max_steps = 6
self._best_reward = 0.0
self._difficulty = "easy"
self._task_cfg = TASKS["easy"]
def reset(
self,
difficulty: Optional[str] = None,
episode_id: Optional[str] = None,
**kwargs: Any,
) -> UnittestcasegeneratorObservation:
"""
Reset the environment with a new task.
Args:
difficulty: "easy" | "medium" | "hard"
Auto-cycles easyβmediumβhard if not provided.
episode_id: Optional custom episode ID.
Returns:
UnittestcasegeneratorObservation with source_code and task_hint.
"""
if difficulty not in DIFFICULTIES:
difficulty = DIFFICULTIES[self._episode_count % 3]
self._episode_count += 1
self._difficulty = difficulty
self._task_cfg = TASKS[difficulty]
self._step_count = 0
self._best_reward = 0.0
self._state = State(
episode_id=episode_id or str(uuid4()),
step_count=0
)
print(json.dumps({
"event": "debug",
"type": "reset",
"difficulty": difficulty,
"source_class": self._task_cfg["source_class"],
}), flush=True)
return UnittestcasegeneratorObservation(
source_code = self._task_cfg["source_code"],
task_hint = self._task_cfg["task_hint"],
passed=0, failed=0, total=0,
error=None, reward=0.0, done=False,
metadata={
"difficulty": difficulty,
"episode_id": self._state.episode_id,
"message": (
f"New {difficulty} task loaded. "
f"Write JUnit 5 tests for {self._task_cfg['source_class']} class."
),
}
)
def step(self, action: UnittestcasegeneratorAction) -> UnittestcasegeneratorObservation:
"""
Execute one step β compile and run the agent's JUnit test code.
Args:
action: UnittestcasegeneratorAction with test_code field.
Returns:
UnittestcasegeneratorObservation with passed/failed counts and reward.
"""
self._state.step_count += 1
self._step_count += 1
done = self._step_count >= self._max_steps
passed, failed, total, error = run_junit_tests(
source_code = self._task_cfg["source_code"],
test_code = action.test_code,
source_class = self._task_cfg["source_class"],
test_class = self._task_cfg["test_class"],
)
reward = compute_reward(passed, total, action.test_code, self._task_cfg)
self._best_reward = max(self._best_reward, reward)
if reward >= 0.95:
done = True
print(json.dumps({
"event": "debug",
"type": "step_result",
"passed": passed,
"failed": failed,
"total": total,
"reward": reward,
"done": done,
}), flush=True)
return UnittestcasegeneratorObservation(
source_code = self._task_cfg["source_code"],
task_hint = self._task_cfg["task_hint"],
passed=passed, failed=failed, total=total,
error=error, reward=reward, done=done,
)
@property
def state(self) -> State:
"""Get current episode state."""
return self._state |