python-playground / assignment1.html
sh1k4ku's picture
Session: persist answers in localStorage with no expiry (until Clear)
21f8947 verified
Raw History Blame
19.3 kB
<!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>