Spaces:
Running
Running
File size: 19,334 Bytes
1113aa2 8cc8d07 21f8947 8cc8d07 21f8947 8cc8d07 1113aa2 | 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 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Black-Box Testing Playground</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css">
<style>
:root {
--bg: #1e1e2e; --panel: #252535; --border: #353550;
--accent: #89b4fa; --accent-hover: #74a0f0;
--text: #cdd6f4; --muted: #7f849c;
--err: #f38ba8; --ok: #a6e3a1;
}
* { box-sizing: border-box; }
html, body {
margin: 0; height: 100%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: var(--bg); color: var(--text);
}
body { display: flex; flex-direction: column; height: 100vh; }
header {
display: flex; align-items: center; gap: 12px;
padding: 10px 16px; background: var(--panel);
border-bottom: 1px solid var(--border);
}
header h1 { font-size: 15px; margin: 0; font-weight: 600; }
header .status { font-size: 12px; color: var(--muted); margin-left: auto; }
header .status.ready { color: var(--ok); }
header .status.error { color: var(--err); }
button {
background: var(--accent); color: #11111b; border: none;
padding: 7px 16px; border-radius: 6px; font-size: 13px;
font-weight: 600; cursor: pointer; transition: background .15s;
}
button:hover:not(:disabled) { background: var(--accent-hover); }
button:disabled { opacity: .5; cursor: not-allowed; }
button.ghost { background: transparent; color: var(--muted); }
button.ghost:hover:not(:disabled) { color: var(--text); background: var(--border); }
.kbd { font-size: 11px; color: var(--muted); }
/* Mode toggle (segmented control) */
.seg { display: flex; background: var(--bg); border: 1px solid var(--border); border-radius: 7px; padding: 2px; }
.seg-btn {
background: transparent; color: var(--muted); font-weight: 600;
padding: 5px 12px; border-radius: 5px; font-size: 12px;
}
.seg-btn:hover:not(.active) { color: var(--text); }
.seg-btn.active { background: var(--accent); color: #11111b; }
main { flex: 1; display: flex; min-height: 0; }
.pane { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.pane-label {
padding: 6px 12px; font-size: 11px; text-transform: uppercase;
letter-spacing: .05em; color: var(--muted); background: var(--panel);
border-bottom: 1px solid var(--border);
display: flex; align-items: center; gap: 8px;
}
.pane-label .badge {
font-size: 10px; background: var(--border); color: var(--muted);
padding: 1px 7px; border-radius: 10px; text-transform: none; letter-spacing: 0;
}
#problem {
background: var(--bg); color: var(--text);
border: 1px solid var(--border); border-radius: 8px;
padding: 8px 14px; font-size: 16px; font-weight: 700; cursor: pointer;
text-transform: none; letter-spacing: 0; min-width: 90px;
}
#problem:hover { border-color: var(--accent); }
#problem:focus { outline: none; border-color: var(--accent); }
.editor-wrap { flex: 1; min-height: 0; overflow: hidden; }
.CodeMirror { height: 100% !important; font-size: 14px; font-family: "SF Mono", Menlo, Consolas, monospace; }
.divider { width: 1px; background: var(--border); cursor: col-resize; }
.divider:hover { background: var(--accent); }
#summary {
padding: 8px 16px; font-size: 13px; font-weight: 600;
border-bottom: 1px solid var(--border); background: var(--panel);
display: none;
}
#summary.pass { color: var(--ok); }
#summary.fail { color: var(--err); }
#output {
flex: 1; margin: 0; padding: 12px 16px; overflow: auto;
font-family: "SF Mono", Menlo, Consolas, monospace; font-size: 13px;
line-height: 1.55; white-space: pre-wrap; word-break: break-word;
background: #181825;
}
#output .err { color: var(--err); }
#output .ok { color: var(--ok); }
#output .warn { color: #f9e2af; }
#output .meta { color: var(--muted); }
#output img { max-width: 100%; background: #fff; border-radius: 4px; margin: 8px 0; }
</style>
</head>
<body>
<header>
<h1>Python Playground</h1>
<div class="seg">
<button id="mode-run" class="seg-btn active">Run</button>
<button id="mode-test" class="seg-btn">Black-Box Test</button>
</div>
<button id="run" disabled>βΆ Run <span class="kbd">β/Ctrl+Enter</span></button>
<button id="reset" class="ghost">Reset Template</button>
<span id="status" class="status">Loading runtimeβ¦</span>
</header>
<main>
<div class="pane" id="left">
<div class="pane-label">
<select id="problem" title="Select a problem">
<option value="Q1">Q1</option>
<option value="Q2">Q2</option>
</select>
<span id="leftLabel">Your Code</span>
<span class="badge">editable</span>
</div>
<div class="editor-wrap"><textarea id="code"></textarea></div>
</div>
<div class="divider" id="divider"></div>
<div class="pane" id="right">
<div class="pane-label"><span id="rightLabel">Output</span> <span class="badge" id="modinfo">blackbox: not loaded</span></div>
<div id="summary"></div>
<div id="output"><span class="meta">(Click "Run" once the runtime is ready)</span></div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/pyodide/v0.26.2/full/pyodide.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script>
<script>
// ===== Plain "Run" mode starter =====
const RUN_TEMPLATE = `import sys
print("Python", sys.version.split()[0])
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print([fib(i) for i in range(10)])
`;
// ===== Problems: UI metadata only. The hidden blackbox/oracle live in the worker. =====
const PROBLEMS = {
Q1: {
public: "allocate",
sig: "allocate(students, rooms, capacity, mode)",
testTemplate: `# Q1 Room Allocator -- blackbox.allocate(students, rooms, capacity, mode), 5 bugs.
# TESTS = [ ((args), "expected-from-spec"), ... ], one case per line.
TESTS = [
((50, 2, 30, "Lecture"), "SEATED"),
((200, 5, 25, "Lecture"), "OVERFLOW"),
((50, 2, 30, "Online"), "INVALID"),
]
`,
},
Q2: {
public: "approve",
sig: "approve(role, fte, weekly_hours, period)",
testTemplate: `# Q2 Workload Approval -- blackbox.approve(role, fte, weekly_hours, period), 5 bugs.
# TESTS = [ ((args), "expected-from-spec"), ... ], one case per line.
TESTS = [
(("Tutor", 1.0, 5, "Teaching"), "APPROVED"),
(("Marker", 0.5, 3, "Break"), "APPROVED"),
(("Coordinator", 1.0, 50, "Teaching"), "DENIED"),
]
`,
},
};
// ===== State + working copies (so switching never loses your edits) =====
let mode = "test"; // "run" | "test" -- default to Black-Box Test on load
let prob = "Q1"; // current problem key
const work = {
run: RUN_TEMPLATE,
test: { Q1: PROBLEMS.Q1.testTemplate, Q2: PROBLEMS.Q2.testTemplate },
};
const slotTemplate = () => (mode === "run" ? RUN_TEMPLATE : PROBLEMS[prob].testTemplate);
const saveEditor = () => { if (mode === "run") work.run = editor.getValue(); else work.test[prob] = editor.getValue(); };
const loadEditor = () => editor.setValue(mode === "run" ? work.run : work.test[prob]);
// Pull ONLY the TESTS = [ ... ] list out of whatever the student typed; everything
// else is ignored (never executed). Balanced-bracket scan, quote-aware.
function extractTestsLiteral(src) {
// Anchor to line start so a commented "# TESTS = [ ... ]" line is NOT matched.
const m = /^[ \t]*TESTS\s*=\s*\[/m.exec(src);
if (!m) return null;
const start = src.indexOf("[", m.index);
let depth = 0, quote = null;
for (let j = start; j < src.length; j++) {
const ch = src[j];
if (quote) { if (ch === quote && src[j - 1] !== "\\") quote = null; continue; }
if (ch === '"' || ch === "'") { quote = ch; continue; }
if (ch === "[") depth++;
else if (ch === "]") { depth--; if (depth === 0) return src.slice(start, j + 1); }
}
return null;
}
const output = document.getElementById("output");
const summary = document.getElementById("summary");
const statusEl = document.getElementById("status");
const modinfo = document.getElementById("modinfo");
const runBtn = document.getElementById("run");
const resetBtn = document.getElementById("reset");
const leftLabel = document.getElementById("leftLabel");
const rightLabel= document.getElementById("rightLabel");
const modeRunBtn = document.getElementById("mode-run");
const modeTestBtn = document.getElementById("mode-test");
const problemSel = document.getElementById("problem");
function append(text, cls) {
const span = document.createElement("span");
if (cls) span.className = cls;
span.textContent = text;
output.appendChild(span);
output.scrollTop = output.scrollHeight;
}
// ===== Editor =====
const editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "python", theme: "material-darker",
lineNumbers: true, indentUnit: 4, tabSize: 4, indentWithTabs: false,
extraKeys: {
"Cmd-Enter": run, "Ctrl-Enter": run,
Tab: (cm) => cm.replaceSelection(" "),
},
});
loadEditor();
resetBtn.onclick = () => {
if (mode === "run") work.run = RUN_TEMPLATE; else work.test[prob] = PROBLEMS[prob].testTemplate;
loadEditor();
};
// ===== Mode switching (Run <-> Black-Box Test) =====
function applyMode() {
modeRunBtn.classList.toggle("active", mode === "run");
modeTestBtn.classList.toggle("active", mode === "test");
leftLabel.textContent = mode === "test" ? "Your Test Code" : "Your Code";
rightLabel.textContent = mode === "test" ? "Test Results" : "Output";
const leftBadge = document.querySelector("#left .badge");
if (leftBadge) leftBadge.textContent = mode === "test" ? "only TESTS = [...] is read" : "editable";
modinfo.style.display = mode === "test" ? "" : "none";
summary.style.display = "none";
runBtn.innerHTML = (mode === "test" ? "βΆ Run Tests " : "βΆ Run ")
+ '<span class="kbd">β/Ctrl+Enter</span>';
}
function switchMode(next) {
if (next === mode) return;
saveEditor();
mode = next;
applyMode();
loadEditor();
}
modeRunBtn.onclick = () => switchMode("run");
modeTestBtn.onclick = () => switchMode("test");
// ===== Problem switching (Q1 / Q2) =====
problemSel.onchange = async () => {
saveEditor();
prob = problemSel.value;
loadEditor(); // show this problem's test code
await loadProblem(prob); // swap the hidden blackbox module
};
applyMode();
// ===== 24h local session: keep the code you typed across reloads =====
const A1_KEY = "st_a1_session_v1"; // persists in this browser (no expiry)
let __a1timer = null;
function persistA1(){
clearTimeout(__a1timer);
__a1timer = setTimeout(() => {
try { saveEditor(); localStorage.setItem(A1_KEY, JSON.stringify({ ts: Date.now(), mode, prob, work })); } catch(_){}
}, 250);
}
function restoreA1(){
let d; try { d = JSON.parse(localStorage.getItem(A1_KEY)); } catch(_){ return; }
if (!d) return;
if (d.work){
if (typeof d.work.run === "string") work.run = d.work.run;
if (d.work.test){ if (d.work.test.Q1 != null) work.test.Q1 = d.work.test.Q1; if (d.work.test.Q2 != null) work.test.Q2 = d.work.test.Q2; }
}
if (d.mode) mode = d.mode;
if (d.prob){ prob = d.prob; problemSel.value = prob; }
}
restoreA1();
applyMode();
loadEditor();
editor.on("change", persistA1);
// ===== Grader Web Worker =====
// The answer key (oracle / bug definitions / reasons) lives in a SEPARATE Pyodide
// running inside grader.worker.js, on its own thread with its own memory. Student
// code runs in the main-thread Pyodide below and cannot reach into the worker:
// gc.get_objects(), closure reflection and print(globals()) only see this interpreter.
let grader = null, graderReady = false, mainReady = false;
let __msgId = 0;
const __pending = new Map();
function startGrader() {
grader = new Worker("grader.worker.js?v=" + Date.now()); // bust browser cache of the worker
grader.onmessage = (e) => {
const d = e.data || {};
if (d.type === "ready") { graderReady = true; maybeReady(); return; }
if (d.type === "fatal") { append("Grader failed to load: " + d.error + "\n", "err"); return; }
const p = __pending.get(d.id);
if (!p) return;
__pending.delete(d.id);
if (d.ok) p.resolve(JSON.parse(d.report)); else p.reject(new Error(d.error));
};
grader.onerror = (e) => append("Grader worker error: " + (e.message || e) + "\n", "err");
}
// Send a grading request to the worker and await its report.
function gradeViaWorker(problem, source, testsJson) {
return new Promise((resolve, reject) => {
const id = ++__msgId;
__pending.set(id, { resolve, reject });
grader.postMessage({ id, problem, source, tests: testsJson });
});
}
function maybeReady() {
if (mainReady && graderReady) {
statusEl.textContent = "\u2713 Ready";
statusEl.className = "status ready";
runBtn.disabled = false;
}
}
// ===== Load Pyodide (main thread runs student code only -- no answer key here) =====
let pyodide;
// Problem switch: just update the label. The worker loads the .dat lazily on first grade.
async function loadProblem(key) {
modinfo.textContent = key + " \u00b7 " + PROBLEMS[key].sig;
}
startGrader();
(async () => {
try {
pyodide = await loadPyodide({
stdout: (s) => append(s + "\n"),
stderr: (s) => append(s + "\n", "err"),
});
await loadProblem(prob);
mainReady = true;
maybeReady();
} catch (e) {
statusEl.textContent = "Failed to load";
statusEl.className = "status error";
append("Failed to load runtime: " + e + "\n", "err");
}
})();
// ===== Run the student's tests =====
async function run() {
if (!pyodide || runBtn.disabled) return;
runBtn.disabled = true;
output.innerHTML = "";
summary.style.display = "none";
const code = editor.getValue();
try {
if (mode === "test") {
// Run the student's code in the (clean) main interpreter to define TESTS,
// then send ONLY the TESTS data to the worker. The worker holds the answer
// key in its own interpreter; nothing sensitive lives in this one.
// Regex out the TESTS = [ ... ] block and evaluate ONLY that literal. Student
// code is NEVER executed; anything outside the list is ignored. literal_eval
// accepts numbers/strings/tuples/lists/bools/None and rejects calls/names.
const lit = extractTestsLiteral(code);
if (!lit) {
append('\nNo "TESTS = [ ... ]" found. Define your test cases as a list, e.g.\nTESTS = [ ((50, 2, 30, "Lecture"), "SEATED") ]\n', "err");
return;
}
pyodide.globals.set("__lit", lit);
let testsJson;
try {
testsJson = pyodide.runPython("import ast, json\njson.dumps(ast.literal_eval(__lit))");
} catch (se) {
append('\nTESTS must contain only literal values (numbers, strings, tuples), e.g. ((50, 2, 30, "Lecture"), "SEATED").\n' + cleanError(se.message || String(se)) + "\n", "err");
return;
}
const rep = await gradeViaWorker(prob, code, testsJson);
renderReport(rep);
} else {
// Plain run: just execute and show output, no grading
const result = await pyodide.runPythonAsync(code);
renderMatplotlib();
if (result !== undefined && result !== null) append(String(result) + "\n", "meta");
}
} catch (e) {
append("\nExecution stopped:\n" + cleanError(e.message || String(e)) + "\n", "err");
} finally {
runBtn.disabled = false;
}
}
runBtn.onclick = run;
// Render the grading report: one line per test case, a "Bug caught at line N" for
// each newly-detected bug, and a summary of how many distinct bugs were caught.
function renderReport(rep) {
if (!rep.ok) {
summary.style.display = "none";
append((rep.error || "Invalid test setup.") + "\n", "err");
return;
}
for (const r of rep.rows) {
const at = r.line ? "line " + r.line : "(unknown line)";
if (r.status === "bug") {
append(`β Bug #${r.num}/${r.total} caught at ${at}: ${r.reason}\n`, "ok");
append(` input ${r.argstr} β program returned ${r.actual}, spec expects ${r.expected}\n`, "meta");
} else if (r.status === "combo") {
append(`β ${at}: discrepancy found (program returned ${r.actual}, spec expects ${r.expected}), but this input breaks several boundaries at once β it does NOT isolate one of the 5 bugs. Test one boundary at a time.\n`, "warn");
} else if (r.status === "dup") {
append(`Β· ${at}: catches bug #${r.num} again\n`, "meta");
} else if (r.status === "invalid") {
append(`β ${at}: your expected ${r.expected} does NOT match the spec β this test does not count (program returned ${r.actual})\n`, "warn");
} else if (r.status === "ok") {
append(`Β· ${at}: program matches the spec (${r.actual}) β no bug here\n`, "meta");
} else if (r.status === "malformed") {
append(`β ${at}: malformed test case ${r.raw} β expected ((args), expected)\n`, "err");
} else if (r.status === "error") {
append(`β ${at}: error calling the program on ${r.argstr}: ${r.msg}\n`, "err");
}
}
const all = rep.caughtCount === rep.totalBugs;
summary.style.display = "block";
summary.className = all ? "pass" : "";
summary.style.color = all ? "" : "var(--accent)";
summary.textContent = all
? `π Caught all ${rep.totalBugs}/${rep.totalBugs} bugs`
: `π Caught ${rep.caughtCount}/${rep.totalBugs} bugs (${rep.totalBugs - rep.caughtCount} still hidden)`;
}
// Strip internal file paths from tracebacks to avoid leakage/noise
function cleanError(msg) {
return msg
.split("\n")
.filter((l) => !l.includes("/lib/python") && !l.includes("pyodide"))
.join("\n")
.trim();
}
function renderMatplotlib() {
try {
const has = pyodide.runPython(`"matplotlib" in __import__("sys").modules`);
if (!has) return;
const b64 = pyodide.runPython(`
import io, base64
import matplotlib.pyplot as _plt
_imgs = []
for _n in _plt.get_fignums():
_buf = io.BytesIO()
_plt.figure(_n).savefig(_buf, format="png", dpi=110, bbox_inches="tight")
_imgs.append(base64.b64encode(_buf.getvalue()).decode())
_plt.close("all")
"\\n".join(_imgs)
`);
for (const data of (b64 || "").split("\n")) {
if (!data) continue;
const img = document.createElement("img");
img.src = "data:image/png;base64," + data;
output.appendChild(img);
}
} catch (_) {}
}
// ===== Draggable divider =====
const divider = document.getElementById("divider");
const left = document.getElementById("left");
const mainEl = document.querySelector("main");
let dragging = false;
divider.addEventListener("mousedown", () => (dragging = true));
window.addEventListener("mouseup", () => (dragging = false));
window.addEventListener("mousemove", (e) => {
if (!dragging) return;
const rect = mainEl.getBoundingClientRect();
const pct = ((e.clientX - rect.left) / rect.width) * 100;
if (pct > 15 && pct < 85) left.style.flex = "0 0 " + pct + "%";
});
</script>
</body>
</html>
|