Spaces:
Running
Running
Add Assignment 2 (decision tables, CFG, loops, mutation playground) + left sidebar shell
Browse files- .gitattributes +4 -0
- a2/assets/img0.png +3 -0
- a2/assets/img1.png +3 -0
- a2/assets/img2.png +3 -0
- a2/assets/img3.png +3 -0
- assignment1.html +474 -0
- assignment2.html +435 -0
- index.html +62 -449
- worker.js +99 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
a2/assets/img0.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
a2/assets/img1.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
a2/assets/img2.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
a2/assets/img3.png filter=lfs diff=lfs merge=lfs -text
|
a2/assets/img0.png
ADDED
|
Git LFS Details
|
a2/assets/img1.png
ADDED
|
Git LFS Details
|
a2/assets/img2.png
ADDED
|
Git LFS Details
|
a2/assets/img3.png
ADDED
|
Git LFS Details
|
assignment1.html
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>Python Black-Box Testing Playground</title>
|
| 7 |
+
|
| 8 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
|
| 9 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css">
|
| 10 |
+
|
| 11 |
+
<style>
|
| 12 |
+
:root {
|
| 13 |
+
--bg: #1e1e2e; --panel: #252535; --border: #353550;
|
| 14 |
+
--accent: #89b4fa; --accent-hover: #74a0f0;
|
| 15 |
+
--text: #cdd6f4; --muted: #7f849c;
|
| 16 |
+
--err: #f38ba8; --ok: #a6e3a1;
|
| 17 |
+
}
|
| 18 |
+
* { box-sizing: border-box; }
|
| 19 |
+
html, body {
|
| 20 |
+
margin: 0; height: 100%;
|
| 21 |
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
| 22 |
+
background: var(--bg); color: var(--text);
|
| 23 |
+
}
|
| 24 |
+
body { display: flex; flex-direction: column; height: 100vh; }
|
| 25 |
+
|
| 26 |
+
header {
|
| 27 |
+
display: flex; align-items: center; gap: 12px;
|
| 28 |
+
padding: 10px 16px; background: var(--panel);
|
| 29 |
+
border-bottom: 1px solid var(--border);
|
| 30 |
+
}
|
| 31 |
+
header h1 { font-size: 15px; margin: 0; font-weight: 600; }
|
| 32 |
+
header .status { font-size: 12px; color: var(--muted); margin-left: auto; }
|
| 33 |
+
header .status.ready { color: var(--ok); }
|
| 34 |
+
header .status.error { color: var(--err); }
|
| 35 |
+
|
| 36 |
+
button {
|
| 37 |
+
background: var(--accent); color: #11111b; border: none;
|
| 38 |
+
padding: 7px 16px; border-radius: 6px; font-size: 13px;
|
| 39 |
+
font-weight: 600; cursor: pointer; transition: background .15s;
|
| 40 |
+
}
|
| 41 |
+
button:hover:not(:disabled) { background: var(--accent-hover); }
|
| 42 |
+
button:disabled { opacity: .5; cursor: not-allowed; }
|
| 43 |
+
button.ghost { background: transparent; color: var(--muted); }
|
| 44 |
+
button.ghost:hover:not(:disabled) { color: var(--text); background: var(--border); }
|
| 45 |
+
.kbd { font-size: 11px; color: var(--muted); }
|
| 46 |
+
|
| 47 |
+
/* Mode toggle (segmented control) */
|
| 48 |
+
.seg { display: flex; background: var(--bg); border: 1px solid var(--border); border-radius: 7px; padding: 2px; }
|
| 49 |
+
.seg-btn {
|
| 50 |
+
background: transparent; color: var(--muted); font-weight: 600;
|
| 51 |
+
padding: 5px 12px; border-radius: 5px; font-size: 12px;
|
| 52 |
+
}
|
| 53 |
+
.seg-btn:hover:not(.active) { color: var(--text); }
|
| 54 |
+
.seg-btn.active { background: var(--accent); color: #11111b; }
|
| 55 |
+
|
| 56 |
+
main { flex: 1; display: flex; min-height: 0; }
|
| 57 |
+
.pane { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
| 58 |
+
.pane-label {
|
| 59 |
+
padding: 6px 12px; font-size: 11px; text-transform: uppercase;
|
| 60 |
+
letter-spacing: .05em; color: var(--muted); background: var(--panel);
|
| 61 |
+
border-bottom: 1px solid var(--border);
|
| 62 |
+
display: flex; align-items: center; gap: 8px;
|
| 63 |
+
}
|
| 64 |
+
.pane-label .badge {
|
| 65 |
+
font-size: 10px; background: var(--border); color: var(--muted);
|
| 66 |
+
padding: 1px 7px; border-radius: 10px; text-transform: none; letter-spacing: 0;
|
| 67 |
+
}
|
| 68 |
+
#problem {
|
| 69 |
+
background: var(--bg); color: var(--text);
|
| 70 |
+
border: 1px solid var(--border); border-radius: 8px;
|
| 71 |
+
padding: 8px 14px; font-size: 16px; font-weight: 700; cursor: pointer;
|
| 72 |
+
text-transform: none; letter-spacing: 0; min-width: 90px;
|
| 73 |
+
}
|
| 74 |
+
#problem:hover { border-color: var(--accent); }
|
| 75 |
+
#problem:focus { outline: none; border-color: var(--accent); }
|
| 76 |
+
|
| 77 |
+
.editor-wrap { flex: 1; min-height: 0; overflow: hidden; }
|
| 78 |
+
.CodeMirror { height: 100% !important; font-size: 14px; font-family: "SF Mono", Menlo, Consolas, monospace; }
|
| 79 |
+
|
| 80 |
+
.divider { width: 1px; background: var(--border); cursor: col-resize; }
|
| 81 |
+
.divider:hover { background: var(--accent); }
|
| 82 |
+
|
| 83 |
+
#summary {
|
| 84 |
+
padding: 8px 16px; font-size: 13px; font-weight: 600;
|
| 85 |
+
border-bottom: 1px solid var(--border); background: var(--panel);
|
| 86 |
+
display: none;
|
| 87 |
+
}
|
| 88 |
+
#summary.pass { color: var(--ok); }
|
| 89 |
+
#summary.fail { color: var(--err); }
|
| 90 |
+
|
| 91 |
+
#output {
|
| 92 |
+
flex: 1; margin: 0; padding: 12px 16px; overflow: auto;
|
| 93 |
+
font-family: "SF Mono", Menlo, Consolas, monospace; font-size: 13px;
|
| 94 |
+
line-height: 1.55; white-space: pre-wrap; word-break: break-word;
|
| 95 |
+
background: #181825;
|
| 96 |
+
}
|
| 97 |
+
#output .err { color: var(--err); }
|
| 98 |
+
#output .ok { color: var(--ok); }
|
| 99 |
+
#output .warn { color: #f9e2af; }
|
| 100 |
+
#output .meta { color: var(--muted); }
|
| 101 |
+
#output img { max-width: 100%; background: #fff; border-radius: 4px; margin: 8px 0; }
|
| 102 |
+
</style>
|
| 103 |
+
</head>
|
| 104 |
+
<body>
|
| 105 |
+
|
| 106 |
+
<header>
|
| 107 |
+
<h1>Python Playground</h1>
|
| 108 |
+
<div class="seg">
|
| 109 |
+
<button id="mode-run" class="seg-btn active">Run</button>
|
| 110 |
+
<button id="mode-test" class="seg-btn">Black-Box Test</button>
|
| 111 |
+
</div>
|
| 112 |
+
<button id="run" disabled>▶ Run <span class="kbd">⌘/Ctrl+Enter</span></button>
|
| 113 |
+
<button id="reset" class="ghost">Reset Template</button>
|
| 114 |
+
<span id="status" class="status">Loading runtime…</span>
|
| 115 |
+
</header>
|
| 116 |
+
|
| 117 |
+
<main>
|
| 118 |
+
<div class="pane" id="left">
|
| 119 |
+
<div class="pane-label">
|
| 120 |
+
<select id="problem" title="Select a problem">
|
| 121 |
+
<option value="Q1">Q1</option>
|
| 122 |
+
<option value="Q2">Q2</option>
|
| 123 |
+
</select>
|
| 124 |
+
<span id="leftLabel">Your Code</span>
|
| 125 |
+
<span class="badge">editable</span>
|
| 126 |
+
</div>
|
| 127 |
+
<div class="editor-wrap"><textarea id="code"></textarea></div>
|
| 128 |
+
</div>
|
| 129 |
+
<div class="divider" id="divider"></div>
|
| 130 |
+
<div class="pane" id="right">
|
| 131 |
+
<div class="pane-label"><span id="rightLabel">Output</span> <span class="badge" id="modinfo">blackbox: not loaded</span></div>
|
| 132 |
+
<div id="summary"></div>
|
| 133 |
+
<div id="output"><span class="meta">(Click "Run" once the runtime is ready)</span></div>
|
| 134 |
+
</div>
|
| 135 |
+
</main>
|
| 136 |
+
|
| 137 |
+
<script src="https://cdn.jsdelivr.net/pyodide/v0.26.2/full/pyodide.js"></script>
|
| 138 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
|
| 139 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script>
|
| 140 |
+
|
| 141 |
+
<script>
|
| 142 |
+
// ===== Plain "Run" mode starter =====
|
| 143 |
+
const RUN_TEMPLATE = `import sys
|
| 144 |
+
print("Python", sys.version.split()[0])
|
| 145 |
+
|
| 146 |
+
def fib(n):
|
| 147 |
+
a, b = 0, 1
|
| 148 |
+
for _ in range(n):
|
| 149 |
+
a, b = b, a + b
|
| 150 |
+
return a
|
| 151 |
+
|
| 152 |
+
print([fib(i) for i in range(10)])
|
| 153 |
+
`;
|
| 154 |
+
|
| 155 |
+
// ===== Problems: UI metadata only. The hidden blackbox/oracle live in the worker. =====
|
| 156 |
+
const PROBLEMS = {
|
| 157 |
+
Q1: {
|
| 158 |
+
public: "allocate",
|
| 159 |
+
sig: "allocate(students, rooms, capacity, mode)",
|
| 160 |
+
testTemplate: `# Q1 Room Allocator -- blackbox.allocate(students, rooms, capacity, mode), 5 bugs.
|
| 161 |
+
# TESTS = [ ((args), "expected-from-spec"), ... ], one case per line.
|
| 162 |
+
TESTS = [
|
| 163 |
+
((50, 2, 30, "Lecture"), "SEATED"),
|
| 164 |
+
((200, 5, 25, "Lecture"), "OVERFLOW"),
|
| 165 |
+
((50, 2, 30, "Online"), "INVALID"),
|
| 166 |
+
]
|
| 167 |
+
`,
|
| 168 |
+
},
|
| 169 |
+
Q2: {
|
| 170 |
+
public: "approve",
|
| 171 |
+
sig: "approve(role, fte, weekly_hours, period)",
|
| 172 |
+
testTemplate: `# Q2 Workload Approval -- blackbox.approve(role, fte, weekly_hours, period), 5 bugs.
|
| 173 |
+
# TESTS = [ ((args), "expected-from-spec"), ... ], one case per line.
|
| 174 |
+
TESTS = [
|
| 175 |
+
(("Tutor", 1.0, 5, "Teaching"), "APPROVED"),
|
| 176 |
+
(("Marker", 0.5, 3, "Break"), "APPROVED"),
|
| 177 |
+
(("Coordinator", 1.0, 50, "Teaching"), "DENIED"),
|
| 178 |
+
]
|
| 179 |
+
`,
|
| 180 |
+
},
|
| 181 |
+
};
|
| 182 |
+
|
| 183 |
+
// ===== State + working copies (so switching never loses your edits) =====
|
| 184 |
+
let mode = "test"; // "run" | "test" -- default to Black-Box Test on load
|
| 185 |
+
let prob = "Q1"; // current problem key
|
| 186 |
+
const work = {
|
| 187 |
+
run: RUN_TEMPLATE,
|
| 188 |
+
test: { Q1: PROBLEMS.Q1.testTemplate, Q2: PROBLEMS.Q2.testTemplate },
|
| 189 |
+
};
|
| 190 |
+
const slotTemplate = () => (mode === "run" ? RUN_TEMPLATE : PROBLEMS[prob].testTemplate);
|
| 191 |
+
const saveEditor = () => { if (mode === "run") work.run = editor.getValue(); else work.test[prob] = editor.getValue(); };
|
| 192 |
+
const loadEditor = () => editor.setValue(mode === "run" ? work.run : work.test[prob]);
|
| 193 |
+
|
| 194 |
+
// Pull ONLY the TESTS = [ ... ] list out of whatever the student typed; everything
|
| 195 |
+
// else is ignored (never executed). Balanced-bracket scan, quote-aware.
|
| 196 |
+
function extractTestsLiteral(src) {
|
| 197 |
+
// Anchor to line start so a commented "# TESTS = [ ... ]" line is NOT matched.
|
| 198 |
+
const m = /^[ \t]*TESTS\s*=\s*\[/m.exec(src);
|
| 199 |
+
if (!m) return null;
|
| 200 |
+
const start = src.indexOf("[", m.index);
|
| 201 |
+
let depth = 0, quote = null;
|
| 202 |
+
for (let j = start; j < src.length; j++) {
|
| 203 |
+
const ch = src[j];
|
| 204 |
+
if (quote) { if (ch === quote && src[j - 1] !== "\\") quote = null; continue; }
|
| 205 |
+
if (ch === '"' || ch === "'") { quote = ch; continue; }
|
| 206 |
+
if (ch === "[") depth++;
|
| 207 |
+
else if (ch === "]") { depth--; if (depth === 0) return src.slice(start, j + 1); }
|
| 208 |
+
}
|
| 209 |
+
return null;
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
const output = document.getElementById("output");
|
| 213 |
+
const summary = document.getElementById("summary");
|
| 214 |
+
const statusEl = document.getElementById("status");
|
| 215 |
+
const modinfo = document.getElementById("modinfo");
|
| 216 |
+
const runBtn = document.getElementById("run");
|
| 217 |
+
const resetBtn = document.getElementById("reset");
|
| 218 |
+
const leftLabel = document.getElementById("leftLabel");
|
| 219 |
+
const rightLabel= document.getElementById("rightLabel");
|
| 220 |
+
const modeRunBtn = document.getElementById("mode-run");
|
| 221 |
+
const modeTestBtn = document.getElementById("mode-test");
|
| 222 |
+
const problemSel = document.getElementById("problem");
|
| 223 |
+
|
| 224 |
+
function append(text, cls) {
|
| 225 |
+
const span = document.createElement("span");
|
| 226 |
+
if (cls) span.className = cls;
|
| 227 |
+
span.textContent = text;
|
| 228 |
+
output.appendChild(span);
|
| 229 |
+
output.scrollTop = output.scrollHeight;
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
// ===== Editor =====
|
| 233 |
+
const editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
| 234 |
+
mode: "python", theme: "material-darker",
|
| 235 |
+
lineNumbers: true, indentUnit: 4, tabSize: 4, indentWithTabs: false,
|
| 236 |
+
extraKeys: {
|
| 237 |
+
"Cmd-Enter": run, "Ctrl-Enter": run,
|
| 238 |
+
Tab: (cm) => cm.replaceSelection(" "),
|
| 239 |
+
},
|
| 240 |
+
});
|
| 241 |
+
loadEditor();
|
| 242 |
+
resetBtn.onclick = () => {
|
| 243 |
+
if (mode === "run") work.run = RUN_TEMPLATE; else work.test[prob] = PROBLEMS[prob].testTemplate;
|
| 244 |
+
loadEditor();
|
| 245 |
+
};
|
| 246 |
+
|
| 247 |
+
// ===== Mode switching (Run <-> Black-Box Test) =====
|
| 248 |
+
function applyMode() {
|
| 249 |
+
modeRunBtn.classList.toggle("active", mode === "run");
|
| 250 |
+
modeTestBtn.classList.toggle("active", mode === "test");
|
| 251 |
+
leftLabel.textContent = mode === "test" ? "Your Test Code" : "Your Code";
|
| 252 |
+
rightLabel.textContent = mode === "test" ? "Test Results" : "Output";
|
| 253 |
+
const leftBadge = document.querySelector("#left .badge");
|
| 254 |
+
if (leftBadge) leftBadge.textContent = mode === "test" ? "only TESTS = [...] is read" : "editable";
|
| 255 |
+
modinfo.style.display = mode === "test" ? "" : "none";
|
| 256 |
+
summary.style.display = "none";
|
| 257 |
+
runBtn.innerHTML = (mode === "test" ? "▶ Run Tests " : "▶ Run ")
|
| 258 |
+
+ '<span class="kbd">⌘/Ctrl+Enter</span>';
|
| 259 |
+
}
|
| 260 |
+
function switchMode(next) {
|
| 261 |
+
if (next === mode) return;
|
| 262 |
+
saveEditor();
|
| 263 |
+
mode = next;
|
| 264 |
+
applyMode();
|
| 265 |
+
loadEditor();
|
| 266 |
+
}
|
| 267 |
+
modeRunBtn.onclick = () => switchMode("run");
|
| 268 |
+
modeTestBtn.onclick = () => switchMode("test");
|
| 269 |
+
|
| 270 |
+
// ===== Problem switching (Q1 / Q2) =====
|
| 271 |
+
problemSel.onchange = async () => {
|
| 272 |
+
saveEditor();
|
| 273 |
+
prob = problemSel.value;
|
| 274 |
+
loadEditor(); // show this problem's test code
|
| 275 |
+
await loadProblem(prob); // swap the hidden blackbox module
|
| 276 |
+
};
|
| 277 |
+
|
| 278 |
+
applyMode();
|
| 279 |
+
|
| 280 |
+
// ===== Grader Web Worker =====
|
| 281 |
+
// The answer key (oracle / bug definitions / reasons) lives in a SEPARATE Pyodide
|
| 282 |
+
// running inside grader.worker.js, on its own thread with its own memory. Student
|
| 283 |
+
// code runs in the main-thread Pyodide below and cannot reach into the worker:
|
| 284 |
+
// gc.get_objects(), closure reflection and print(globals()) only see this interpreter.
|
| 285 |
+
let grader = null, graderReady = false, mainReady = false;
|
| 286 |
+
let __msgId = 0;
|
| 287 |
+
const __pending = new Map();
|
| 288 |
+
|
| 289 |
+
function startGrader() {
|
| 290 |
+
grader = new Worker("grader.worker.js?v=" + Date.now()); // bust browser cache of the worker
|
| 291 |
+
grader.onmessage = (e) => {
|
| 292 |
+
const d = e.data || {};
|
| 293 |
+
if (d.type === "ready") { graderReady = true; maybeReady(); return; }
|
| 294 |
+
if (d.type === "fatal") { append("Grader failed to load: " + d.error + "\n", "err"); return; }
|
| 295 |
+
const p = __pending.get(d.id);
|
| 296 |
+
if (!p) return;
|
| 297 |
+
__pending.delete(d.id);
|
| 298 |
+
if (d.ok) p.resolve(JSON.parse(d.report)); else p.reject(new Error(d.error));
|
| 299 |
+
};
|
| 300 |
+
grader.onerror = (e) => append("Grader worker error: " + (e.message || e) + "\n", "err");
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
// Send a grading request to the worker and await its report.
|
| 304 |
+
function gradeViaWorker(problem, source, testsJson) {
|
| 305 |
+
return new Promise((resolve, reject) => {
|
| 306 |
+
const id = ++__msgId;
|
| 307 |
+
__pending.set(id, { resolve, reject });
|
| 308 |
+
grader.postMessage({ id, problem, source, tests: testsJson });
|
| 309 |
+
});
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
function maybeReady() {
|
| 313 |
+
if (mainReady && graderReady) {
|
| 314 |
+
statusEl.textContent = "\u2713 Ready";
|
| 315 |
+
statusEl.className = "status ready";
|
| 316 |
+
runBtn.disabled = false;
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
// ===== Load Pyodide (main thread runs student code only -- no answer key here) =====
|
| 321 |
+
let pyodide;
|
| 322 |
+
|
| 323 |
+
// Problem switch: just update the label. The worker loads the .dat lazily on first grade.
|
| 324 |
+
async function loadProblem(key) {
|
| 325 |
+
modinfo.textContent = key + " \u00b7 " + PROBLEMS[key].sig;
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
startGrader();
|
| 329 |
+
(async () => {
|
| 330 |
+
try {
|
| 331 |
+
pyodide = await loadPyodide({
|
| 332 |
+
stdout: (s) => append(s + "\n"),
|
| 333 |
+
stderr: (s) => append(s + "\n", "err"),
|
| 334 |
+
});
|
| 335 |
+
await loadProblem(prob);
|
| 336 |
+
mainReady = true;
|
| 337 |
+
maybeReady();
|
| 338 |
+
} catch (e) {
|
| 339 |
+
statusEl.textContent = "Failed to load";
|
| 340 |
+
statusEl.className = "status error";
|
| 341 |
+
append("Failed to load runtime: " + e + "\n", "err");
|
| 342 |
+
}
|
| 343 |
+
})();
|
| 344 |
+
|
| 345 |
+
// ===== Run the student's tests =====
|
| 346 |
+
async function run() {
|
| 347 |
+
if (!pyodide || runBtn.disabled) return;
|
| 348 |
+
runBtn.disabled = true;
|
| 349 |
+
output.innerHTML = "";
|
| 350 |
+
summary.style.display = "none";
|
| 351 |
+
|
| 352 |
+
const code = editor.getValue();
|
| 353 |
+
try {
|
| 354 |
+
if (mode === "test") {
|
| 355 |
+
// Run the student's code in the (clean) main interpreter to define TESTS,
|
| 356 |
+
// then send ONLY the TESTS data to the worker. The worker holds the answer
|
| 357 |
+
// key in its own interpreter; nothing sensitive lives in this one.
|
| 358 |
+
// Regex out the TESTS = [ ... ] block and evaluate ONLY that literal. Student
|
| 359 |
+
// code is NEVER executed; anything outside the list is ignored. literal_eval
|
| 360 |
+
// accepts numbers/strings/tuples/lists/bools/None and rejects calls/names.
|
| 361 |
+
const lit = extractTestsLiteral(code);
|
| 362 |
+
if (!lit) {
|
| 363 |
+
append('\nNo "TESTS = [ ... ]" found. Define your test cases as a list, e.g.\nTESTS = [ ((50, 2, 30, "Lecture"), "SEATED") ]\n', "err");
|
| 364 |
+
return;
|
| 365 |
+
}
|
| 366 |
+
pyodide.globals.set("__lit", lit);
|
| 367 |
+
let testsJson;
|
| 368 |
+
try {
|
| 369 |
+
testsJson = pyodide.runPython("import ast, json\njson.dumps(ast.literal_eval(__lit))");
|
| 370 |
+
} catch (se) {
|
| 371 |
+
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");
|
| 372 |
+
return;
|
| 373 |
+
}
|
| 374 |
+
const rep = await gradeViaWorker(prob, code, testsJson);
|
| 375 |
+
renderReport(rep);
|
| 376 |
+
} else {
|
| 377 |
+
// Plain run: just execute and show output, no grading
|
| 378 |
+
const result = await pyodide.runPythonAsync(code);
|
| 379 |
+
renderMatplotlib();
|
| 380 |
+
if (result !== undefined && result !== null) append(String(result) + "\n", "meta");
|
| 381 |
+
}
|
| 382 |
+
} catch (e) {
|
| 383 |
+
append("\nExecution stopped:\n" + cleanError(e.message || String(e)) + "\n", "err");
|
| 384 |
+
} finally {
|
| 385 |
+
runBtn.disabled = false;
|
| 386 |
+
}
|
| 387 |
+
}
|
| 388 |
+
runBtn.onclick = run;
|
| 389 |
+
|
| 390 |
+
// Render the grading report: one line per test case, a "Bug caught at line N" for
|
| 391 |
+
// each newly-detected bug, and a summary of how many distinct bugs were caught.
|
| 392 |
+
function renderReport(rep) {
|
| 393 |
+
if (!rep.ok) {
|
| 394 |
+
summary.style.display = "none";
|
| 395 |
+
append((rep.error || "Invalid test setup.") + "\n", "err");
|
| 396 |
+
return;
|
| 397 |
+
}
|
| 398 |
+
for (const r of rep.rows) {
|
| 399 |
+
const at = r.line ? "line " + r.line : "(unknown line)";
|
| 400 |
+
if (r.status === "bug") {
|
| 401 |
+
append(`✓ Bug #${r.num}/${r.total} caught at ${at}: ${r.reason}\n`, "ok");
|
| 402 |
+
append(` input ${r.argstr} → program returned ${r.actual}, spec expects ${r.expected}\n`, "meta");
|
| 403 |
+
} else if (r.status === "combo") {
|
| 404 |
+
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");
|
| 405 |
+
} else if (r.status === "dup") {
|
| 406 |
+
append(`· ${at}: catches bug #${r.num} again\n`, "meta");
|
| 407 |
+
} else if (r.status === "invalid") {
|
| 408 |
+
append(`⚠ ${at}: your expected ${r.expected} does NOT match the spec — this test does not count (program returned ${r.actual})\n`, "warn");
|
| 409 |
+
} else if (r.status === "ok") {
|
| 410 |
+
append(`· ${at}: program matches the spec (${r.actual}) — no bug here\n`, "meta");
|
| 411 |
+
} else if (r.status === "malformed") {
|
| 412 |
+
append(`✗ ${at}: malformed test case ${r.raw} — expected ((args), expected)\n`, "err");
|
| 413 |
+
} else if (r.status === "error") {
|
| 414 |
+
append(`✗ ${at}: error calling the program on ${r.argstr}: ${r.msg}\n`, "err");
|
| 415 |
+
}
|
| 416 |
+
}
|
| 417 |
+
const all = rep.caughtCount === rep.totalBugs;
|
| 418 |
+
summary.style.display = "block";
|
| 419 |
+
summary.className = all ? "pass" : "";
|
| 420 |
+
summary.style.color = all ? "" : "var(--accent)";
|
| 421 |
+
summary.textContent = all
|
| 422 |
+
? `🐞 Caught all ${rep.totalBugs}/${rep.totalBugs} bugs`
|
| 423 |
+
: `🐞 Caught ${rep.caughtCount}/${rep.totalBugs} bugs (${rep.totalBugs - rep.caughtCount} still hidden)`;
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
// Strip internal file paths from tracebacks to avoid leakage/noise
|
| 427 |
+
function cleanError(msg) {
|
| 428 |
+
return msg
|
| 429 |
+
.split("\n")
|
| 430 |
+
.filter((l) => !l.includes("/lib/python") && !l.includes("pyodide"))
|
| 431 |
+
.join("\n")
|
| 432 |
+
.trim();
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
function renderMatplotlib() {
|
| 436 |
+
try {
|
| 437 |
+
const has = pyodide.runPython(`"matplotlib" in __import__("sys").modules`);
|
| 438 |
+
if (!has) return;
|
| 439 |
+
const b64 = pyodide.runPython(`
|
| 440 |
+
import io, base64
|
| 441 |
+
import matplotlib.pyplot as _plt
|
| 442 |
+
_imgs = []
|
| 443 |
+
for _n in _plt.get_fignums():
|
| 444 |
+
_buf = io.BytesIO()
|
| 445 |
+
_plt.figure(_n).savefig(_buf, format="png", dpi=110, bbox_inches="tight")
|
| 446 |
+
_imgs.append(base64.b64encode(_buf.getvalue()).decode())
|
| 447 |
+
_plt.close("all")
|
| 448 |
+
"\\n".join(_imgs)
|
| 449 |
+
`);
|
| 450 |
+
for (const data of (b64 || "").split("\n")) {
|
| 451 |
+
if (!data) continue;
|
| 452 |
+
const img = document.createElement("img");
|
| 453 |
+
img.src = "data:image/png;base64," + data;
|
| 454 |
+
output.appendChild(img);
|
| 455 |
+
}
|
| 456 |
+
} catch (_) {}
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
// ===== Draggable divider =====
|
| 460 |
+
const divider = document.getElementById("divider");
|
| 461 |
+
const left = document.getElementById("left");
|
| 462 |
+
const mainEl = document.querySelector("main");
|
| 463 |
+
let dragging = false;
|
| 464 |
+
divider.addEventListener("mousedown", () => (dragging = true));
|
| 465 |
+
window.addEventListener("mouseup", () => (dragging = false));
|
| 466 |
+
window.addEventListener("mousemove", (e) => {
|
| 467 |
+
if (!dragging) return;
|
| 468 |
+
const rect = mainEl.getBoundingClientRect();
|
| 469 |
+
const pct = ((e.clientX - rect.left) / rect.width) * 100;
|
| 470 |
+
if (pct > 15 && pct < 85) left.style.flex = "0 0 " + pct + "%";
|
| 471 |
+
});
|
| 472 |
+
</script>
|
| 473 |
+
</body>
|
| 474 |
+
</html>
|
assignment2.html
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>Assignment 2 — Software Testing</title>
|
| 7 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
|
| 8 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css">
|
| 9 |
+
<style>
|
| 10 |
+
:root {
|
| 11 |
+
--bg:#1e1e2e; --panel:#252535; --card:#22222f; --border:#353550;
|
| 12 |
+
--accent:#89b4fa; --accent-hover:#74a0f0;
|
| 13 |
+
--text:#cdd6f4; --muted:#7f849c; --err:#f38ba8; --ok:#a6e3a1; --warn:#f9e2af;
|
| 14 |
+
}
|
| 15 |
+
* { box-sizing:border-box; }
|
| 16 |
+
html,body { margin:0; }
|
| 17 |
+
body {
|
| 18 |
+
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
|
| 19 |
+
background:var(--bg); color:var(--text); line-height:1.55; font-size:14px;
|
| 20 |
+
}
|
| 21 |
+
.wrap { max-width:980px; margin:0 auto; padding:24px 28px 120px; }
|
| 22 |
+
h1 { font-size:22px; margin:0 0 4px; }
|
| 23 |
+
h2 { font-size:18px; margin:34px 0 6px; padding-top:14px; border-top:1px solid var(--border); }
|
| 24 |
+
h2 .pts { font-size:12px; color:var(--muted); font-weight:500; }
|
| 25 |
+
h3 { font-size:14px; color:var(--accent); margin:18px 0 6px; }
|
| 26 |
+
p { margin:8px 0; }
|
| 27 |
+
code, .mono { font-family:"SF Mono",Menlo,Consolas,monospace; }
|
| 28 |
+
pre { background:#181825; border:1px solid var(--border); border-radius:8px; padding:12px 14px; overflow:auto; font-size:13px; }
|
| 29 |
+
.muted { color:var(--muted); }
|
| 30 |
+
a { color:var(--accent); }
|
| 31 |
+
table.dt { border-collapse:collapse; font-size:12px; font-family:"SF Mono",Menlo,Consolas,monospace; margin:4px 0; }
|
| 32 |
+
table.dt th, table.dt td { border:1px solid var(--border); padding:3px 8px; text-align:center; }
|
| 33 |
+
table.dt th { background:var(--panel); color:var(--muted); font-weight:600; }
|
| 34 |
+
table.spec { border-collapse:collapse; font-size:13px; margin:8px 0; }
|
| 35 |
+
table.spec th, table.spec td { border:1px solid var(--border); padding:5px 10px; text-align:left; }
|
| 36 |
+
table.spec th { background:var(--panel); }
|
| 37 |
+
|
| 38 |
+
/* option card with radio */
|
| 39 |
+
.opt {
|
| 40 |
+
border:1px solid var(--border); border-radius:10px; padding:10px 14px; margin:10px 0;
|
| 41 |
+
background:var(--card); transition:border-color .12s, background .12s;
|
| 42 |
+
}
|
| 43 |
+
.opt.sel { border-color:var(--accent); background:#262a3f; }
|
| 44 |
+
.opt-head { display:flex; align-items:center; gap:10px; cursor:pointer; font-weight:600; }
|
| 45 |
+
.opt-head input { width:16px; height:16px; accent-color:var(--accent); cursor:pointer; }
|
| 46 |
+
.opt-body { margin-top:8px; overflow:auto; }
|
| 47 |
+
.opt-body img { max-width:100%; background:#fff; border-radius:6px; }
|
| 48 |
+
|
| 49 |
+
/* fill-in blanks */
|
| 50 |
+
input.blank {
|
| 51 |
+
width:64px; text-align:center; background:#181825; color:var(--ok);
|
| 52 |
+
border:1px solid var(--border); border-radius:5px; padding:2px 4px;
|
| 53 |
+
font-family:"SF Mono",Menlo,Consolas,monospace; font-size:13px; font-weight:600;
|
| 54 |
+
}
|
| 55 |
+
input.blank:focus { outline:none; border-color:var(--accent); }
|
| 56 |
+
input.txt {
|
| 57 |
+
background:#181825; color:var(--text); border:1px solid var(--border);
|
| 58 |
+
border-radius:6px; padding:7px 10px; font-size:13px;
|
| 59 |
+
font-family:"SF Mono",Menlo,Consolas,monospace;
|
| 60 |
+
}
|
| 61 |
+
input.txt:focus { outline:none; border-color:var(--accent); }
|
| 62 |
+
.circ { display:inline-block; min-width:18px; color:var(--accent); font-weight:700; }
|
| 63 |
+
|
| 64 |
+
button {
|
| 65 |
+
background:var(--accent); color:#11111b; border:none; padding:8px 16px;
|
| 66 |
+
border-radius:7px; font-size:13px; font-weight:700; cursor:pointer; transition:background .15s;
|
| 67 |
+
}
|
| 68 |
+
button:hover:not(:disabled){ background:var(--accent-hover); }
|
| 69 |
+
button:disabled { opacity:.5; cursor:not-allowed; }
|
| 70 |
+
button.ghost { background:transparent; color:var(--muted); border:1px solid var(--border); }
|
| 71 |
+
button.ghost:hover:not(:disabled){ color:var(--text); }
|
| 72 |
+
|
| 73 |
+
/* Q4 playground */
|
| 74 |
+
.pg { border:1px solid var(--border); border-radius:10px; overflow:hidden; margin:12px 0; background:var(--card); }
|
| 75 |
+
.pg-head { display:flex; align-items:center; gap:10px; padding:8px 12px; background:var(--panel); border-bottom:1px solid var(--border); flex-wrap:wrap; }
|
| 76 |
+
.pg-head .status { font-size:12px; color:var(--muted); margin-left:auto; }
|
| 77 |
+
.pg-head .status.ready { color:var(--ok); }
|
| 78 |
+
.pg-head .status.error { color:var(--err); }
|
| 79 |
+
.CodeMirror { height:auto; min-height:230px; font-size:13px; font-family:"SF Mono",Menlo,Consolas,monospace; }
|
| 80 |
+
.pg-row { display:flex; gap:14px; flex-wrap:wrap; align-items:flex-end; padding:10px 12px; border-top:1px solid var(--border); }
|
| 81 |
+
.pg-row label { font-size:12px; color:var(--muted); display:block; margin-bottom:4px; }
|
| 82 |
+
#q4out { margin:0; padding:12px 14px; border-top:1px solid var(--border); background:#181825; font-size:13px; white-space:pre-wrap; min-height:40px; }
|
| 83 |
+
#q4out .ok{color:var(--ok);} #q4out .err{color:var(--err);} #q4out .warn{color:var(--warn);} #q4out .meta{color:var(--muted);}
|
| 84 |
+
|
| 85 |
+
/* sticky export bar */
|
| 86 |
+
.exportbar {
|
| 87 |
+
position:fixed; left:0; right:0; bottom:0; background:var(--panel);
|
| 88 |
+
border-top:1px solid var(--border); padding:10px 28px;
|
| 89 |
+
display:flex; align-items:center; gap:14px; z-index:10;
|
| 90 |
+
}
|
| 91 |
+
.exportbar .sid { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--muted); }
|
| 92 |
+
.exportbar .spacer { flex:1; }
|
| 93 |
+
.toast { font-size:12px; color:var(--ok); }
|
| 94 |
+
</style>
|
| 95 |
+
</head>
|
| 96 |
+
<body>
|
| 97 |
+
<div class="wrap">
|
| 98 |
+
<h1>Software Testing — Assignment 2</h1>
|
| 99 |
+
<p class="muted">Answer all questions below. Q4 has an interactive playground. When you are done, export your answers as JSON at the bottom.</p>
|
| 100 |
+
|
| 101 |
+
<!-- ============ Q1 ============ -->
|
| 102 |
+
<h2>Q1 Extended Entry Decision Table <span class="pts">[6 pts] · single choice</span></h2>
|
| 103 |
+
<p>Test the UNSW Lecture-Theatre Booking system with Decision-Table testing. Rules are checked one by one and the <b>first matching rule</b> applies. Outputs: <code>0</code>=Booked, <code>1</code>=Wait-list, <code>2</code>=Rejected.</p>
|
| 104 |
+
<table class="spec">
|
| 105 |
+
<tr><th>Input</th><th>Encoding</th></tr>
|
| 106 |
+
<tr><td>room_size</td><td>1=Small, 2=Medium, 3=Large</td></tr>
|
| 107 |
+
<tr><td>time_slot</td><td>1=Morning, 2=Afternoon, 3=Evening</td></tr>
|
| 108 |
+
<tr><td>week</td><td>1 to 12 (numeric)</td></tr>
|
| 109 |
+
<tr><td>equipment</td><td>1=Standard, 2=AV, 3=ComputerLab, 4=Hybrid</td></tr>
|
| 110 |
+
<tr><td>staff_role</td><td>1=Academic, 2=Admin, 3=Guest</td></tr>
|
| 111 |
+
</table>
|
| 112 |
+
<p class="muted">Rules: invalid input → rejected; exam weeks 11–12 allow only academics and block Large theatres; teaching weeks 1–10 have room/equipment/role constraints; otherwise booked. <b>Exactly one table below is correct — select it.</b></p>
|
| 113 |
+
<div id="q1opts"></div>
|
| 114 |
+
|
| 115 |
+
<!-- ============ Reference function ============ -->
|
| 116 |
+
<h2>Reference function <span class="pts">for Q2, Q3, Q4</span></h2>
|
| 117 |
+
<pre id="reffn"></pre>
|
| 118 |
+
|
| 119 |
+
<!-- ============ Q2 ============ -->
|
| 120 |
+
<h2>Q2 Control-Flow Graph <span class="pts">[3 pts] · single choice</span></h2>
|
| 121 |
+
<p>Below are four candidate CFGs for <code>binary_search</code>, written as DOT graphs and rendered. Exactly one is correct — select it.</p>
|
| 122 |
+
<div id="q2opts"></div>
|
| 123 |
+
|
| 124 |
+
<!-- ============ Q3 ============ -->
|
| 125 |
+
<h2>Q3 Loop-Boundary Test Cases <span class="pts">[3 pts] · fill in the blanks</span></h2>
|
| 126 |
+
<p>Develop a test suite achieving loop-boundary coverage (loop runs 0, 1, and 2 times). Fill each circled blank. Recall <code>mid = int(round((top+bott)/2.0))</code>.</p>
|
| 127 |
+
<p class="muted">Marking: each loop case = 1 mark; within a case, one wrong blank −0.5, two or more wrong −1.</p>
|
| 128 |
+
<pre id="q3block"></pre>
|
| 129 |
+
|
| 130 |
+
<!-- ============ Q4 ============ -->
|
| 131 |
+
<h2>Q4 Fault-Based Testing: Plant a Bug and Catch It <span class="pts">[3 pts] · playground</span></h2>
|
| 132 |
+
<p>(a) Introduce <b>exactly one</b> single-line bug into <code>binary_search</code> so that <b>all three Q3 tests still pass</b> (the bug is invisible to the Q3 suite).
|
| 133 |
+
(b) Give <b>one</b> extra test case that <b>distinguishes</b> the mutant from the original (original passes, mutant fails).</p>
|
| 134 |
+
<p class="muted">Use the playground: edit the function to your mutant, enter your distinguishing test, and press <b>Run check</b>. It reports whether your mutant still passes the Q3 suite and whether your test separates the two.</p>
|
| 135 |
+
|
| 136 |
+
<p style="margin-top:14px"><b>(a) Describe your one-line mutation</b> (form <code>from → to</code>):</p>
|
| 137 |
+
<input class="txt" id="q4mutation" style="width:100%" placeholder="e.g. top = mid - 1 -> top = mid - 2">
|
| 138 |
+
|
| 139 |
+
<div class="pg">
|
| 140 |
+
<div class="pg-head">
|
| 141 |
+
<b>Q4 Playground</b>
|
| 142 |
+
<button id="q4run" disabled>▶ Run check</button>
|
| 143 |
+
<button id="q4reset" class="ghost">Reset to original</button>
|
| 144 |
+
<span class="status" id="q4status">Loading Python runtime…</span>
|
| 145 |
+
</div>
|
| 146 |
+
<textarea id="q4code"></textarea>
|
| 147 |
+
<div class="pg-row">
|
| 148 |
+
<div><label>(b) Distinguishing test — target (Python list)</label>
|
| 149 |
+
<input class="txt" id="q4target" placeholder="[1, 3, 5, 7]" style="width:220px"></div>
|
| 150 |
+
<div><label>key</label>
|
| 151 |
+
<input class="txt" id="q4key" placeholder="3" style="width:90px"></div>
|
| 152 |
+
</div>
|
| 153 |
+
<pre id="q4out"><span class="meta">(edit the function, fill the test, then Run check)</span></pre>
|
| 154 |
+
</div>
|
| 155 |
+
|
| 156 |
+
<!-- ============ Q5 ============ -->
|
| 157 |
+
<h2>Q5 Halstead Programming Effort <span class="pts">[1 pt] · single choice</span></h2>
|
| 158 |
+
<p>Calculate the Halstead <b>programming effort</b> for the following code (parentheses are not counted as operators):</p>
|
| 159 |
+
<pre id="q5code"></pre>
|
| 160 |
+
<div id="q5opts"></div>
|
| 161 |
+
</div>
|
| 162 |
+
|
| 163 |
+
<!-- ============ sticky export bar ============ -->
|
| 164 |
+
<div class="exportbar">
|
| 165 |
+
<div class="sid">Student ID <input class="txt" id="studentId" placeholder="z1234567" style="width:130px"></div>
|
| 166 |
+
<div class="spacer"></div>
|
| 167 |
+
<span class="toast" id="toast"></span>
|
| 168 |
+
<button class="ghost" id="copyBtn">Copy JSON</button>
|
| 169 |
+
<button id="exportBtn">⤓ Export JSON</button>
|
| 170 |
+
</div>
|
| 171 |
+
|
| 172 |
+
<script src="https://cdn.jsdelivr.net/pyodide/v0.26.2/full/pyodide.js"></script>
|
| 173 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
|
| 174 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script>
|
| 175 |
+
<script>
|
| 176 |
+
// ============ canonical reference function ============
|
| 177 |
+
const REF_SRC = `def binary_search(key: int, target: list[int]):
|
| 178 |
+
size = len(target)
|
| 179 |
+
bott = 0
|
| 180 |
+
top = size - 1
|
| 181 |
+
location = 0
|
| 182 |
+
found = False
|
| 183 |
+
if target[location] == key:
|
| 184 |
+
found = True
|
| 185 |
+
else:
|
| 186 |
+
found = False
|
| 187 |
+
while bott <= top and not found:
|
| 188 |
+
mid = int(round((top + bott) / 2.0))
|
| 189 |
+
if target[mid] == key:
|
| 190 |
+
found = True
|
| 191 |
+
location = mid
|
| 192 |
+
else:
|
| 193 |
+
if target[mid] < key:
|
| 194 |
+
bott = mid + 1
|
| 195 |
+
else:
|
| 196 |
+
top = mid - 1
|
| 197 |
+
return found, location`;
|
| 198 |
+
document.getElementById("reffn").textContent = REF_SRC;
|
| 199 |
+
|
| 200 |
+
// ============ Q1: six decision tables ============
|
| 201 |
+
const Q1_COLS = ["rule","room_size","time_slot","week","equipment","staff_role","outcome"];
|
| 202 |
+
const Q1 = {
|
| 203 |
+
1: [["A1","0","-","-","-","-","2"],["A2","-","0","-","-","-","2"],["A3","-","-","13","-","-","2"],["A4","-","-","-","5","-","2"],["A5","-","-","-","-","4","2"],["B1","-","-","11-12","-","2/3","2"],["B2","3","-","11-12","-","1","2"],["C1","3","3","1-10","-","-","2"],["C3","3","-","1-10","-","3","2"],["D1","1","-","-","4","-","2"],["E1","1/2","-","1-10","3","3","1"],["F1","1","3","1-10","-","2","1"],["F2","1","-","11-12","-","2","N/A"],["G","-","-","-","-","-","0"]],
|
| 204 |
+
2: [["A1","0","-","-","-","-","2"],["A2","-","0","-","-","-","2"],["A3","-","-","13","-","-","2"],["A4","-","-","-","5","-","2"],["A5","-","-","-","-","4","2"],["B1","-","-","11-12","-","2/3","2"],["B2","3","-","11-12","-","1","2"],["C1","3","3","1-10","-","-","2"],["C2","3","-","1-10","3","-","2"],["C3","3","-","1-10","-","3","2"],["D1","1","-","-","4","-","2"],["E1","1/2","-","1-10","3","3","2"],["F1","1","3","1-10","-","2","1"],["F2","1","-","11-12","-","2","N/A"],["G","-","-","-","-","-","0"]],
|
| 205 |
+
3: [["A1","0","-","-","-","-","2"],["A2","-","0","-","-","-","2"],["A3","-","-","13","-","-","2"],["A4","-","-","-","5","-","2"],["A5","-","-","-","-","4","2"],["B1","-","-","11-12","-","2/3","2"],["B2","3","-","11-12","-","1","2"],["C1","3","3","1-10","-","-","2"],["C2","3","-","1-10","3","-","2"],["C3","-","-","1-10","-","3","2"],["D1","1","-","-","4","-","2"],["E1","1/2","-","1-10","3","3","1"],["F1","1","3","1-10","-","2","1"],["F2","1","-","11-12","-","2","N/A"],["G","-","-","-","-","-","0"]],
|
| 206 |
+
4: [["A1","0","-","-","-","-","2"],["A2","-","0","-","-","-","2"],["A3","-","-","13","-","-","2"],["A4","-","-","-","5","-","2"],["A5","-","-","-","-","4","2"],["B1","-","-","10-12","-","2/3","2"],["B2","3","-","10-12","-","1","2"],["C1","3","3","1-9","-","-","2"],["C2","3","-","1-9","3","-","2"],["C3","3","-","1-9","-","3","2"],["D1","1","-","-","4","-","2"],["E1","1/2","-","1-9","3","3","1"],["F1","1","3","1-9","-","2","1"],["F2","1","-","10-12","-","2","N/A"],["G","-","-","-","-","-","0"]],
|
| 207 |
+
5: [["A1","0","-","-","-","-","2"],["A2","-","0","-","-","-","2"],["A3","-","-","13","-","-","2"],["A4","-","-","-","5","-","2"],["A5","-","-","-","-","4","2"],["B1","-","-","11-12","-","2/3","2"],["B2","3","-","11-12","-","1","2"],["C1","3","3","1-10","-","-","2"],["C2","3","-","1-10","3","-","2"],["C3","3","-","1-10","-","3","2"],["D1","1","-","-","4","-","2"],["E1","1/2","-","1-10","3","3","1"],["F1","1","3","1-10","-","2","1"],["F2","1","-","11-12","-","2","N/A"],["G","-","-","-","-","-","0"]],
|
| 208 |
+
6: [["A1","0","-","-","-","-","2"],["A2","-","0","-","-","-","2"],["A3","-","-","13","-","-","2"],["A4","-","-","-","5","-","2"],["A5","-","-","-","-","4","2"],["B1","-","-","11-12","-","3","2"],["B2","3","-","11-12","-","1","2"],["C1","3","3","1-10","-","-","2"],["C2","3","-","1-10","3","-","2"],["C3","3","-","1-10","-","3","2"],["D1","1","-","-","4","-","2"],["E1","1/2","-","1-10","3","3","1"],["F1","1","3","1-10","-","2","1"],["F2","1","-","11-12","-","2","N/A"],["G","-","-","-","-","-","0"]],
|
| 209 |
+
};
|
| 210 |
+
function dtTable(rows){
|
| 211 |
+
let h = "<table class='dt'><tr>" + Q1_COLS.map(c=>`<th>${c}</th>`).join("") + "</tr>";
|
| 212 |
+
for (const r of rows) h += "<tr>" + r.map(x=>`<td>${x}</td>`).join("") + "</tr>";
|
| 213 |
+
return h + "</table>";
|
| 214 |
+
}
|
| 215 |
+
const answers = { q1:null, q2:null, q3:{}, q5:null };
|
| 216 |
+
function buildChoice(host, name, items, onSel){
|
| 217 |
+
host.innerHTML = "";
|
| 218 |
+
for (const it of items){
|
| 219 |
+
const card = document.createElement("div"); card.className = "opt";
|
| 220 |
+
card.innerHTML = `<label class="opt-head"><input type="radio" name="${name}" value="${it.val}"><span>${it.label}</span></label><div class="opt-body">${it.body}</div>`;
|
| 221 |
+
const radio = card.querySelector("input");
|
| 222 |
+
radio.onchange = () => {
|
| 223 |
+
[...host.querySelectorAll(".opt")].forEach(o=>o.classList.remove("sel"));
|
| 224 |
+
card.classList.add("sel"); onSel(it.val);
|
| 225 |
+
};
|
| 226 |
+
host.appendChild(card);
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
buildChoice(document.getElementById("q1opts"), "q1",
|
| 230 |
+
[1,2,3,4,5,6].map(n=>({val:String(n), label:"Option "+n, body:dtTable(Q1[n])})),
|
| 231 |
+
v => answers.q1 = v);
|
| 232 |
+
|
| 233 |
+
// ============ Q2: four CFG images ============
|
| 234 |
+
buildChoice(document.getElementById("q2opts"), "q2",
|
| 235 |
+
[1,2,3,4].map(n=>({val:String(n), label:"Option "+n, body:`<img src="a2/assets/img${n-1}.png" alt="CFG option ${n}">`})),
|
| 236 |
+
v => answers.q2 = v);
|
| 237 |
+
|
| 238 |
+
// ============ Q3: fill-in trace with 12 blanks ============
|
| 239 |
+
const Q3_TEXT =
|
| 240 |
+
`Test 1 loop runs 0 times
|
| 241 |
+
Input: target = [5, 8, 12], key = @1@
|
| 242 |
+
Output: found = @2@ , location = @3@
|
| 243 |
+
Reason: target[0] @4@ key, so found is True before the loop;
|
| 244 |
+
'not found' in the while condition is @5@ , the body is skipped.
|
| 245 |
+
|
| 246 |
+
Test 2 loop runs 1 time
|
| 247 |
+
Input: target = [2, 4, 6], key = 4
|
| 248 |
+
Output: found = True, location = @6@
|
| 249 |
+
Reason: target[0]=2 != 4, enter the loop. First mid = @7@ ,
|
| 250 |
+
target[mid] = @8@ = key, found=True, location set, loop exits.
|
| 251 |
+
|
| 252 |
+
Test 3 loop runs 2 times
|
| 253 |
+
Input: target = [1, 3, 5, 7, 9], key = @9@
|
| 254 |
+
Output: found = True, location = @10@
|
| 255 |
+
Reason: first mid=2, target[2]=5 < 9, bott becomes @11@ ;
|
| 256 |
+
second mid = @12@ , where round(3.5)=4, target[4]=9 = key, found.`;
|
| 257 |
+
(function buildQ3(){
|
| 258 |
+
const host = document.getElementById("q3block");
|
| 259 |
+
host.textContent = ""; host.style.whiteSpace = "pre-wrap";
|
| 260 |
+
const parts = Q3_TEXT.split(/@(\d+)@/);
|
| 261 |
+
for (let i=0;i<parts.length;i++){
|
| 262 |
+
if (i % 2 === 0){ host.appendChild(document.createTextNode(parts[i])); }
|
| 263 |
+
else {
|
| 264 |
+
const n = parts[i];
|
| 265 |
+
const wrap = document.createElement("span");
|
| 266 |
+
const circ = document.createElement("span"); circ.className="circ"; circ.textContent = "⓪".replace("⓪","")+"";
|
| 267 |
+
const inp = document.createElement("input");
|
| 268 |
+
inp.className = "blank"; inp.dataset.n = n; inp.title = "blank "+n;
|
| 269 |
+
inp.placeholder = n;
|
| 270 |
+
inp.oninput = () => answers.q3[n] = inp.value;
|
| 271 |
+
host.appendChild(inp);
|
| 272 |
+
}
|
| 273 |
+
}
|
| 274 |
+
})();
|
| 275 |
+
|
| 276 |
+
// ============ Q5: code + options ============
|
| 277 |
+
document.getElementById("q5code").textContent =
|
| 278 |
+
`d = a + b # addition
|
| 279 |
+
e = b * c # multiplication
|
| 280 |
+
f = d / (e + 1) # division and addition
|
| 281 |
+
|
| 282 |
+
if f > 0:
|
| 283 |
+
g = f + d - e # operations in conditional branch
|
| 284 |
+
if f <= 0:
|
| 285 |
+
g = d - e / (c + 1) # different operations without else
|
| 286 |
+
|
| 287 |
+
result = g * a + b - c # final operation
|
| 288 |
+
|
| 289 |
+
return result`;
|
| 290 |
+
buildChoice(document.getElementById("q5opts"), "q5",
|
| 291 |
+
[["a","(a) 2729.72"],["b","(b) 2827.21"],["c","(c) 2882.64"],["d","(d) 2938.08"]]
|
| 292 |
+
.map(([v,l])=>({val:v, label:l, body:""})),
|
| 293 |
+
v => answers.q5 = v);
|
| 294 |
+
|
| 295 |
+
// ============ Q4 playground (Pyodide) ============
|
| 296 |
+
const q4status = document.getElementById("q4status");
|
| 297 |
+
const q4run = document.getElementById("q4run");
|
| 298 |
+
const q4out = document.getElementById("q4out");
|
| 299 |
+
const q4target = document.getElementById("q4target");
|
| 300 |
+
const q4key = document.getElementById("q4key");
|
| 301 |
+
let lastQ4 = { original_output:"", mutant_output:"" };
|
| 302 |
+
|
| 303 |
+
const editor = CodeMirror.fromTextArea(document.getElementById("q4code"), {
|
| 304 |
+
mode:"python", theme:"material-darker", lineNumbers:true, indentUnit:4, tabSize:4,
|
| 305 |
+
extraKeys:{ "Cmd-Enter":runQ4, "Ctrl-Enter":runQ4, Tab:cm=>cm.replaceSelection(" ") },
|
| 306 |
+
});
|
| 307 |
+
editor.setValue(REF_SRC);
|
| 308 |
+
document.getElementById("q4reset").onclick = () => editor.setValue(REF_SRC);
|
| 309 |
+
|
| 310 |
+
function q4append(t, cls){ const s=document.createElement("span"); if(cls)s.className=cls; s.textContent=t; q4out.appendChild(s); }
|
| 311 |
+
|
| 312 |
+
const HARNESS = `
|
| 313 |
+
import json, ast
|
| 314 |
+
def __make_orig():
|
| 315 |
+
ns = {}
|
| 316 |
+
exec(__REF, ns)
|
| 317 |
+
return ns["binary_search"]
|
| 318 |
+
def __run():
|
| 319 |
+
res = {}
|
| 320 |
+
try:
|
| 321 |
+
orig = __make_orig()
|
| 322 |
+
except Exception as e:
|
| 323 |
+
return json.dumps({"error":"reference error: "+str(e)})
|
| 324 |
+
ns = {}
|
| 325 |
+
try:
|
| 326 |
+
exec(__MUT, ns)
|
| 327 |
+
except Exception as e:
|
| 328 |
+
return json.dumps({"error":"Your code has an error: "+str(e)})
|
| 329 |
+
mut = ns.get("binary_search")
|
| 330 |
+
if mut is None:
|
| 331 |
+
return json.dumps({"error":"Your code must define a function named binary_search."})
|
| 332 |
+
q3 = [([5,8,12],5), ([2,4,6],4), ([1,3,5,7,9],9)]
|
| 333 |
+
rows = []; allpass = True
|
| 334 |
+
for tgt,k in q3:
|
| 335 |
+
try: o = orig(k, list(tgt))
|
| 336 |
+
except Exception as e: o = "ERR: "+str(e)
|
| 337 |
+
try: m = mut(k, list(tgt))
|
| 338 |
+
except Exception as e: m = "ERR: "+str(e)
|
| 339 |
+
same = (str(o)==str(m))
|
| 340 |
+
if not same: allpass = False
|
| 341 |
+
rows.append({"target":str(list(tgt)),"key":k,"orig":str(o),"mut":str(m),"same":same})
|
| 342 |
+
dist = None
|
| 343 |
+
ts = __TGT.strip(); ks = __KEY.strip()
|
| 344 |
+
if ts and ks:
|
| 345 |
+
try:
|
| 346 |
+
tgt = ast.literal_eval(ts); k = ast.literal_eval(ks)
|
| 347 |
+
try: o = orig(k, tgt)
|
| 348 |
+
except Exception as e: o = "ERR: "+str(e)
|
| 349 |
+
try: m = mut(k, tgt)
|
| 350 |
+
except Exception as e: m = "ERR: "+str(e)
|
| 351 |
+
dist = {"target":str(tgt),"key":str(k),"orig":str(o),"mut":str(m),"differs":(str(o)!=str(m))}
|
| 352 |
+
except Exception as e:
|
| 353 |
+
dist = {"error":"could not parse target/key: "+str(e)}
|
| 354 |
+
return json.dumps({"rows":rows,"allpass":allpass,"dist":dist})
|
| 355 |
+
__run()
|
| 356 |
+
`;
|
| 357 |
+
|
| 358 |
+
let pyodide = null;
|
| 359 |
+
async function runQ4(){
|
| 360 |
+
if (!pyodide || q4run.disabled) return;
|
| 361 |
+
q4run.disabled = true; q4out.innerHTML = "";
|
| 362 |
+
try {
|
| 363 |
+
pyodide.globals.set("__REF", REF_SRC);
|
| 364 |
+
pyodide.globals.set("__MUT", editor.getValue());
|
| 365 |
+
pyodide.globals.set("__TGT", q4target.value || "");
|
| 366 |
+
pyodide.globals.set("__KEY", q4key.value || "");
|
| 367 |
+
const rep = JSON.parse(pyodide.runPython(HARNESS));
|
| 368 |
+
if (rep.error){ q4append(rep.error+"\n","err"); lastQ4={original_output:"",mutant_output:""}; return; }
|
| 369 |
+
q4append("Q3 suite on your mutant (must all pass / match):\n","meta");
|
| 370 |
+
for (const r of rep.rows){
|
| 371 |
+
const tag = r.same ? " PASS " : " FAIL ";
|
| 372 |
+
q4append(tag, r.same?"ok":"err");
|
| 373 |
+
q4append(`target=${r.target}, key=${r.key} original=${r.orig} mutant=${r.mut}\n`, "meta");
|
| 374 |
+
}
|
| 375 |
+
if (rep.allpass) q4append("(a) ✓ Mutant is invisible to the Q3 suite — all three match.\n","ok");
|
| 376 |
+
else q4append("(a) ✗ Mutant changes a Q3 result — the Q3 suite would catch it. Pick a bug on an unexercised path.\n","warn");
|
| 377 |
+
q4append("\n");
|
| 378 |
+
if (!rep.dist){ q4append("(b) Fill target + key above to test your distinguishing case.\n","meta"); lastQ4={original_output:"",mutant_output:""}; }
|
| 379 |
+
else if (rep.dist.error){ q4append("(b) "+rep.dist.error+"\n","err"); lastQ4={original_output:"",mutant_output:""}; }
|
| 380 |
+
else {
|
| 381 |
+
lastQ4 = { original_output: rep.dist.orig, mutant_output: rep.dist.mut };
|
| 382 |
+
q4append(`(b) Distinguishing test target=${rep.dist.target}, key=${rep.dist.key}\n`,"meta");
|
| 383 |
+
q4append(` original = ${rep.dist.orig}\n mutant = ${rep.dist.mut}\n`,"meta");
|
| 384 |
+
if (rep.dist.differs) q4append(" ✓ This test distinguishes the mutant from the original.\n","ok");
|
| 385 |
+
else q4append(" ✗ Same output on both — this test does NOT distinguish them yet.\n","warn");
|
| 386 |
+
}
|
| 387 |
+
} catch(e){ q4append("Runtime error: "+e+"\n","err"); }
|
| 388 |
+
finally { q4run.disabled = false; }
|
| 389 |
+
}
|
| 390 |
+
q4run.onclick = runQ4;
|
| 391 |
+
(async () => {
|
| 392 |
+
try {
|
| 393 |
+
pyodide = await loadPyodide({});
|
| 394 |
+
q4status.textContent = "✓ Ready"; q4status.className = "status ready"; q4run.disabled = false;
|
| 395 |
+
} catch(e){ q4status.textContent = "Failed to load"; q4status.className = "status error"; }
|
| 396 |
+
})();
|
| 397 |
+
|
| 398 |
+
// ============ JSON export (fixed format) ============
|
| 399 |
+
function buildJSON(){
|
| 400 |
+
const q3 = {};
|
| 401 |
+
for (let i=1;i<=12;i++) q3[i] = (answers.q3[i] || "");
|
| 402 |
+
return {
|
| 403 |
+
assignment: "Software Testing — Assignment 2",
|
| 404 |
+
student_id: document.getElementById("studentId").value.trim(),
|
| 405 |
+
answers: {
|
| 406 |
+
q1: answers.q1 || "",
|
| 407 |
+
q2: answers.q2 || "",
|
| 408 |
+
q3: q3,
|
| 409 |
+
q4: {
|
| 410 |
+
mutation: document.getElementById("q4mutation").value.trim(),
|
| 411 |
+
mutant_code: editor.getValue(),
|
| 412 |
+
test: { target: q4target.value.trim(), key: q4key.value.trim() },
|
| 413 |
+
original_output: lastQ4.original_output,
|
| 414 |
+
mutant_output: lastQ4.mutant_output
|
| 415 |
+
},
|
| 416 |
+
q5: answers.q5 || ""
|
| 417 |
+
}
|
| 418 |
+
};
|
| 419 |
+
}
|
| 420 |
+
function toast(msg){ const t=document.getElementById("toast"); t.textContent=msg; setTimeout(()=>t.textContent="",2500); }
|
| 421 |
+
document.getElementById("exportBtn").onclick = () => {
|
| 422 |
+
const data = JSON.stringify(buildJSON(), null, 2);
|
| 423 |
+
const blob = new Blob([data], {type:"application/json"});
|
| 424 |
+
const a = document.createElement("a");
|
| 425 |
+
const sid = document.getElementById("studentId").value.trim() || "submission";
|
| 426 |
+
a.href = URL.createObjectURL(blob); a.download = `assignment2_${sid}.json`;
|
| 427 |
+
a.click(); URL.revokeObjectURL(a.href); toast("Exported ✓");
|
| 428 |
+
};
|
| 429 |
+
document.getElementById("copyBtn").onclick = async () => {
|
| 430 |
+
try { await navigator.clipboard.writeText(JSON.stringify(buildJSON(), null, 2)); toast("Copied ✓"); }
|
| 431 |
+
catch(_){ toast("Copy failed"); }
|
| 432 |
+
};
|
| 433 |
+
</script>
|
| 434 |
+
</body>
|
| 435 |
+
</html>
|
index.html
CHANGED
|
@@ -3,472 +3,85 @@
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
-
<title>
|
| 7 |
-
|
| 8 |
-
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
|
| 9 |
-
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css">
|
| 10 |
-
|
| 11 |
<style>
|
| 12 |
:root {
|
| 13 |
--bg: #1e1e2e; --panel: #252535; --border: #353550;
|
| 14 |
--accent: #89b4fa; --accent-hover: #74a0f0;
|
| 15 |
--text: #cdd6f4; --muted: #7f849c;
|
| 16 |
-
--err: #f38ba8; --ok: #a6e3a1;
|
| 17 |
}
|
| 18 |
* { box-sizing: border-box; }
|
| 19 |
-
html, body {
|
| 20 |
-
|
|
|
|
| 21 |
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
| 22 |
background: var(--bg); color: var(--text);
|
| 23 |
}
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
padding:
|
| 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 |
-
.seg-btn:hover:not(.active) { color: var(--text); }
|
| 54 |
-
.seg-btn.active { background: var(--accent); color: #11111b; }
|
| 55 |
-
|
| 56 |
-
main { flex: 1; display: flex; min-height: 0; }
|
| 57 |
-
.pane { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
| 58 |
-
.pane-label {
|
| 59 |
-
padding: 6px 12px; font-size: 11px; text-transform: uppercase;
|
| 60 |
-
letter-spacing: .05em; color: var(--muted); background: var(--panel);
|
| 61 |
-
border-bottom: 1px solid var(--border);
|
| 62 |
-
display: flex; align-items: center; gap: 8px;
|
| 63 |
-
}
|
| 64 |
-
.pane-label .badge {
|
| 65 |
-
font-size: 10px; background: var(--border); color: var(--muted);
|
| 66 |
-
padding: 1px 7px; border-radius: 10px; text-transform: none; letter-spacing: 0;
|
| 67 |
-
}
|
| 68 |
-
#problem {
|
| 69 |
-
background: var(--bg); color: var(--text);
|
| 70 |
-
border: 1px solid var(--border); border-radius: 8px;
|
| 71 |
-
padding: 8px 14px; font-size: 16px; font-weight: 700; cursor: pointer;
|
| 72 |
-
text-transform: none; letter-spacing: 0; min-width: 90px;
|
| 73 |
-
}
|
| 74 |
-
#problem:hover { border-color: var(--accent); }
|
| 75 |
-
#problem:focus { outline: none; border-color: var(--accent); }
|
| 76 |
-
|
| 77 |
-
.editor-wrap { flex: 1; min-height: 0; overflow: hidden; }
|
| 78 |
-
.CodeMirror { height: 100% !important; font-size: 14px; font-family: "SF Mono", Menlo, Consolas, monospace; }
|
| 79 |
-
|
| 80 |
-
.divider { width: 1px; background: var(--border); cursor: col-resize; }
|
| 81 |
-
.divider:hover { background: var(--accent); }
|
| 82 |
-
|
| 83 |
-
#summary {
|
| 84 |
-
padding: 8px 16px; font-size: 13px; font-weight: 600;
|
| 85 |
-
border-bottom: 1px solid var(--border); background: var(--panel);
|
| 86 |
-
display: none;
|
| 87 |
-
}
|
| 88 |
-
#summary.pass { color: var(--ok); }
|
| 89 |
-
#summary.fail { color: var(--err); }
|
| 90 |
-
|
| 91 |
-
#output {
|
| 92 |
-
flex: 1; margin: 0; padding: 12px 16px; overflow: auto;
|
| 93 |
-
font-family: "SF Mono", Menlo, Consolas, monospace; font-size: 13px;
|
| 94 |
-
line-height: 1.55; white-space: pre-wrap; word-break: break-word;
|
| 95 |
-
background: #181825;
|
| 96 |
-
}
|
| 97 |
-
#output .err { color: var(--err); }
|
| 98 |
-
#output .ok { color: var(--ok); }
|
| 99 |
-
#output .warn { color: #f9e2af; }
|
| 100 |
-
#output .meta { color: var(--muted); }
|
| 101 |
-
#output img { max-width: 100%; background: #fff; border-radius: 4px; margin: 8px 0; }
|
| 102 |
</style>
|
| 103 |
</head>
|
| 104 |
<body>
|
| 105 |
-
|
| 106 |
-
<
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
</div>
|
| 112 |
-
<button id="run" disabled>▶ Run <span class="kbd">⌘/Ctrl+Enter</span></button>
|
| 113 |
-
<button id="reset" class="ghost">Reset Template</button>
|
| 114 |
-
<span id="status" class="status">Loading runtime…</span>
|
| 115 |
-
</header>
|
| 116 |
-
|
| 117 |
-
<main>
|
| 118 |
-
<div class="pane" id="left">
|
| 119 |
-
<div class="pane-label">
|
| 120 |
-
<select id="problem" title="Select a problem">
|
| 121 |
-
<option value="Q1">Q1</option>
|
| 122 |
-
<option value="Q2">Q2</option>
|
| 123 |
-
</select>
|
| 124 |
-
<span id="leftLabel">Your Code</span>
|
| 125 |
-
<span class="badge">editable</span>
|
| 126 |
-
</div>
|
| 127 |
-
<div class="editor-wrap"><textarea id="code"></textarea></div>
|
| 128 |
-
</div>
|
| 129 |
-
<div class="divider" id="divider"></div>
|
| 130 |
-
<div class="pane" id="right">
|
| 131 |
-
<div class="pane-label"><span id="rightLabel">Output</span> <span class="badge" id="modinfo">blackbox: not loaded</span></div>
|
| 132 |
-
<div id="summary"></div>
|
| 133 |
-
<div id="output"><span class="meta">(Click "Run" once the runtime is ready)</span></div>
|
| 134 |
-
</div>
|
| 135 |
-
</main>
|
| 136 |
-
|
| 137 |
-
<script src="https://cdn.jsdelivr.net/pyodide/v0.26.2/full/pyodide.js"></script>
|
| 138 |
-
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
|
| 139 |
-
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script>
|
| 140 |
|
| 141 |
<script>
|
| 142 |
-
|
| 143 |
-
const
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
// ===== Problems: UI metadata only. The hidden blackbox/oracle live in the worker. =====
|
| 156 |
-
const PROBLEMS = {
|
| 157 |
-
Q1: {
|
| 158 |
-
public: "allocate",
|
| 159 |
-
sig: "allocate(students, rooms, capacity, mode)",
|
| 160 |
-
testTemplate: `# Q1 Room Allocator -- blackbox.allocate(students, rooms, capacity, mode), 5 bugs.
|
| 161 |
-
# TESTS = [ ((args), "expected-from-spec"), ... ], one case per line.
|
| 162 |
-
TESTS = [
|
| 163 |
-
((50, 2, 30, "Lecture"), "SEATED"),
|
| 164 |
-
((200, 5, 25, "Lecture"), "OVERFLOW"),
|
| 165 |
-
((50, 2, 30, "Online"), "INVALID"),
|
| 166 |
-
]
|
| 167 |
-
`,
|
| 168 |
-
},
|
| 169 |
-
Q2: {
|
| 170 |
-
public: "approve",
|
| 171 |
-
sig: "approve(role, fte, weekly_hours, period)",
|
| 172 |
-
testTemplate: `# Q2 Workload Approval -- blackbox.approve(role, fte, weekly_hours, period), 5 bugs.
|
| 173 |
-
# TESTS = [ ((args), "expected-from-spec"), ... ], one case per line.
|
| 174 |
-
TESTS = [
|
| 175 |
-
(("Tutor", 1.0, 5, "Teaching"), "APPROVED"),
|
| 176 |
-
(("Marker", 0.5, 3, "Break"), "APPROVED"),
|
| 177 |
-
(("Coordinator", 1.0, 50, "Teaching"), "DENIED"),
|
| 178 |
-
]
|
| 179 |
-
`,
|
| 180 |
-
},
|
| 181 |
-
};
|
| 182 |
-
|
| 183 |
-
// ===== State + working copies (so switching never loses your edits) =====
|
| 184 |
-
let mode = "test"; // "run" | "test" -- default to Black-Box Test on load
|
| 185 |
-
let prob = "Q1"; // current problem key
|
| 186 |
-
const work = {
|
| 187 |
-
run: RUN_TEMPLATE,
|
| 188 |
-
test: { Q1: PROBLEMS.Q1.testTemplate, Q2: PROBLEMS.Q2.testTemplate },
|
| 189 |
-
};
|
| 190 |
-
const slotTemplate = () => (mode === "run" ? RUN_TEMPLATE : PROBLEMS[prob].testTemplate);
|
| 191 |
-
const saveEditor = () => { if (mode === "run") work.run = editor.getValue(); else work.test[prob] = editor.getValue(); };
|
| 192 |
-
const loadEditor = () => editor.setValue(mode === "run" ? work.run : work.test[prob]);
|
| 193 |
-
|
| 194 |
-
// Pull ONLY the TESTS = [ ... ] list out of whatever the student typed; everything
|
| 195 |
-
// else is ignored (never executed). Balanced-bracket scan, quote-aware.
|
| 196 |
-
function extractTestsLiteral(src) {
|
| 197 |
-
// Anchor to line start so a commented "# TESTS = [ ... ]" line is NOT matched.
|
| 198 |
-
const m = /^[ \t]*TESTS\s*=\s*\[/m.exec(src);
|
| 199 |
-
if (!m) return null;
|
| 200 |
-
const start = src.indexOf("[", m.index);
|
| 201 |
-
let depth = 0, quote = null;
|
| 202 |
-
for (let j = start; j < src.length; j++) {
|
| 203 |
-
const ch = src[j];
|
| 204 |
-
if (quote) { if (ch === quote && src[j - 1] !== "\\") quote = null; continue; }
|
| 205 |
-
if (ch === '"' || ch === "'") { quote = ch; continue; }
|
| 206 |
-
if (ch === "[") depth++;
|
| 207 |
-
else if (ch === "]") { depth--; if (depth === 0) return src.slice(start, j + 1); }
|
| 208 |
-
}
|
| 209 |
-
return null;
|
| 210 |
-
}
|
| 211 |
-
|
| 212 |
-
const output = document.getElementById("output");
|
| 213 |
-
const summary = document.getElementById("summary");
|
| 214 |
-
const statusEl = document.getElementById("status");
|
| 215 |
-
const modinfo = document.getElementById("modinfo");
|
| 216 |
-
const runBtn = document.getElementById("run");
|
| 217 |
-
const resetBtn = document.getElementById("reset");
|
| 218 |
-
const leftLabel = document.getElementById("leftLabel");
|
| 219 |
-
const rightLabel= document.getElementById("rightLabel");
|
| 220 |
-
const modeRunBtn = document.getElementById("mode-run");
|
| 221 |
-
const modeTestBtn = document.getElementById("mode-test");
|
| 222 |
-
const problemSel = document.getElementById("problem");
|
| 223 |
-
|
| 224 |
-
function append(text, cls) {
|
| 225 |
-
const span = document.createElement("span");
|
| 226 |
-
if (cls) span.className = cls;
|
| 227 |
-
span.textContent = text;
|
| 228 |
-
output.appendChild(span);
|
| 229 |
-
output.scrollTop = output.scrollHeight;
|
| 230 |
-
}
|
| 231 |
-
|
| 232 |
-
// ===== Editor =====
|
| 233 |
-
const editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
| 234 |
-
mode: "python", theme: "material-darker",
|
| 235 |
-
lineNumbers: true, indentUnit: 4, tabSize: 4, indentWithTabs: false,
|
| 236 |
-
extraKeys: {
|
| 237 |
-
"Cmd-Enter": run, "Ctrl-Enter": run,
|
| 238 |
-
Tab: (cm) => cm.replaceSelection(" "),
|
| 239 |
-
},
|
| 240 |
-
});
|
| 241 |
-
loadEditor();
|
| 242 |
-
resetBtn.onclick = () => {
|
| 243 |
-
if (mode === "run") work.run = RUN_TEMPLATE; else work.test[prob] = PROBLEMS[prob].testTemplate;
|
| 244 |
-
loadEditor();
|
| 245 |
-
};
|
| 246 |
-
|
| 247 |
-
// ===== Mode switching (Run <-> Black-Box Test) =====
|
| 248 |
-
function applyMode() {
|
| 249 |
-
modeRunBtn.classList.toggle("active", mode === "run");
|
| 250 |
-
modeTestBtn.classList.toggle("active", mode === "test");
|
| 251 |
-
leftLabel.textContent = mode === "test" ? "Your Test Code" : "Your Code";
|
| 252 |
-
rightLabel.textContent = mode === "test" ? "Test Results" : "Output";
|
| 253 |
-
const leftBadge = document.querySelector("#left .badge");
|
| 254 |
-
if (leftBadge) leftBadge.textContent = mode === "test" ? "only TESTS = [...] is read" : "editable";
|
| 255 |
-
modinfo.style.display = mode === "test" ? "" : "none";
|
| 256 |
-
summary.style.display = "none";
|
| 257 |
-
runBtn.innerHTML = (mode === "test" ? "▶ Run Tests " : "▶ Run ")
|
| 258 |
-
+ '<span class="kbd">⌘/Ctrl+Enter</span>';
|
| 259 |
-
}
|
| 260 |
-
function switchMode(next) {
|
| 261 |
-
if (next === mode) return;
|
| 262 |
-
saveEditor();
|
| 263 |
-
mode = next;
|
| 264 |
-
applyMode();
|
| 265 |
-
loadEditor();
|
| 266 |
-
}
|
| 267 |
-
modeRunBtn.onclick = () => switchMode("run");
|
| 268 |
-
modeTestBtn.onclick = () => switchMode("test");
|
| 269 |
-
|
| 270 |
-
// ===== Problem switching (Q1 / Q2) =====
|
| 271 |
-
problemSel.onchange = async () => {
|
| 272 |
-
saveEditor();
|
| 273 |
-
prob = problemSel.value;
|
| 274 |
-
loadEditor(); // show this problem's test code
|
| 275 |
-
await loadProblem(prob); // swap the hidden blackbox module
|
| 276 |
-
};
|
| 277 |
-
|
| 278 |
-
applyMode();
|
| 279 |
-
|
| 280 |
-
// ===== Grader Web Worker =====
|
| 281 |
-
// The answer key (oracle / bug definitions / reasons) lives in a SEPARATE Pyodide
|
| 282 |
-
// running inside grader.worker.js, on its own thread with its own memory. Student
|
| 283 |
-
// code runs in the main-thread Pyodide below and cannot reach into the worker:
|
| 284 |
-
// gc.get_objects(), closure reflection and print(globals()) only see this interpreter.
|
| 285 |
-
let grader = null, graderReady = false, mainReady = false;
|
| 286 |
-
let __msgId = 0;
|
| 287 |
-
const __pending = new Map();
|
| 288 |
-
|
| 289 |
-
function startGrader() {
|
| 290 |
-
grader = new Worker("grader.worker.js?v=" + Date.now()); // bust browser cache of the worker
|
| 291 |
-
grader.onmessage = (e) => {
|
| 292 |
-
const d = e.data || {};
|
| 293 |
-
if (d.type === "ready") { graderReady = true; maybeReady(); return; }
|
| 294 |
-
if (d.type === "fatal") { append("Grader failed to load: " + d.error + "\n", "err"); return; }
|
| 295 |
-
const p = __pending.get(d.id);
|
| 296 |
-
if (!p) return;
|
| 297 |
-
__pending.delete(d.id);
|
| 298 |
-
if (d.ok) p.resolve(JSON.parse(d.report)); else p.reject(new Error(d.error));
|
| 299 |
-
};
|
| 300 |
-
grader.onerror = (e) => append("Grader worker error: " + (e.message || e) + "\n", "err");
|
| 301 |
-
}
|
| 302 |
-
|
| 303 |
-
// Send a grading request to the worker and await its report.
|
| 304 |
-
function gradeViaWorker(problem, source, testsJson) {
|
| 305 |
-
return new Promise((resolve, reject) => {
|
| 306 |
-
const id = ++__msgId;
|
| 307 |
-
__pending.set(id, { resolve, reject });
|
| 308 |
-
grader.postMessage({ id, problem, source, tests: testsJson });
|
| 309 |
});
|
| 310 |
-
}
|
| 311 |
-
|
| 312 |
-
function maybeReady() {
|
| 313 |
-
if (mainReady && graderReady) {
|
| 314 |
-
statusEl.textContent = "\u2713 Ready";
|
| 315 |
-
statusEl.className = "status ready";
|
| 316 |
-
runBtn.disabled = false;
|
| 317 |
-
}
|
| 318 |
-
}
|
| 319 |
-
|
| 320 |
-
// ===== Load Pyodide (main thread runs student code only -- no answer key here) =====
|
| 321 |
-
let pyodide;
|
| 322 |
-
|
| 323 |
-
// Problem switch: just update the label. The worker loads the .dat lazily on first grade.
|
| 324 |
-
async function loadProblem(key) {
|
| 325 |
-
modinfo.textContent = key + " \u00b7 " + PROBLEMS[key].sig;
|
| 326 |
-
}
|
| 327 |
-
|
| 328 |
-
startGrader();
|
| 329 |
-
(async () => {
|
| 330 |
-
try {
|
| 331 |
-
pyodide = await loadPyodide({
|
| 332 |
-
stdout: (s) => append(s + "\n"),
|
| 333 |
-
stderr: (s) => append(s + "\n", "err"),
|
| 334 |
-
});
|
| 335 |
-
await loadProblem(prob);
|
| 336 |
-
mainReady = true;
|
| 337 |
-
maybeReady();
|
| 338 |
-
} catch (e) {
|
| 339 |
-
statusEl.textContent = "Failed to load";
|
| 340 |
-
statusEl.className = "status error";
|
| 341 |
-
append("Failed to load runtime: " + e + "\n", "err");
|
| 342 |
-
}
|
| 343 |
-
})();
|
| 344 |
-
|
| 345 |
-
// ===== Run the student's tests =====
|
| 346 |
-
async function run() {
|
| 347 |
-
if (!pyodide || runBtn.disabled) return;
|
| 348 |
-
runBtn.disabled = true;
|
| 349 |
-
output.innerHTML = "";
|
| 350 |
-
summary.style.display = "none";
|
| 351 |
-
|
| 352 |
-
const code = editor.getValue();
|
| 353 |
-
try {
|
| 354 |
-
if (mode === "test") {
|
| 355 |
-
// Run the student's code in the (clean) main interpreter to define TESTS,
|
| 356 |
-
// then send ONLY the TESTS data to the worker. The worker holds the answer
|
| 357 |
-
// key in its own interpreter; nothing sensitive lives in this one.
|
| 358 |
-
// Regex out the TESTS = [ ... ] block and evaluate ONLY that literal. Student
|
| 359 |
-
// code is NEVER executed; anything outside the list is ignored. literal_eval
|
| 360 |
-
// accepts numbers/strings/tuples/lists/bools/None and rejects calls/names.
|
| 361 |
-
const lit = extractTestsLiteral(code);
|
| 362 |
-
if (!lit) {
|
| 363 |
-
append('\nNo "TESTS = [ ... ]" found. Define your test cases as a list, e.g.\nTESTS = [ ((50, 2, 30, "Lecture"), "SEATED") ]\n', "err");
|
| 364 |
-
return;
|
| 365 |
-
}
|
| 366 |
-
pyodide.globals.set("__lit", lit);
|
| 367 |
-
let testsJson;
|
| 368 |
-
try {
|
| 369 |
-
testsJson = pyodide.runPython("import ast, json\njson.dumps(ast.literal_eval(__lit))");
|
| 370 |
-
} catch (se) {
|
| 371 |
-
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");
|
| 372 |
-
return;
|
| 373 |
-
}
|
| 374 |
-
const rep = await gradeViaWorker(prob, code, testsJson);
|
| 375 |
-
renderReport(rep);
|
| 376 |
-
} else {
|
| 377 |
-
// Plain run: just execute and show output, no grading
|
| 378 |
-
const result = await pyodide.runPythonAsync(code);
|
| 379 |
-
renderMatplotlib();
|
| 380 |
-
if (result !== undefined && result !== null) append(String(result) + "\n", "meta");
|
| 381 |
-
}
|
| 382 |
-
} catch (e) {
|
| 383 |
-
append("\nExecution stopped:\n" + cleanError(e.message || String(e)) + "\n", "err");
|
| 384 |
-
} finally {
|
| 385 |
-
runBtn.disabled = false;
|
| 386 |
-
}
|
| 387 |
-
}
|
| 388 |
-
runBtn.onclick = run;
|
| 389 |
-
|
| 390 |
-
// Render the grading report: one line per test case, a "Bug caught at line N" for
|
| 391 |
-
// each newly-detected bug, and a summary of how many distinct bugs were caught.
|
| 392 |
-
function renderReport(rep) {
|
| 393 |
-
if (!rep.ok) {
|
| 394 |
-
summary.style.display = "none";
|
| 395 |
-
append((rep.error || "Invalid test setup.") + "\n", "err");
|
| 396 |
-
return;
|
| 397 |
-
}
|
| 398 |
-
for (const r of rep.rows) {
|
| 399 |
-
const at = r.line ? "line " + r.line : "(unknown line)";
|
| 400 |
-
if (r.status === "bug") {
|
| 401 |
-
append(`✓ Bug #${r.num}/${r.total} caught at ${at}: ${r.reason}\n`, "ok");
|
| 402 |
-
append(` input ${r.argstr} → program returned ${r.actual}, spec expects ${r.expected}\n`, "meta");
|
| 403 |
-
} else if (r.status === "combo") {
|
| 404 |
-
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");
|
| 405 |
-
} else if (r.status === "dup") {
|
| 406 |
-
append(`· ${at}: catches bug #${r.num} again\n`, "meta");
|
| 407 |
-
} else if (r.status === "invalid") {
|
| 408 |
-
append(`⚠ ${at}: your expected ${r.expected} does NOT match the spec — this test does not count (program returned ${r.actual})\n`, "warn");
|
| 409 |
-
} else if (r.status === "ok") {
|
| 410 |
-
append(`· ${at}: program matches the spec (${r.actual}) — no bug here\n`, "meta");
|
| 411 |
-
} else if (r.status === "malformed") {
|
| 412 |
-
append(`✗ ${at}: malformed test case ${r.raw} — expected ((args), expected)\n`, "err");
|
| 413 |
-
} else if (r.status === "error") {
|
| 414 |
-
append(`✗ ${at}: error calling the program on ${r.argstr}: ${r.msg}\n`, "err");
|
| 415 |
-
}
|
| 416 |
-
}
|
| 417 |
-
const all = rep.caughtCount === rep.totalBugs;
|
| 418 |
-
summary.style.display = "block";
|
| 419 |
-
summary.className = all ? "pass" : "";
|
| 420 |
-
summary.style.color = all ? "" : "var(--accent)";
|
| 421 |
-
summary.textContent = all
|
| 422 |
-
? `🐞 Caught all ${rep.totalBugs}/${rep.totalBugs} bugs`
|
| 423 |
-
: `🐞 Caught ${rep.caughtCount}/${rep.totalBugs} bugs (${rep.totalBugs - rep.caughtCount} still hidden)`;
|
| 424 |
-
}
|
| 425 |
-
|
| 426 |
-
// Strip internal file paths from tracebacks to avoid leakage/noise
|
| 427 |
-
function cleanError(msg) {
|
| 428 |
-
return msg
|
| 429 |
-
.split("\n")
|
| 430 |
-
.filter((l) => !l.includes("/lib/python") && !l.includes("pyodide"))
|
| 431 |
-
.join("\n")
|
| 432 |
-
.trim();
|
| 433 |
-
}
|
| 434 |
-
|
| 435 |
-
function renderMatplotlib() {
|
| 436 |
-
try {
|
| 437 |
-
const has = pyodide.runPython(`"matplotlib" in __import__("sys").modules`);
|
| 438 |
-
if (!has) return;
|
| 439 |
-
const b64 = pyodide.runPython(`
|
| 440 |
-
import io, base64
|
| 441 |
-
import matplotlib.pyplot as _plt
|
| 442 |
-
_imgs = []
|
| 443 |
-
for _n in _plt.get_fignums():
|
| 444 |
-
_buf = io.BytesIO()
|
| 445 |
-
_plt.figure(_n).savefig(_buf, format="png", dpi=110, bbox_inches="tight")
|
| 446 |
-
_imgs.append(base64.b64encode(_buf.getvalue()).decode())
|
| 447 |
-
_plt.close("all")
|
| 448 |
-
"\\n".join(_imgs)
|
| 449 |
-
`);
|
| 450 |
-
for (const data of (b64 || "").split("\n")) {
|
| 451 |
-
if (!data) continue;
|
| 452 |
-
const img = document.createElement("img");
|
| 453 |
-
img.src = "data:image/png;base64," + data;
|
| 454 |
-
output.appendChild(img);
|
| 455 |
-
}
|
| 456 |
-
} catch (_) {}
|
| 457 |
-
}
|
| 458 |
-
|
| 459 |
-
// ===== Draggable divider =====
|
| 460 |
-
const divider = document.getElementById("divider");
|
| 461 |
-
const left = document.getElementById("left");
|
| 462 |
-
const mainEl = document.querySelector("main");
|
| 463 |
-
let dragging = false;
|
| 464 |
-
divider.addEventListener("mousedown", () => (dragging = true));
|
| 465 |
-
window.addEventListener("mouseup", () => (dragging = false));
|
| 466 |
-
window.addEventListener("mousemove", (e) => {
|
| 467 |
-
if (!dragging) return;
|
| 468 |
-
const rect = mainEl.getBoundingClientRect();
|
| 469 |
-
const pct = ((e.clientX - rect.left) / rect.width) * 100;
|
| 470 |
-
if (pct > 15 && pct < 85) left.style.flex = "0 0 " + pct + "%";
|
| 471 |
-
});
|
| 472 |
</script>
|
| 473 |
</body>
|
| 474 |
</html>
|
|
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>Software Testing — Playground</title>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
<style>
|
| 8 |
:root {
|
| 9 |
--bg: #1e1e2e; --panel: #252535; --border: #353550;
|
| 10 |
--accent: #89b4fa; --accent-hover: #74a0f0;
|
| 11 |
--text: #cdd6f4; --muted: #7f849c;
|
|
|
|
| 12 |
}
|
| 13 |
* { box-sizing: border-box; }
|
| 14 |
+
html, body { margin: 0; height: 100%; }
|
| 15 |
+
body {
|
| 16 |
+
display: flex; height: 100vh; overflow: hidden;
|
| 17 |
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
| 18 |
background: var(--bg); color: var(--text);
|
| 19 |
}
|
| 20 |
+
/* ===== Left sidebar ===== */
|
| 21 |
+
nav.sidebar {
|
| 22 |
+
width: 210px; flex: 0 0 210px; background: var(--panel);
|
| 23 |
+
border-right: 1px solid var(--border);
|
| 24 |
+
display: flex; flex-direction: column; padding: 14px 10px; gap: 4px;
|
| 25 |
+
}
|
| 26 |
+
.sidebar .brand {
|
| 27 |
+
font-size: 13px; font-weight: 700; color: var(--text);
|
| 28 |
+
padding: 6px 10px 14px; letter-spacing: .02em;
|
| 29 |
+
}
|
| 30 |
+
.sidebar .brand small { display: block; color: var(--muted); font-weight: 500; font-size: 11px; margin-top: 3px; }
|
| 31 |
+
.sidebar .nav-label {
|
| 32 |
+
font-size: 10px; text-transform: uppercase; letter-spacing: .08em;
|
| 33 |
+
color: var(--muted); padding: 10px 10px 4px;
|
| 34 |
+
}
|
| 35 |
+
.sidebar button.item {
|
| 36 |
+
display: block; width: 100%; text-align: left;
|
| 37 |
+
background: transparent; color: var(--text); border: none;
|
| 38 |
+
padding: 9px 12px; border-radius: 7px; font-size: 13px; font-weight: 600;
|
| 39 |
+
cursor: pointer; transition: background .12s, color .12s;
|
| 40 |
+
}
|
| 41 |
+
.sidebar button.item:hover { background: var(--border); }
|
| 42 |
+
.sidebar button.item.active { background: var(--accent); color: #11111b; }
|
| 43 |
+
.sidebar button.item .sub { display: block; font-size: 11px; font-weight: 500; opacity: .8; margin-top: 2px; }
|
| 44 |
+
.sidebar .spacer { flex: 1; }
|
| 45 |
+
.sidebar .foot { font-size: 10px; color: var(--muted); padding: 8px 10px; line-height: 1.5; }
|
| 46 |
+
/* ===== Content frame ===== */
|
| 47 |
+
.content { flex: 1; min-width: 0; }
|
| 48 |
+
.content iframe { width: 100%; height: 100%; border: none; display: block; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
</style>
|
| 50 |
</head>
|
| 51 |
<body>
|
| 52 |
+
<nav class="sidebar">
|
| 53 |
+
<div class="brand">Software Testing<small>UNSW · Playground</small></div>
|
| 54 |
+
<div class="nav-label">Assignments</div>
|
| 55 |
+
<button class="item active" data-src="assignment1.html">
|
| 56 |
+
Assignment 1
|
| 57 |
+
<span class="sub">Black-box testing playground</span>
|
| 58 |
+
</button>
|
| 59 |
+
<button class="item" data-src="assignment2.html">
|
| 60 |
+
Assignment 2
|
| 61 |
+
<span class="sub">Decision tables · CFG · loops · mutation</span>
|
| 62 |
+
</button>
|
| 63 |
+
<div class="spacer"></div>
|
| 64 |
+
<div class="foot">Pick an assignment on the left.<br>Assignment 2 has an interactive Q4 and a JSON export.</div>
|
| 65 |
+
</nav>
|
| 66 |
+
<div class="content">
|
| 67 |
+
<iframe id="frame" src="assignment1.html" title="assignment"></iframe>
|
| 68 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
<script>
|
| 71 |
+
const frame = document.getElementById("frame");
|
| 72 |
+
const items = [...document.querySelectorAll(".sidebar button.item")];
|
| 73 |
+
// restore last-selected assignment
|
| 74 |
+
const last = localStorage.getItem("st_last_assignment");
|
| 75 |
+
if (last) {
|
| 76 |
+
const btn = items.find(b => b.dataset.src === last);
|
| 77 |
+
if (btn) { items.forEach(i => i.classList.remove("active")); btn.classList.add("active"); frame.src = last; }
|
| 78 |
+
}
|
| 79 |
+
items.forEach(btn => btn.onclick = () => {
|
| 80 |
+
items.forEach(i => i.classList.remove("active"));
|
| 81 |
+
btn.classList.add("active");
|
| 82 |
+
frame.src = btn.dataset.src;
|
| 83 |
+
localStorage.setItem("st_last_assignment", btn.dataset.src);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ===========================================================================
|
| 2 |
+
// Cloudflare Worker — hidden "blackbox" backend.
|
| 3 |
+
//
|
| 4 |
+
// The real implementations live ONLY here, on Cloudflare's edge. They are
|
| 5 |
+
// never sent to the browser, so students cannot download or read them.
|
| 6 |
+
// The frontend only sends inputs and receives outputs (black-box RPC).
|
| 7 |
+
//
|
| 8 |
+
// Deploy via the Cloudflare dashboard: Workers & Pages -> Create -> Worker
|
| 9 |
+
// -> paste this file -> Deploy. Then copy the *.workers.dev URL.
|
| 10 |
+
// ===========================================================================
|
| 11 |
+
|
| 12 |
+
// ---- Hidden problem implementations (keep behaviour matching the originals) ----
|
| 13 |
+
const SOLUTIONS = {
|
| 14 |
+
Q1: {
|
| 15 |
+
grade(score) {
|
| 16 |
+
if (score >= 85) return "HD";
|
| 17 |
+
if (score >= 75) return "DN";
|
| 18 |
+
if (score >= 65) return "CR";
|
| 19 |
+
if (score >= 50) return "PS";
|
| 20 |
+
return "FL";
|
| 21 |
+
},
|
| 22 |
+
clamp(x, lo, hi) {
|
| 23 |
+
return Math.max(lo, Math.min(x, hi));
|
| 24 |
+
},
|
| 25 |
+
fizzbuzz(n) {
|
| 26 |
+
if (n % 15 === 0) return "FizzBuzz";
|
| 27 |
+
if (n % 3 === 0) return "Fizz";
|
| 28 |
+
if (n % 5 === 0) return "Buzz";
|
| 29 |
+
return String(n);
|
| 30 |
+
},
|
| 31 |
+
},
|
| 32 |
+
Q2: {
|
| 33 |
+
is_palindrome(s) {
|
| 34 |
+
const c = [...String(s).toLowerCase()].filter((ch) => /[a-z0-9]/.test(ch)).join("");
|
| 35 |
+
return c === [...c].reverse().join("");
|
| 36 |
+
},
|
| 37 |
+
count_vowels(s) {
|
| 38 |
+
return [...String(s).toLowerCase()].filter((ch) => "aeiou".includes(ch)).length;
|
| 39 |
+
},
|
| 40 |
+
reverse_words(s) {
|
| 41 |
+
const parts = String(s).trim().split(/\s+/).filter(Boolean);
|
| 42 |
+
return parts.reverse().join(" ");
|
| 43 |
+
},
|
| 44 |
+
},
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
const CORS = {
|
| 48 |
+
"Access-Control-Allow-Origin": "*",
|
| 49 |
+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
| 50 |
+
"Access-Control-Allow-Headers": "Content-Type",
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
function json(obj, status = 200) {
|
| 54 |
+
return new Response(JSON.stringify(obj), {
|
| 55 |
+
status,
|
| 56 |
+
headers: { "Content-Type": "application/json", ...CORS },
|
| 57 |
+
});
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
export default {
|
| 61 |
+
async fetch(request) {
|
| 62 |
+
if (request.method === "OPTIONS") return new Response(null, { headers: CORS });
|
| 63 |
+
|
| 64 |
+
const url = new URL(request.url);
|
| 65 |
+
const problem = url.searchParams.get("problem");
|
| 66 |
+
const func = url.searchParams.get("func");
|
| 67 |
+
|
| 68 |
+
// Health check / root
|
| 69 |
+
if (!problem) {
|
| 70 |
+
return json({ ok: true, problems: Object.keys(SOLUTIONS) });
|
| 71 |
+
}
|
| 72 |
+
const impl = SOLUTIONS[problem];
|
| 73 |
+
if (!impl) return json({ error: `unknown problem: ${problem}` }, 404);
|
| 74 |
+
|
| 75 |
+
// Metadata: list the callable function names for a problem (names are NOT secret)
|
| 76 |
+
if (!func) {
|
| 77 |
+
return json({ problem, functions: Object.keys(impl) });
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
// A black-box call: run the hidden function with the given args
|
| 81 |
+
const fn = impl[func];
|
| 82 |
+
if (typeof fn !== "function") {
|
| 83 |
+
return json({ error: `unknown function: ${problem}.${func}` }, 404);
|
| 84 |
+
}
|
| 85 |
+
let args;
|
| 86 |
+
try {
|
| 87 |
+
args = JSON.parse(url.searchParams.get("args") || "[]");
|
| 88 |
+
if (!Array.isArray(args)) throw new Error("args must be a JSON array");
|
| 89 |
+
} catch (e) {
|
| 90 |
+
return json({ error: "bad args: " + e.message }, 400);
|
| 91 |
+
}
|
| 92 |
+
try {
|
| 93 |
+
const result = fn(...args);
|
| 94 |
+
return json({ result });
|
| 95 |
+
} catch (e) {
|
| 96 |
+
return json({ error: String(e && e.message || e) }, 400);
|
| 97 |
+
}
|
| 98 |
+
},
|
| 99 |
+
};
|