sh1k4ku commited on
Commit
443f404
·
verified ·
1 Parent(s): 2daf171

Add Assignment 3 (Q1-Q4 + Q5 coverage-guided fuzzing); relocate all hidden-answer source outside the deployed tree

Browse files
.gitattributes CHANGED
@@ -37,3 +37,4 @@ 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
 
 
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
40
+ ASSIGNMENT-1-desc.pdf filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # 隐藏实现的明文源码已经移到 T2_UNSW 目录外面 (../T2_UNSW_solution/),
2
+ # 因为整个 T2_UNSW 是当静态站点整体部署的,放在里面即使 gitignore 了
3
+ # 也挡不住被当成静态文件直接访问到。不要把 _solution/ 移回这里。
4
+ __pycache__/
ASSIGNMENT-1-desc.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e43cd4981050a6a432d0d8fd6d09e147169b5b581bb6081549b12939f8a0ab25
3
+ size 216863
assignment3.html ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 3 — 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
+ h3 { font-size:14px; color:var(--accent); margin:18px 0 6px; }
25
+ p { margin:8px 0; }
26
+ code, .mono { font-family:"SF Mono",Menlo,Consolas,monospace; }
27
+ pre { background:#181825; border:1px solid var(--border); border-radius:8px; padding:12px 14px; overflow:auto; font-size:13px; }
28
+ .muted { color:var(--muted); }
29
+ table.spec { border-collapse:collapse; font-size:13px; margin:8px 0; }
30
+ table.spec th, table.spec td { border:1px solid var(--border); padding:5px 10px; text-align:left; }
31
+ table.spec th { background:var(--panel); }
32
+ a { color:var(--accent); }
33
+
34
+ /* option card with radio/checkbox */
35
+ .opt {
36
+ border:1px solid var(--border); border-radius:10px; padding:10px 14px; margin:10px 0;
37
+ background:var(--card); transition:border-color .12s, background .12s;
38
+ }
39
+ .opt.sel { border-color:var(--accent); background:#262a3f; }
40
+ .opt-head { display:flex; align-items:center; gap:10px; cursor:pointer; font-weight:600; }
41
+ .opt-head input { width:16px; height:16px; accent-color:var(--accent); cursor:pointer; }
42
+ .opt-body { margin-top:8px; overflow:auto; }
43
+ .opt-body pre { margin:0; }
44
+
45
+ /* fill-in blanks */
46
+ input.blank {
47
+ width:220px; text-align:center; background:#181825; color:var(--ok);
48
+ border:1px solid var(--border); border-radius:5px; padding:2px 6px;
49
+ font-family:"SF Mono",Menlo,Consolas,monospace; font-size:13px; font-weight:600;
50
+ }
51
+ input.blank:focus { outline:none; border-color:var(--accent); }
52
+ input.blank.short { width:70px; }
53
+ input.txt {
54
+ background:#181825; color:var(--text); border:1px solid var(--border);
55
+ border-radius:6px; padding:7px 10px; font-size:13px;
56
+ font-family:"SF Mono",Menlo,Consolas,monospace;
57
+ }
58
+ input.txt:focus { outline:none; border-color:var(--accent); }
59
+
60
+ button {
61
+ background:var(--accent); color:#11111b; border:none; padding:8px 16px;
62
+ border-radius:7px; font-size:13px; font-weight:700; cursor:pointer; transition:background .15s;
63
+ }
64
+ button:hover:not(:disabled){ background:var(--accent-hover); }
65
+ button:disabled { opacity:.5; cursor:not-allowed; }
66
+ button.ghost { background:transparent; color:var(--muted); border:1px solid var(--border); }
67
+ button.ghost:hover:not(:disabled){ color:var(--text); }
68
+
69
+ /* Q4.2 code editor */
70
+ .pg { border:1px solid var(--border); border-radius:10px; overflow:hidden; margin:12px 0; background:var(--card); }
71
+ .pg-head { display:flex; align-items:center; gap:10px; padding:8px 12px; background:var(--panel); border-bottom:1px solid var(--border); flex-wrap:wrap; }
72
+ .CodeMirror { height:auto; min-height:170px; font-size:13px; font-family:"SF Mono",Menlo,Consolas,monospace; }
73
+
74
+ /* sticky export bar */
75
+ .exportbar {
76
+ position:fixed; left:0; right:0; bottom:0; background:var(--panel);
77
+ border-top:1px solid var(--border); padding:10px 28px;
78
+ display:flex; align-items:center; gap:14px; z-index:10;
79
+ }
80
+ .exportbar .sid { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--muted); }
81
+ .exportbar .spacer { flex:1; }
82
+ .toast { font-size:12px; color:var(--ok); }
83
+
84
+ /* ===== left vertical tabs (Ant style) ===== */
85
+ .layout { display:flex; gap:20px; align-items:flex-start; margin-top:16px; }
86
+ .tabs { flex:0 0 190px; display:flex; flex-direction:column; gap:5px;
87
+ position:sticky; top:16px; }
88
+ .tabs button { background:transparent; color:var(--muted); border:none;
89
+ border-left:3px solid transparent; border-radius:8px;
90
+ padding:11px 14px; font-size:14px; font-weight:600; cursor:pointer;
91
+ text-align:left; width:100%; white-space:nowrap;
92
+ transition:color .15s, background .15s, border-color .15s; }
93
+ .tabs button:hover:not(:disabled) { background:var(--panel); color:var(--text); }
94
+ .tabs button.active { color:var(--accent); background:var(--card);
95
+ border-left-color:var(--accent); border-radius:0 8px 8px 0; }
96
+ .panes { flex:1; min-width:0; }
97
+ .pane { display:none; }
98
+ .pane.active { display:block; animation:tabfade .22s ease;
99
+ background:var(--panel); border:1px solid var(--border);
100
+ border-radius:12px; padding:20px 24px; }
101
+ @keyframes tabfade { from{opacity:0; transform:translateY(4px)} to{opacity:1; transform:none} }
102
+ .pane h2:first-child { margin-top:0; border-top:none; padding-top:0; }
103
+ </style>
104
+ </head>
105
+ <body>
106
+ <div class="wrap">
107
+ <h1>Assignment 3: Software Testing</h1>
108
+ <p class="muted">Answer all questions below — one tab per question. Your answers auto-save in this browser; export them as JSON at the bottom when done.</p>
109
+
110
+ <div class="layout">
111
+ <div class="tabs" id="tabbar">
112
+ <button data-tab="q1" class="active">Q1 · Test Scaffolding</button>
113
+ <button data-tab="q2">Q2 · Combinatorial</button>
114
+ <button data-tab="q3">Q3 · Integration</button>
115
+ <button data-tab="q4">Q4 · Metamorphic &amp; Mutation</button>
116
+ <button data-tab="q5">Q5 · Coverage Fuzzing</button>
117
+ </div>
118
+ <div class="panes">
119
+
120
+ <!-- ============ Q1 ============ -->
121
+ <section class="pane active" data-tab="q1">
122
+ <h2>Q1 Test Scaffolding Concepts</h2>
123
+ <p class="muted">Multiple answers may apply unless otherwise stated.</p>
124
+
125
+ <h3>Q1.1</h3>
126
+ <p>Which of the following may be used as test scaffolding?</p>
127
+ <div id="q11opts"></div>
128
+
129
+ <h3>Q1.2</h3>
130
+ <p>Consider the following test scaffolding code.</p>
131
+ <pre id="q12code"></pre>
132
+ <p>The real data source has not yet been integrated. During the test, <code>FixedDataSource</code> supplies predefined records to <code>ReportGenerator</code>.</p>
133
+ <p>How should <code>FixedDataSource</code> be classified?</p>
134
+ <div id="q12opts"></div>
135
+ </section>
136
+
137
+ <!-- ============ Q2 ============ -->
138
+ <section class="pane" data-tab="q2">
139
+ <h2>Q2 Combinatorial Testing</h2>
140
+ <p>A web application supports the following parameters:</p>
141
+ <pre>Browser: Chrome, Firefox
142
+ Authentication: Password, SSO
143
+ Region: AU, US</pre>
144
+ <p>Exactly one option is correct for each question.</p>
145
+
146
+ <h3>Q2.1 Selecting a Pairwise Covering Array</h3>
147
+ <p>Which option is a smallest pairwise covering array?</p>
148
+ <div id="q21opts"></div>
149
+
150
+ <h3>Q2.2 Increasing the Interaction Strength</h3>
151
+ <p>If the required interaction strength is increased from pairwise testing to three-way testing, how many tests are required to cover every combination of the three parameters?</p>
152
+ <div id="q22opts"></div>
153
+ </section>
154
+
155
+ <!-- ============ Q3 ============ -->
156
+ <section class="pane" data-tab="q3">
157
+ <h2>Q3 Integration Testing</h2>
158
+ <p>Consider a system with the following dependencies:</p>
159
+ <pre>CheckoutController
160
+ |
161
+ v
162
+ OrderService
163
+ | |
164
+ v v
165
+ InventoryService PaymentGateway</pre>
166
+ <p>Fill in the blanks.</p>
167
+ <div id="q3block" style="line-height:2.2"></div>
168
+ </section>
169
+
170
+ <!-- ============ Q4 ============ -->
171
+ <section class="pane" data-tab="q4">
172
+ <h2>Q4 Metamorphic Oracle and Mutation Testing</h2>
173
+ <p>Consider the following program.</p>
174
+ <pre id="q4prog"></pre>
175
+
176
+ <p>Initial test suite:</p>
177
+ <pre id="q4tests"></pre>
178
+
179
+ <p>Assume that none of the following mutants is equivalent to the original program.</p>
180
+ <table class="spec">
181
+ <tr><th>Mutant</th><th>Change</th></tr>
182
+ <tr><td>M1</td><td><code>hours &gt;= 8</code> &rarr; <code>hours &gt; 8</code></td></tr>
183
+ <tr><td>M2</td><td><code>fee = 14</code> &rarr; <code>fee = 15</code></td></tr>
184
+ <tr><td>M3</td><td><code>if weekend</code> &rarr; <code>if not weekend</code></td></tr>
185
+ <tr><td>M4</td><td><code>fee -= 2</code> &rarr; <code>fee -= 1</code></td></tr>
186
+ </table>
187
+
188
+ <h3>Q4.1 Mutant Status</h3>
189
+ <p>For each mutant, write <code>Killed</code> or <code>Survived</code> under the initial test suite.</p>
190
+ <div id="q41block" style="line-height:2.2"></div>
191
+
192
+ <h3>Q4.2 Metamorphic Test Oracle</h3>
193
+ <p>For any <code>hours &gt;= 8</code> and positive integer <code>increase</code>, increasing the parking duration should not change the parking fee. The values of <code>weekend</code> and <code>member</code> must remain unchanged.</p>
194
+ <p>Complete the metamorphic oracle. It may call <code>parking_fee</code> exactly twice and must not directly assert a particular fee value.</p>
195
+ <div class="pg">
196
+ <div class="pg-head"><b>Your answer</b></div>
197
+ <textarea id="q42code"></textarea>
198
+ </div>
199
+
200
+ <h3>Q4.3 Mutation Score</h3>
201
+ <p>Compute the mutation score of the initial test suite.</p>
202
+ <div id="q43block" style="line-height:2.2"></div>
203
+
204
+ <h3>Q4.4 Improving the Test Suite</h3>
205
+ <p>Give one source input and its metamorphic follow-up that kill every mutant surviving the initial test suite.</p>
206
+ <div id="q44block" style="line-height:2.2"></div>
207
+ <p>Then write the corresponding direct regression test.</p>
208
+ <div id="q44assert" style="line-height:2.2"></div>
209
+ </section>
210
+
211
+ <!-- ============ Q5 ============ -->
212
+ <section class="pane" data-tab="q5" style="padding:0;overflow:hidden">
213
+ <iframe src="coverage_fuzzing/index.html" title="Q5 Coverage-Guided Fuzzing"
214
+ style="width:100%;height:1500px;border:0;display:block;border-radius:12px"></iframe>
215
+ </section>
216
+
217
+ </div><!-- /.panes -->
218
+ </div><!-- /.layout -->
219
+ </div>
220
+
221
+ <!-- ============ sticky export bar ============ -->
222
+ <div class="exportbar">
223
+ <div class="sid">Student ID <input class="txt" id="studentId" placeholder="z1234567" style="width:130px"></div>
224
+ <div class="spacer"></div>
225
+ <span class="toast" id="toast"></span>
226
+ <button class="ghost" id="clearBtn">Clear saved</button>
227
+ <button class="ghost" id="copyBtn">Copy JSON</button>
228
+ <button id="exportBtn">⤓ Export JSON</button>
229
+ </div>
230
+
231
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
232
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script>
233
+ <script>
234
+ const answers = { q11:[], q12:null, q21:null, q22:null, q3:{}, q41:{}, q43:{}, q44:{}, q44assert:{} };
235
+
236
+ function buildChoice(host, name, items, onSel){
237
+ host.innerHTML = "";
238
+ for (const it of items){
239
+ const card = document.createElement("div"); card.className = "opt";
240
+ card.innerHTML = `<label class="opt-head"><input type="radio" name="${name}" value="${it.val}"><span>${it.label}</span></label>${it.body ? `<div class="opt-body">${it.body}</div>` : ""}`;
241
+ const radio = card.querySelector("input");
242
+ radio.onchange = () => {
243
+ [...host.querySelectorAll(".opt")].forEach(o=>o.classList.remove("sel"));
244
+ card.classList.add("sel"); onSel(it.val);
245
+ };
246
+ host.appendChild(card);
247
+ }
248
+ }
249
+ function buildMulti(host, name, items, arr, onChange){
250
+ host.innerHTML = "";
251
+ for (const it of items){
252
+ const card = document.createElement("div"); card.className = "opt";
253
+ card.innerHTML = `<label class="opt-head"><input type="checkbox" name="${name}" value="${it.val}"><span>${it.label}</span></label>`;
254
+ const cb = card.querySelector("input");
255
+ cb.onchange = () => {
256
+ card.classList.toggle("sel", cb.checked);
257
+ const i = arr.indexOf(it.val);
258
+ if (cb.checked && i === -1) arr.push(it.val);
259
+ if (!cb.checked && i !== -1) arr.splice(i,1);
260
+ onChange();
261
+ };
262
+ host.appendChild(card);
263
+ }
264
+ }
265
+
266
+ // ============ Q1.1 (multi-select) ============
267
+ buildMulti(document.getElementById("q11opts"), "q11", [
268
+ {val:"a", label:"a. A production database containing real customer data"},
269
+ {val:"b", label:"b. A driver that invokes a program unit whose caller is not yet available"},
270
+ {val:"c", label:"c. A stub that substitutes for unavailable system functionality"},
271
+ {val:"d", label:"d. Code that must remain permanently in the deployed product"},
272
+ ], answers.q11, saveSession);
273
+
274
+ // ============ Q1.2 ============
275
+ document.getElementById("q12code").textContent =
276
+ `class ReportGenerator:
277
+ def __init__(self, data_source):
278
+ self.data_source = data_source
279
+
280
+ def generate_summary(self, report_id):
281
+ records = self.data_source.fetch_records(report_id)
282
+
283
+ if len(records) == 0:
284
+ return "No records found"
285
+
286
+ total = sum(record["value"] for record in records)
287
+ return f"{len(records)} records, total value: {total}"
288
+
289
+
290
+ class FixedDataSource:
291
+ def fetch_records(self, report_id):
292
+ return [
293
+ {"name": "Item A", "value": 20},
294
+ {"name": "Item B", "value": 30},
295
+ ]
296
+
297
+
298
+ def test_generate_summary():
299
+ data_source = FixedDataSource()
300
+ generator = ReportGenerator(data_source)
301
+
302
+ result = generator.generate_summary("weekly-report")
303
+
304
+ assert result == "2 records, total value: 50"`;
305
+
306
+ buildChoice(document.getElementById("q12opts"), "q12", [
307
+ {val:"a", label:"a. stub"},
308
+ {val:"b", label:"b. driver"},
309
+ ], v => { answers.q12 = v; saveSession(); });
310
+
311
+ // ============ Q2.1 ============
312
+ const Q21_BLOCKS = {
313
+ A: "Chrome Password AU\nChrome SSO US\nFirefox Password US",
314
+ B: "Chrome Password AU\nChrome SSO US\nFirefox Password US\nFirefox SSO AU",
315
+ C: "Chrome Password AU\nChrome Password US\nFirefox SSO AU\nFirefox SSO US",
316
+ D: "Chrome Password AU\nChrome Password US\nChrome SSO AU\nChrome SSO US\nFirefox Password AU\nFirefox Password US\nFirefox SSO AU\nFirefox SSO US",
317
+ };
318
+ buildChoice(document.getElementById("q21opts"), "q21",
319
+ ["A","B","C","D"].map(k => ({val:k, label:k, body:`<pre>${Q21_BLOCKS[k]}</pre>`})),
320
+ v => { answers.q21 = v; saveSession(); });
321
+
322
+ // ============ Q2.2 ============
323
+ buildChoice(document.getElementById("q22opts"), "q22", [
324
+ {val:"a", label:"a. 4"},
325
+ {val:"b", label:"b. 6"},
326
+ {val:"c", label:"c. 8"},
327
+ {val:"d", label:"d. 12"},
328
+ ], v => { answers.q22 = v; saveSession(); });
329
+
330
+ // ============ generic blank-template builder ============
331
+ // Template text with @n@ placeholders -> replaced with <input class="blank">.
332
+ // widthClass: "short" for small numeric-ish blanks, "" (default) for long blanks.
333
+ function buildBlanks(host, text, store, widthClass){
334
+ host.innerHTML = ""; host.style.whiteSpace = "pre-wrap";
335
+ const parts = text.split(/@(\d+)@/);
336
+ for (let i=0;i<parts.length;i++){
337
+ if (i % 2 === 0){ host.appendChild(document.createTextNode(parts[i])); }
338
+ else {
339
+ const n = parts[i];
340
+ const inp = document.createElement("input");
341
+ inp.className = "blank" + (widthClass ? " " + widthClass : "");
342
+ inp.dataset.n = n; inp.title = "blank " + n;
343
+ inp.oninput = () => { store[n] = inp.value; saveSession(); };
344
+ host.appendChild(inp);
345
+ }
346
+ }
347
+ }
348
+
349
+ // ============ Q3: 5 fill-in blanks ============
350
+ const Q3_TEXT =
351
+ `1. Integrating and testing high-level modules before lower-level modules is called @1@ integration testing.
352
+
353
+ 2. During this strategy, unavailable lower-level modules are commonly replaced by @2@.
354
+
355
+ 3. Integrating low-level modules first commonly requires @3@ to invoke them before their callers are available.
356
+
357
+ 4. Integrating all components at the same time is called @4@ integration testing.
358
+
359
+ 5. Restricting one integration test session to only \`OrderService\` and \`PaymentGateway\` corresponds to @5@ integration.`;
360
+ buildBlanks(document.getElementById("q3block"), Q3_TEXT, answers.q3);
361
+
362
+ // ============ Q4 reference program + tests (static) ============
363
+ document.getElementById("q4prog").textContent =
364
+ `def parking_fee(
365
+ hours: int,
366
+ weekend: bool,
367
+ member: bool,
368
+ ) -> int:
369
+ if hours <= 0:
370
+ raise ValueError("hours must be positive")
371
+
372
+ if hours >= 8:
373
+ fee = 20
374
+ elif hours >= 4:
375
+ fee = 14
376
+ else:
377
+ fee = 8
378
+
379
+ if weekend:
380
+ fee += 3
381
+
382
+ if member:
383
+ fee -= 2
384
+
385
+ return fee`;
386
+
387
+ document.getElementById("q4tests").textContent =
388
+ `TESTS = [
389
+ ((10, False, False), 20),
390
+ ((5, False, False), 14),
391
+ ((2, True, False), 11),
392
+ ((5, False, True), 12),
393
+ ]`;
394
+
395
+ // ============ Q4.1: 4 blanks ============
396
+ const Q41_TEXT = `M1: @1@
397
+ M2: @2@
398
+ M3: @3@
399
+ M4: @4@`;
400
+ buildBlanks(document.getElementById("q41block"), Q41_TEXT, answers.q41, "short");
401
+
402
+ // ============ Q4.2: code editor ============
403
+ const Q42_SKELETON =
404
+ `def capped_parking_fee_mr_oracle(
405
+ hours: int,
406
+ increase: int,
407
+ weekend: bool,
408
+ member: bool,
409
+ ) -> bool:
410
+ if hours < 8 or increase <= 0:
411
+ raise ValueError("invalid metamorphic test input")
412
+
413
+ # Complete this function
414
+ pass`;
415
+ const q42editor = CodeMirror.fromTextArea(document.getElementById("q42code"), {
416
+ mode:"python", theme:"material-darker", lineNumbers:true, indentUnit:4, tabSize:4,
417
+ extraKeys:{ Tab:cm=>cm.replaceSelection(" ") },
418
+ });
419
+ q42editor.setValue(Q42_SKELETON);
420
+ q42editor.on("change", () => saveSession());
421
+
422
+ // ============ Q4.3: 3 blanks (mutation score) ============
423
+ const Q43_TEXT =
424
+ `mutation score = killed non-equivalent mutants / total non-equivalent mutants
425
+ = @1@ / @2@
426
+ = @3@ %`;
427
+ buildBlanks(document.getElementById("q43block"), Q43_TEXT, answers.q43, "short");
428
+
429
+ // ============ Q4.4: source/follow-up blanks + regression assert ============
430
+ const Q44_TEXT =
431
+ `source input:
432
+ hours = @1@
433
+ weekend = @2@
434
+ member = @3@
435
+
436
+ transformation:
437
+ increase = @4@
438
+
439
+ follow-up input:
440
+ hours = @5@
441
+ weekend = @6@
442
+ member = @7@
443
+
444
+ source output from the surviving mutant = @8@
445
+ follow-up output from the surviving mutant = @9@`;
446
+ buildBlanks(document.getElementById("q44block"), Q44_TEXT, answers.q44, "short");
447
+
448
+ const Q44_ASSERT_TEXT = `assert parking_fee(@1@, @2@, @3@) == @4@`;
449
+ buildBlanks(document.getElementById("q44assert"), Q44_ASSERT_TEXT, answers.q44assert, "short");
450
+
451
+ // ============ JSON export ============
452
+ function buildJSON(){
453
+ return {
454
+ assignment: "Assignment 3: Software Testing",
455
+ student_id: document.getElementById("studentId").value.trim(),
456
+ answers: {
457
+ q1: {
458
+ 1: answers.q11.slice(),
459
+ 2: answers.q12 || "",
460
+ },
461
+ q2: {
462
+ 1: answers.q21 || "",
463
+ 2: answers.q22 || "",
464
+ },
465
+ q3: Object.assign({1:"",2:"",3:"",4:"",5:""}, answers.q3),
466
+ q4: {
467
+ 1: Object.assign({1:"",2:"",3:"",4:""}, answers.q41),
468
+ 2: q42editor.getValue(),
469
+ 3: Object.assign({1:"",2:"",3:""}, answers.q43),
470
+ 4: {
471
+ source_followup: Object.assign({1:"",2:"",3:"",4:"",5:"",6:"",7:"",8:"",9:""}, answers.q44),
472
+ regression_assert: Object.assign({1:"",2:"",3:"",4:""}, answers.q44assert),
473
+ },
474
+ },
475
+ }
476
+ };
477
+ }
478
+ function toast(msg){ const t=document.getElementById("toast"); t.textContent=msg; setTimeout(()=>t.textContent="",2500); }
479
+ document.getElementById("exportBtn").onclick = () => {
480
+ const data = JSON.stringify(buildJSON(), null, 2);
481
+ const blob = new Blob([data], {type:"application/json"});
482
+ const a = document.createElement("a");
483
+ const sid = document.getElementById("studentId").value.trim() || "submission";
484
+ a.href = URL.createObjectURL(blob); a.download = `assignment3_${sid}.json`;
485
+ a.click(); URL.revokeObjectURL(a.href); toast("Exported ✓");
486
+ };
487
+ document.getElementById("copyBtn").onclick = async () => {
488
+ try { await navigator.clipboard.writeText(JSON.stringify(buildJSON(), null, 2)); toast("Copied ✓"); }
489
+ catch(_){ toast("Copy failed"); }
490
+ };
491
+
492
+ // ============ local session (auto-save / restore) ============
493
+ const SESSION_KEY = "st_a3_session_v1";
494
+ let __saveTimer = null;
495
+ function saveSession(){
496
+ clearTimeout(__saveTimer);
497
+ __saveTimer = setTimeout(() => {
498
+ try {
499
+ const d = {
500
+ ts: Date.now(),
501
+ studentId: document.getElementById("studentId").value,
502
+ q11: answers.q11, q12: answers.q12, q21: answers.q21, q22: answers.q22,
503
+ q3: answers.q3, q41: answers.q41, q43: answers.q43, q44: answers.q44, q44assert: answers.q44assert,
504
+ q42code: q42editor.getValue(),
505
+ };
506
+ localStorage.setItem(SESSION_KEY, JSON.stringify(d));
507
+ } catch(_){}
508
+ }, 250);
509
+ }
510
+ function restoreRadio(name, val){
511
+ if (!val) return;
512
+ const r = document.querySelector(`input[name="${name}"][value="${val}"]`);
513
+ if (r){ r.checked = true; const opt = r.closest(".opt"); if (opt) opt.classList.add("sel"); }
514
+ }
515
+ function restoreCheckboxes(name, arr){
516
+ if (!arr || !arr.length) return;
517
+ for (const v of arr){
518
+ const cb = document.querySelector(`input[name="${name}"][value="${v}"]`);
519
+ if (cb){ cb.checked = true; const opt = cb.closest(".opt"); if (opt) opt.classList.add("sel"); }
520
+ }
521
+ }
522
+ function restoreBlanks(host, obj){
523
+ if (!obj) return;
524
+ host.querySelectorAll("input.blank").forEach(inp => { const v = obj[inp.dataset.n]; if (v != null) inp.value = v; });
525
+ }
526
+ function loadSession(){
527
+ let d;
528
+ try { d = JSON.parse(localStorage.getItem(SESSION_KEY)); } catch(_){ return; }
529
+ if (!d) return;
530
+ document.getElementById("studentId").value = d.studentId || "";
531
+ if (d.q11){ answers.q11 = d.q11.slice(); restoreCheckboxes("q11", d.q11); }
532
+ answers.q12 = d.q12 || null; restoreRadio("q12", d.q12);
533
+ answers.q21 = d.q21 || null; restoreRadio("q21", d.q21);
534
+ answers.q22 = d.q22 || null; restoreRadio("q22", d.q22);
535
+ if (d.q3){ answers.q3 = Object.assign({}, d.q3); restoreBlanks(document.getElementById("q3block"), d.q3); }
536
+ if (d.q41){ answers.q41 = Object.assign({}, d.q41); restoreBlanks(document.getElementById("q41block"), d.q41); }
537
+ if (d.q43){ answers.q43 = Object.assign({}, d.q43); restoreBlanks(document.getElementById("q43block"), d.q43); }
538
+ if (d.q44){ answers.q44 = Object.assign({}, d.q44); restoreBlanks(document.getElementById("q44block"), d.q44); }
539
+ if (d.q44assert){ answers.q44assert = Object.assign({}, d.q44assert); restoreBlanks(document.getElementById("q44assert"), d.q44assert); }
540
+ if (d.q42code) q42editor.setValue(d.q42code);
541
+
542
+ let ago = "earlier";
543
+ if (d.ts){ const mins = Math.round((Date.now() - d.ts) / 60000);
544
+ ago = mins < 1 ? "just now" : mins < 60 ? mins + " min ago" : mins < 1440 ? Math.round(mins/60) + " h ago" : Math.round(mins/1440) + " d ago"; }
545
+ const b = document.createElement("div");
546
+ b.style.cssText = "margin:10px 0;padding:8px 12px;border:1px solid var(--border);border-radius:8px;background:#262a3f;font-size:12px;color:var(--muted)";
547
+ b.innerHTML = `↺ Restored your answers from this browser (saved ${ago}). They stay saved in this browser until you press Clear. `;
548
+ const x = document.createElement("button"); x.textContent = "Clear & start fresh"; x.className = "ghost";
549
+ x.style.cssText = "padding:3px 10px;font-size:11px;margin-left:6px";
550
+ x.onclick = clearSession;
551
+ b.appendChild(x);
552
+ const wrap = document.querySelector(".wrap");
553
+ wrap.insertBefore(b, wrap.children[2]);
554
+ }
555
+ function clearSession(){ localStorage.removeItem(SESSION_KEY); location.reload(); }
556
+ document.getElementById("studentId").addEventListener("input", saveSession);
557
+ document.getElementById("clearBtn").onclick = clearSession;
558
+ loadSession();
559
+
560
+ // ============ tabs (one per question) ============
561
+ (function initTabs(){
562
+ const TAB_KEY = "st_a3_tab";
563
+ const btns = [...document.querySelectorAll("#tabbar button")];
564
+ const panes = [...document.querySelectorAll(".pane")];
565
+ function show(id){
566
+ if (!btns.some(b => b.dataset.tab === id)) id = "q1";
567
+ btns.forEach(b => b.classList.toggle("active", b.dataset.tab === id));
568
+ panes.forEach(p => p.classList.toggle("active", p.dataset.tab === id));
569
+ try { localStorage.setItem(TAB_KEY, id); } catch(_){}
570
+ if (id === "q4" && typeof q42editor !== "undefined" && q42editor) setTimeout(() => q42editor.refresh(), 0);
571
+ window.scrollTo(0, 0);
572
+ }
573
+ btns.forEach(b => b.onclick = () => show(b.dataset.tab));
574
+ show(localStorage.getItem(TAB_KEY) || "q1");
575
+ })();
576
+ </script>
577
+ </body>
578
+ </html>
build_blackbox.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Encrypt every hidden problem implementation into a .dat file.
3
+
4
+ For each <name>.py in ../T2_UNSW_solution/ it writes an ENCRYPTED <name>.dat in
5
+ this project's root. The cipher is a SHA-256 counter-mode keystream (no
6
+ third-party deps); the browser decrypts it with Web Crypto using the same
7
+ passphrase (see PASSPHRASE in index.html).
8
+
9
+ Usage: python3 build_blackbox.py
10
+
11
+ NOTE: this is obfuscation that raises the bar, not real secrecy -- the passphrase
12
+ ships inside index.html, so a determined reader can still recover the source.
13
+ For true protection the implementation must live on a server.
14
+
15
+ Deploy only the .dat files (and index.html). The plaintext source lives in
16
+ ../T2_UNSW_solution/ -- a SIBLING of this project directory, not nested inside
17
+ it -- because this whole project is served wholesale as a static site (no
18
+ server-side access control), so anything nested inside it is effectively
19
+ public the moment it ships, link or no link. Never move that directory back
20
+ inside T2_UNSW/.
21
+ """
22
+ import base64
23
+ import hashlib
24
+ import pathlib
25
+
26
+ # Must match PASSPHRASE in index.html exactly.
27
+ PASSPHRASE = b"t2-unsw-bbt-v1-rotate-me"
28
+
29
+
30
+ def _keystream_block(key: bytes, counter: int) -> bytes:
31
+ return hashlib.sha256(key + counter.to_bytes(8, "big")).digest()
32
+
33
+
34
+ def encrypt(data: bytes, passphrase: bytes) -> bytes:
35
+ key = hashlib.sha256(passphrase).digest()
36
+ out = bytearray(len(data))
37
+ for off in range(len(data)):
38
+ ks = _keystream_block(key, off // 32)
39
+ out[off] = data[off] ^ ks[off % 32]
40
+ return bytes(out)
41
+
42
+
43
+ ROOT = pathlib.Path(__file__).parent
44
+ src_dir = ROOT.parent / "T2_UNSW_solution"
45
+
46
+ count = 0
47
+ for py in sorted(src_dir.glob("*.py")):
48
+ plain = py.read_text(encoding="utf-8").encode("utf-8")
49
+ cipher = encrypt(plain, PASSPHRASE)
50
+ encoded = base64.b64encode(cipher).decode("ascii")
51
+ out = ROOT / (py.stem + ".dat")
52
+ out.write_text(encoded, encoding="utf-8")
53
+ # self-check: round-trip back to plaintext
54
+ assert encrypt(cipher, PASSPHRASE) == plain, f"round-trip failed for {py.name}"
55
+ print(f" {py.name:14} -> {out.name:10} ({len(encoded)} chars, encrypted)")
56
+ count += 1
57
+
58
+ print(f"OK: encrypted {count} problem file(s).")
coverage_fuzzing/Q5.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Q5 Coverage-Guided Fuzzing
2
+
3
+ In lectures we saw that **blind** mutation-based fuzzing wastes almost all of its
4
+ effort when a program hides its bug behind exact checks (magic bytes, length
5
+ fields, checksums): the chance of randomly satisfying every check at once is
6
+ tiny. **Coverage-guided** fuzzing fixes this by *listening to the program*. The
7
+ target is **instrumented** so that every time execution reaches a new place in
8
+ the code, the fuzzer is told. The fuzzer then keeps any input that reached
9
+ somewhere new and mutates it further, so progress accumulates one check at a
10
+ time instead of all at once.
11
+
12
+ In this question you implement the two mechanisms at the heart of that idea —
13
+ **a mutation operator** and **the coverage-guided loop** — and use them to crash
14
+ a small program that blind fuzzing cannot realistically crack. There are
15
+ **two independent bugs** to find, and they reward two different mutation
16
+ strategies.
17
+
18
+ Everything runs **in your web browser**; there is nothing to install and no C
19
+ compiler to run. Open the provided page (see below) and you will find:
20
+
21
+ * the **target** already compiled to WebAssembly and instrumented with a
22
+ coverage probe at every edge (its source is not provided — this is a
23
+ black-box target, so `run`, `coverage`, and `crashed` below are all the
24
+ information you get);
25
+ * a Python editor with a starter file `fuzz.py`;
26
+ * a live dashboard showing executions, coverage, corpus size, and any crashes.
27
+
28
+ ### The target
29
+
30
+ A tiny binary-message parser. It reads a byte buffer and walks a chain of
31
+ checks behind a 4-byte magic prefix. Two independent memory-safety bugs sit
32
+ behind that same prefix:
33
+
34
+ * **Bug 1 — out-of-bounds read.** One field indexes a small internal table
35
+ with no range check.
36
+ * **Bug 2 — integer overflow.** A separate, wider (multi-byte) numeric field
37
+ feeds an arithmetic size check; the check trusts a computation that can
38
+ silently wrap around, while the real access does not.
39
+
40
+ (This assignment does not use AddressSanitizer; the harness reports which
41
+ bug(s) fired via `crashed`, which you should treat exactly like a sanitizer
42
+ abort for that bug.)
43
+
44
+ ### The API available in `fuzz.py`
45
+
46
+ ```text
47
+ run(data) -> (coverage, crashed)
48
+ Execute the target on `data` (bytes / bytearray / list of ints).
49
+ coverage : list[int] of length NUM_EDGES; coverage[k] > 0 means edge k was
50
+ reached on this run.
51
+ crashed : int BITMASK. bit0 (value 1) = Bug 1 fired on this run;
52
+ bit1 (value 2) = Bug 2 fired. Either, both, or neither bit may
53
+ be set. 0 means nothing crashed on this run.
54
+
55
+ NUM_EDGES : int number of instrumented edges
56
+ SEED : bytes a starting input (valid length, does NOT crash)
57
+
58
+ report(execs, corpus_size, covered_edges) update the dashboard
59
+ save_crash(data, which) record a crashing input; `which`
60
+ is "bug1" or "bug2"
61
+ log(*args) print to the console
62
+ ```
63
+
64
+ ### What you must do
65
+
66
+ The fuzzing loop is already written for you and keeps going after a crash —
67
+ finding one bug does not end the search for the other. You only complete
68
+ **two small functions** it calls:
69
+
70
+ 1. **`mutate(data) -> bytes`** — a mutation operator that returns a slightly
71
+ changed copy of the input. A single operator does not have to be your only
72
+ strategy: the two bugs above are different *shapes* of bug and reward
73
+ different mutations. Be ready to justify your choices (see the
74
+ deliverables). *Hints:*
75
+ * For an **exact-byte check** (like a magic prefix), think about what a
76
+ single bit-flip can and cannot accomplish, versus substituting a
77
+ brand-new random byte.
78
+ * For a **wide numeric field feeding arithmetic** (like an overflow),
79
+ random byte substitution is a poor fit — the values that actually matter
80
+ cluster at specific numbers (0, 1, the field's maximum, half its maximum,
81
+ powers of two). Once you are near a promising value, small `+`/`-`
82
+ adjustments let you creep onto the exact point where the arithmetic
83
+ wraps around.
84
+ 2. **`is_interesting(cov, covered) -> bool`** — the coverage decision. `cov` is
85
+ the coverage of the current run (`cov[k] > 0` means edge `k` was reached);
86
+ `covered` is the set of edges reached on all previous runs. Return `True`
87
+ exactly when the run reached an edge that is **not** already in `covered`
88
+ (i.e. the input discovered new code and should be kept) — regardless of
89
+ whether that same run also happened to crash.
90
+
91
+ Run it in the page: when `is_interesting` is right, the loop keeps each input
92
+ that unlocks new coverage, the corpus grows, and the fuzzer climbs the checks
93
+ until it hits each bug and saves its crash file.
94
+
95
+ Your fuzzer must find **both** crashes **in the browser within 5 minutes** (a
96
+ correct solution finds Bug 1 in seconds and Bug 2 shortly after). You may
97
+ **not** hard-code either crashing input.
98
+
99
+ ### Deliverables
100
+
101
+ * `fuzz.py` — your `mutate` and `is_interesting` implementations.
102
+ * `crash_bug1.bin` and `crash_bug2.bin` — the crashing inputs your fuzzer
103
+ discovered for each bug (downloaded from the page). Finding only Bug 1
104
+ earns partial credit; full credit requires both.
105
+ * A short answer (4–6 sentences) covering **both** bugs: for each one, which
106
+ mutation operator did you use and why is it suitable for that bug's shape?
107
+ Contrast an operator that would work for one bug but fail (or be unreliable)
108
+ for the other, and explain in one sentence why making `is_interesting`
109
+ always return `True` (keeping everything) or always `False` (keeping
110
+ nothing) would break the search.
coverage_fuzzing/app.js ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Main-thread UI controller: owns the editor, spawns the worker, renders
2
+ * progress. All the heavy lifting (Pyodide + wasm + the student loop) happens
3
+ * in worker.js so the page never freezes. */
4
+
5
+ const $ = (id) => document.getElementById(id);
6
+ const statusEl = $("status");
7
+ const runBtn = $("run");
8
+ const stopBtn = $("stop");
9
+ const resetBtn = $("reset");
10
+ const consoleEl = $("console");
11
+ const edgesEl = $("edges");
12
+
13
+ let editor;
14
+ let worker = null;
15
+ let workerReady = false;
16
+ let starterCode = "";
17
+
18
+ function print(text, cls) {
19
+ const span = document.createElement("span");
20
+ span.textContent = text + "\n";
21
+ if (cls) span.style.color = cls;
22
+ consoleEl.appendChild(span);
23
+ consoleEl.scrollTop = consoleEl.scrollHeight;
24
+ }
25
+
26
+ function renderEdges(numEdges, covered) {
27
+ const set = new Set(covered || []);
28
+ if (edgesEl.childElementCount !== numEdges) {
29
+ edgesEl.innerHTML = "";
30
+ for (let i = 0; i < numEdges; i++) {
31
+ const d = document.createElement("div");
32
+ d.className = "edge";
33
+ d.id = "edge-" + i;
34
+ d.textContent = i;
35
+ edgesEl.appendChild(d);
36
+ }
37
+ }
38
+ for (let i = 0; i < numEdges; i++) {
39
+ $("edge-" + i).classList.toggle("hit", set.has(i));
40
+ }
41
+ }
42
+
43
+ const CRASH_KINDS = ["bug1", "bug2"];
44
+
45
+ function resetDashboard() {
46
+ $("s-execs").textContent = "0";
47
+ $("s-eps").textContent = "0";
48
+ $("s-corpus").textContent = "0";
49
+ $("s-cov").textContent = "0 / 0";
50
+ for (const kind of CRASH_KINDS) {
51
+ const el = $("crash-" + kind);
52
+ if (el) el.style.display = "none";
53
+ }
54
+ consoleEl.innerHTML = "";
55
+ }
56
+
57
+ // --- worker lifecycle -----------------------------------------------------
58
+
59
+ function spawnWorker() {
60
+ worker = new Worker("worker.js");
61
+ workerReady = false;
62
+ worker.onmessage = (e) => {
63
+ const m = e.data;
64
+ switch (m.type) {
65
+ case "ready":
66
+ workerReady = true;
67
+ statusEl.textContent = "ready — edit fuzz.py and click Run";
68
+ runBtn.disabled = false;
69
+ break;
70
+ case "progress":
71
+ $("s-execs").textContent = m.execs.toLocaleString();
72
+ $("s-eps").textContent = Math.round(m.execsPerSec).toLocaleString();
73
+ $("s-corpus").textContent = m.corpus.toLocaleString();
74
+ $("s-cov").textContent = `${m.covered.length} / ${m.numEdges}`;
75
+ renderEdges(m.numEdges, m.covered);
76
+ break;
77
+ case "log":
78
+ print(m.text, "#9fd0ff");
79
+ break;
80
+ case "print":
81
+ print(m.text);
82
+ break;
83
+ case "crash": {
84
+ const kind = CRASH_KINDS.includes(m.which) ? m.which : "bug1";
85
+ const bytes = Uint8Array.from(m.bytes);
86
+ const hex = Array.from(bytes)
87
+ .map((b) => b.toString(16).padStart(2, "0"))
88
+ .join(" ");
89
+ $(`crash-${kind}-hex`).textContent = hex + ` (${bytes.length} bytes)`;
90
+ const blob = new Blob([bytes], { type: "application/octet-stream" });
91
+ $(`crash-${kind}-dl`).href = URL.createObjectURL(blob);
92
+ $(`crash-${kind}`).style.display = "block";
93
+ print(`💥 crash saved [${kind}] (` + hex + ")", "#ff9aa2");
94
+ break;
95
+ }
96
+ case "done":
97
+ finishRun("finished");
98
+ break;
99
+ case "error":
100
+ print(m.text, "#ff5c6c");
101
+ finishRun("error");
102
+ break;
103
+ }
104
+ };
105
+ }
106
+
107
+ function finishRun(why) {
108
+ runBtn.disabled = false;
109
+ stopBtn.disabled = true;
110
+ statusEl.textContent = why === "error" ? "stopped on error" : "run complete";
111
+ }
112
+
113
+ // --- buttons --------------------------------------------------------------
114
+
115
+ runBtn.onclick = () => {
116
+ if (!workerReady) return;
117
+ resetDashboard();
118
+ runBtn.disabled = true;
119
+ stopBtn.disabled = false;
120
+ statusEl.textContent = "fuzzing…";
121
+ worker.postMessage({ type: "run", code: editor.getValue() });
122
+ };
123
+
124
+ stopBtn.onclick = () => {
125
+ if (worker) worker.terminate();
126
+ print("■ stopped by user", "#ffcf6b");
127
+ spawnWorker();
128
+ statusEl.textContent = "restarting runtime…";
129
+ finishRun("stopped");
130
+ runBtn.disabled = true; // until 'ready'
131
+ };
132
+
133
+ resetBtn.onclick = () => {
134
+ if (starterCode) editor.setValue(starterCode);
135
+ };
136
+
137
+ // Hint: reveal only the coverage-retention step (TODO 2). Does not give away the
138
+ // mutation operator (TODO 1), which students must choose and justify.
139
+ const hintBtn = document.getElementById("hint-btn");
140
+ const hintBox = document.getElementById("hint");
141
+ hintBox.innerHTML =
142
+ "<b>Hint — the two bugs.</b>\n" +
143
+ " • Bug 1: an out-of-bounds READ (an unchecked index/offset).\n" +
144
+ " • Bug 2: an INTEGER OVERFLOW (an arithmetic check that can wrap around).\n\n" +
145
+ "<b>Hint — TODO 1: the mutation operator.</b>\n" +
146
+ "The target checks individual bytes against fixed values. Think it through:\n" +
147
+ " • If one byte is wrong, what is the simplest change that could make it right?\n" +
148
+ " • A single bit-flip only nudges one bit. If the byte you need differs in\n" +
149
+ " several bits, how many flips (and how much luck) would that take?\n" +
150
+ " • What if, instead, you picked one position and dropped in a brand-new\n" +
151
+ " random byte value? Which reaches an exact target byte faster?\n" +
152
+ "That's a poor fit for Bug 2, which hinges on a NUMBER, not one exact byte.\n" +
153
+ "Try whole 'interesting' values (0, 1, max, half-max, powers of two) instead\n" +
154
+ "of a single random byte, then nudge a promising one with small +/- steps.\n\n" +
155
+ "<b>Hint — TODO 2: is_interesting(cov, covered).</b>\n" +
156
+ "`cov[k] > 0` means edge k was reached on THIS run. `covered` is the set of\n" +
157
+ "edges reached on every previous run. Ask yourself:\n" +
158
+ " • Which edges did THIS run reach?\n" +
159
+ " • Is any of them missing from `covered` — something never seen before?\n" +
160
+ " • If so, the input reached new code: should the function say True or False?\n" +
161
+ "Return True exactly when the run reached at least one brand-new edge. Keeping\n" +
162
+ "only those inputs is what lets the fuzzer climb the checks one at a time\n" +
163
+ "instead of guessing them all at once.";
164
+ hintBtn.onclick = () => {
165
+ const show = hintBox.style.display !== "block";
166
+ hintBox.style.display = show ? "block" : "none";
167
+ hintBtn.textContent = show ? "💡 Hide hint" : "💡 Hint";
168
+ };
169
+
170
+ // --- boot -----------------------------------------------------------------
171
+
172
+ async function boot() {
173
+ editor = CodeMirror.fromTextArea($("code"), {
174
+ mode: "python",
175
+ theme: "idea",
176
+ lineNumbers: true,
177
+ indentUnit: 4,
178
+ });
179
+ try {
180
+ starterCode = await (await fetch("starter.py")).text();
181
+ editor.setValue(starterCode);
182
+ window.__editor = editor; // exposed for automated testing
183
+ } catch {
184
+ editor.setValue("# could not load starter.py — are you serving over http?\n");
185
+ }
186
+ renderEdges(12, []);
187
+ spawnWorker();
188
+ }
189
+
190
+ boot();
coverage_fuzzing/index.html ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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" />
6
+ <title>COMP3142 A3 Q5 — Coverage-Guided Fuzzing</title>
7
+
8
+ <!-- CodeMirror (editor) -->
9
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/codemirror@5.65.16/lib/codemirror.min.css" />
10
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/codemirror@5.65.16/theme/idea.min.css" />
11
+ <script src="https://cdn.jsdelivr.net/npm/codemirror@5.65.16/lib/codemirror.min.js"></script>
12
+ <script src="https://cdn.jsdelivr.net/npm/codemirror@5.65.16/mode/python/python.min.js"></script>
13
+
14
+ <style>
15
+ :root { --bg:#0f1420; --panel:#171d2b; --ink:#e6e9ef; --muted:#93a0b5; --accent:#4ea1ff; --ok:#37d67a; --bad:#ff5c6c; --edge:#26304a; }
16
+ * { box-sizing: border-box; }
17
+ body { margin:0; font:14px/1.5 -apple-system,Segoe UI,Roboto,sans-serif; background:var(--bg); color:var(--ink); }
18
+ header { padding:14px 20px; border-bottom:1px solid #222c40; display:flex; align-items:center; gap:16px; flex-wrap:wrap;}
19
+ header h1 { font-size:16px; margin:0; font-weight:600; }
20
+ header .status { color:var(--muted); font-size:13px; }
21
+ main { display:grid; grid-template-columns: 1fr; gap:14px; padding:14px 20px; align-items:start; }
22
+ .panel { background:var(--panel); border:1px solid #222c40; border-radius:10px; overflow:hidden; }
23
+ .panel h2 { font-size:12px; text-transform:uppercase; letter-spacing:.08em; color:var(--muted); margin:0; padding:10px 14px; border-bottom:1px solid #222c40; }
24
+ .toolbar { display:flex; gap:8px; padding:10px 14px; align-items:center; flex-wrap:wrap; }
25
+ button { background:var(--accent); color:#04121f; border:0; border-radius:7px; padding:8px 14px; font-weight:600; cursor:pointer; }
26
+ button.ghost { background:#243049; color:var(--ink); }
27
+ button:disabled { opacity:.5; cursor:not-allowed; }
28
+ .CodeMirror { height:460px; font-size:13px; }
29
+ .dash { display:grid; grid-template-columns: repeat(2,1fr); gap:10px; padding:14px; }
30
+ .stat { background:#111726; border:1px solid #222c40; border-radius:8px; padding:10px 12px; }
31
+ .stat .k { color:var(--muted); font-size:11px; text-transform:uppercase; letter-spacing:.06em; }
32
+ .stat .v { font-size:22px; font-weight:700; font-variant-numeric:tabular-nums; }
33
+ .edges { display:flex; gap:6px; padding:0 14px 14px; flex-wrap:wrap; }
34
+ .edge { width:34px; height:34px; border-radius:6px; background:var(--edge); display:flex; align-items:center; justify-content:center; font-size:12px; color:#6b7897; border:1px solid #2c3855; transition:background .15s; }
35
+ .edge.hit { background:var(--ok); color:#04121f; border-color:var(--ok); font-weight:700; }
36
+ .banner { margin:0 14px 14px; padding:12px 14px; border-radius:8px; display:none;
37
+ background:rgba(255,92,108,.14); border:1px solid var(--bad); color:#ffd4d8; }
38
+ .banner .hex { font-family:ui-monospace,Menlo,monospace; word-break:break-all; margin:6px 0; }
39
+ #console { font-family:ui-monospace,Menlo,monospace; font-size:12px; white-space:pre-wrap; padding:12px 14px; height:150px; overflow:auto; color:#cbd5e6; }
40
+ a.dl { color:var(--accent); }
41
+ code { background:#111726; padding:1px 5px; border-radius:4px; }
42
+ .hint { display:none; margin:0 14px; padding:12px 14px; background:#111726; border:1px solid #2c3855;
43
+ border-radius:8px; font-family:ui-monospace,Menlo,monospace; font-size:12.5px; white-space:pre-wrap; color:#cbd5e6; }
44
+ .hint b { color:var(--accent); }
45
+ </style>
46
+ </head>
47
+ <body>
48
+ <header>
49
+ <h1>COMP3142 · Assignment 3 · Q5 — Coverage-Guided Fuzzing</h1>
50
+ <span class="status" id="status">loading Python runtime…</span>
51
+ </header>
52
+
53
+ <main>
54
+ <!-- LEFT: editor -->
55
+ <section class="panel">
56
+ <h2>fuzz.py — your fuzzer</h2>
57
+ <div class="toolbar">
58
+ <button id="run" disabled>▶ Run</button>
59
+ <button id="stop" class="ghost" disabled>■ Stop</button>
60
+ <button id="reset" class="ghost">⤺ Reset code</button>
61
+ <button id="hint-btn" class="ghost">💡 Hint</button>
62
+ <span class="status">edit → Run. Target &amp; coverage API are provided.</span>
63
+ </div>
64
+ <pre id="hint" class="hint"></pre>
65
+ <textarea id="code"></textarea>
66
+ </section>
67
+
68
+ <!-- RIGHT: dashboard -->
69
+ <section class="panel">
70
+ <h2>fuzzing dashboard</h2>
71
+ <div class="dash">
72
+ <div class="stat"><div class="k">executions</div><div class="v" id="s-execs">0</div></div>
73
+ <div class="stat"><div class="k">exec / sec</div><div class="v" id="s-eps">0</div></div>
74
+ <div class="stat"><div class="k">corpus size</div><div class="v" id="s-corpus">0</div></div>
75
+ <div class="stat"><div class="k">coverage</div><div class="v" id="s-cov">0 / 0</div></div>
76
+ </div>
77
+ <h2>edge coverage map</h2>
78
+ <div class="edges" id="edges"></div>
79
+ <div class="banner" id="crash-bug1">
80
+ <strong>💥 Bug 1 FOUND.</strong>
81
+ <div class="hex" id="crash-bug1-hex"></div>
82
+ <a class="dl" id="crash-bug1-dl" download="crash_bug1.bin">⬇ download crash_bug1.bin</a>
83
+ </div>
84
+ <div class="banner" id="crash-bug2">
85
+ <strong>💥 Bug 2 FOUND.</strong>
86
+ <div class="hex" id="crash-bug2-hex"></div>
87
+ <a class="dl" id="crash-bug2-dl" download="crash_bug2.bin">⬇ download crash_bug2.bin</a>
88
+ </div>
89
+ <h2>console</h2>
90
+ <div id="console"></div>
91
+ </section>
92
+ </main>
93
+
94
+ <script src="app.js"></script>
95
+ </body>
96
+ </html>
coverage_fuzzing/starter.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ MAX_EXECS = 200_000
4
+
5
+ INTERESTING_VALUES = [0, 1, 0x7F, 0x80, 0xFF]
6
+
7
+
8
+ # -----------------------------------------------------------------------------
9
+ # TODO 1 — a mutation operator.
10
+ #
11
+ # Take an input and return a NEW input that is changed a little. Choose a change
12
+ # that can actually steer the target through its checks, and be ready to
13
+ # justify your choice in your report. Your mutation does not need to change
14
+ # the length of `data` -- the starting input is already long enough for
15
+ # anything you'll need to reach.
16
+ #
17
+ # The placeholder below changes nothing (no-op), so the fuzzer makes no progress.
18
+ # Replace it with a real mutation.
19
+ # -----------------------------------------------------------------------------
20
+ def mutate(data: bytes) -> bytes:
21
+ data = bytearray(data)
22
+ # example of the shape a mutation takes (not a full solution):
23
+ # i = random.randrange(len(data))
24
+ # data[i] ^= 1 << random.randrange(8)
25
+ # >>> TODO 1: change one small part of `data` here <<<
26
+ return bytes(data)
27
+
28
+
29
+ # -----------------------------------------------------------------------------
30
+ # TODO 2 — the coverage decision.
31
+ #
32
+ # `cov` is this run's coverage (cov[k] > 0 means edge k was reached this run).
33
+ # `covered` is the set of edge indices reached on ANY previous run.
34
+ # Return True if this run reached an edge that is NOT already in `covered`
35
+ # (i.e. the input discovered new code and is worth keeping).
36
+ #
37
+ # The placeholder below always returns False, so nothing is ever kept.
38
+ # -----------------------------------------------------------------------------
39
+ def is_interesting(cov, covered) -> bool:
40
+ # >>> TODO 2: return True if `cov` reached an edge not in `covered` <<<
41
+ return False
42
+
43
+
44
+ def fuzz():
45
+ log("Starter template running. It will NOT find anything until you complete:")
46
+ log(" TODO 1 (mutate): actually change a byte so inputs can pass the checks.")
47
+ log(" TODO 2 (is_interesting): return True when a run reaches a NEW edge.")
48
+
49
+ corpus = [bytes(SEED)]
50
+ covered = set()
51
+ found = set()
52
+ BUGS = {1: "bug1", 2: "bug2"}
53
+
54
+ def add_edges(cov):
55
+ for i in range(len(cov)):
56
+ if cov[i] > 0:
57
+ covered.add(i)
58
+
59
+ add_edges(run(SEED)[0])
60
+
61
+ for execs in range(1, MAX_EXECS + 1):
62
+ base = random.choice(corpus)
63
+ candidate = mutate(base)
64
+ cov, crashed = run(candidate)
65
+
66
+ if crashed:
67
+ for bit, name in BUGS.items():
68
+ if (crashed & bit) and bit not in found:
69
+ found.add(bit)
70
+ save_crash(candidate, name)
71
+ log(f"CRASH [{name}] after {execs} executions:", candidate.hex(" "))
72
+
73
+ keep = is_interesting(cov, covered)
74
+ add_edges(cov)
75
+ if keep:
76
+ corpus.append(candidate)
77
+
78
+ if found == set(BUGS):
79
+ report(execs, len(corpus), covered)
80
+ log("Both bugs found after", execs, "executions. Done.")
81
+ return
82
+
83
+ if execs % 500 == 0:
84
+ report(execs, len(corpus), covered)
85
+
86
+ missing = [BUGS[b] for b in BUGS if b not in found]
87
+ log("stopped after", MAX_EXECS, "executions -",
88
+ f"found {sorted(BUGS[b] for b in found)}, still missing {missing},",
89
+ f"coverage stuck at {len(covered)}/{NUM_EDGES}. Complete the TODOs and re-run.")
90
+
91
+
92
+ fuzz()
coverage_fuzzing/target/target.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1a6728203eaf8e7650795b4aacbdbd414e73f3da4070e91995e09376cf2c5f0
3
+ size 3354
coverage_fuzzing/worker.js ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Web Worker: runs Pyodide + the WebAssembly target off the main thread so the
3
+ * page stays responsive. The student's Python fuzzer runs here. Progress is
4
+ * streamed back to the page via postMessage; "Stop" on the page simply
5
+ * terminates and respawns this worker.
6
+ */
7
+
8
+ importScripts("https://cdn.jsdelivr.net/pyodide/v0.26.2/full/pyodide.js");
9
+
10
+ let pyodide = null;
11
+ let wasm = null; // exports of target.wasm
12
+
13
+ // --- bridge functions the Python shim calls (visible from Python as js.*) ---
14
+
15
+ self.runTargetJS = function (bytes) {
16
+ // bytes: a JS Array/TypedArray of ints. Returns {coverage:[...], crashed:int}.
17
+ // `crashed` is a BITMASK: bit0 = bug 1, bit1 = bug 2. Either, both, or
18
+ // neither bit may be set for a given input.
19
+ const mem = new Uint8Array(wasm.memory.buffer); // recompute in case of growth
20
+ const inp = wasm.input_ptr();
21
+ const n = Math.min(bytes.length, 256);
22
+ for (let i = 0; i < 256; i++) mem[inp + i] = 0;
23
+ for (let i = 0; i < n; i++) mem[inp + i] = bytes[i] & 0xff;
24
+ wasm.run(n);
25
+ const cov = wasm.cov_ptr();
26
+ const csz = wasm.cov_size();
27
+ return {
28
+ coverage: Array.from(mem.slice(cov, cov + csz)),
29
+ crashed: mem[wasm.crashed_ptr()],
30
+ };
31
+ };
32
+
33
+ let lastReport = 0;
34
+ self.reportJS = function (execs, corpus, coveredEdges, execsPerSec) {
35
+ self.postMessage({
36
+ type: "progress",
37
+ execs,
38
+ corpus,
39
+ covered: Array.from(coveredEdges),
40
+ numEdges: wasm.cov_size(),
41
+ execsPerSec,
42
+ });
43
+ };
44
+
45
+ self.saveCrashJS = function (bytes, which) {
46
+ const arr = Array.from(bytes, (b) => b & 0xff);
47
+ self.postMessage({ type: "crash", bytes: arr, which: String(which) });
48
+ };
49
+
50
+ self.logJS = function (text) {
51
+ self.postMessage({ type: "log", text: String(text) });
52
+ };
53
+
54
+ // --- Python bootstrap injected before the student's code ---
55
+ const PY_BOOTSTRAP = `
56
+ import js, time
57
+ from pyodide.ffi import to_js
58
+
59
+ NUM_EDGES = int(js.runTargetJS(to_js([0])).coverage.length)
60
+ SEED = bytes([0x41] * 5) + bytes([0x12, 0x34, 0x56, 0x78]) # wrong magic, offset='A', a generic non-zero count
61
+
62
+ _t0 = time.time()
63
+
64
+ def run(data):
65
+ """Execute the target on 'data' (bytes/bytearray/list of ints).
66
+ Returns (coverage, crashed):
67
+ coverage : list[int] of length NUM_EDGES; coverage[k] = hits on edge k
68
+ crashed : int BITMASK. bit0 (value 1) = bug 1 fired on this run;
69
+ bit1 (value 2) = bug 2 fired. Either, both, or neither bit
70
+ may be set. Falsy (0) means nothing crashed.
71
+ """
72
+ res = js.runTargetJS(to_js(list(bytearray(data))))
73
+ return list(res.coverage.to_py()), int(res.crashed)
74
+
75
+ def report(execs, corpus_size, covered_edges):
76
+ """Update the on-screen dashboard. 'covered_edges' is any iterable of the
77
+ edge indices your fuzzer has reached so far."""
78
+ eps = execs / max(time.time() - _t0, 1e-6)
79
+ js.reportJS(int(execs), int(corpus_size),
80
+ to_js(sorted({int(e) for e in covered_edges})), float(eps))
81
+
82
+ def save_crash(data, which):
83
+ """Record a crashing input; the page will offer it as a download.
84
+ 'which' is a short label identifying which bug this input triggers
85
+ (e.g. "bug1" or "bug2") -- used only to show it in the right slot on
86
+ the dashboard."""
87
+ js.saveCrashJS(to_js(list(bytearray(data))), which)
88
+
89
+ def log(*args):
90
+ js.logJS(" ".join(str(a) for a in args))
91
+ `;
92
+
93
+ async function init() {
94
+ pyodide = await loadPyodide();
95
+ const resp = await fetch("target/target.wasm");
96
+ const { instance } = await WebAssembly.instantiate(
97
+ await resp.arrayBuffer(),
98
+ {}
99
+ );
100
+ wasm = instance.exports;
101
+
102
+ // redirect Python stdout/stderr to the page
103
+ pyodide.setStdout({ batched: (t) => self.postMessage({ type: "print", text: t }) });
104
+ pyodide.setStderr({ batched: (t) => self.postMessage({ type: "print", text: t }) });
105
+
106
+ self.postMessage({ type: "ready" });
107
+ }
108
+
109
+ const ready = init();
110
+
111
+ self.onmessage = async (e) => {
112
+ if (e.data.type !== "run") return;
113
+ await ready;
114
+ try {
115
+ await pyodide.runPythonAsync(PY_BOOTSTRAP + "\n" + e.data.code);
116
+ self.postMessage({ type: "done" });
117
+ } catch (err) {
118
+ self.postMessage({ type: "error", text: String(err) });
119
+ }
120
+ };
grade_submissions.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Auto-grade UNSW give submissions for Assignment 1 (black-box testing).
3
+
4
+ For every student id in the xlsx:
5
+ 1. extract submission.tar -> nested zip/tar -> find Q1/Q2 test files
6
+ 2. pull out the TESTS list (tolerant: lowercase 'Tests', .txt files, q1.py,
7
+ inline comments, and missing-comma syntax errors via per-line recovery)
8
+ 3. grade against our reference + 5-bug black box (same logic as the playground:
9
+ a case counts only if its expected matches the spec; combined/multi-boundary
10
+ discrepancies that don't isolate ONE of the 5 bugs are NOT counted)
11
+ 4. write Q1/Q2 scores (0.5 per bug, /2.5 each) back into the xlsx.
12
+
13
+ Student code is NEVER executed -- TESTS is parsed with ast.literal_eval only.
14
+
15
+ Usage: python3 grade_submissions.py
16
+ """
17
+ import importlib.util, ast, re, glob, os, json, tarfile, zipfile, tempfile, shutil, collections
18
+ import openpyxl
19
+
20
+ HERE = os.path.dirname(os.path.abspath(__file__))
21
+ ROOT = "/Users/shangzhi/Downloads/26ass1"
22
+ XLSX = "/Users/shangzhi/Downloads/26ass1.xlsx"
23
+
24
+ def load(n, p):
25
+ s = importlib.util.spec_from_file_location(n, p); m = importlib.util.module_from_spec(s); s.loader.exec_module(m); return m
26
+ Q1 = load("q1", os.path.join(HERE, "_solution/q1.py"))
27
+ Q2 = load("q2", os.path.join(HERE, "_solution/q2.py"))
28
+
29
+ # ---------- archive extraction ----------
30
+ def _safe_tar(p, d):
31
+ try:
32
+ with tarfile.open(p) as t: t.extractall(d, filter='data')
33
+ except Exception: pass
34
+ def _safe_zip(p, d):
35
+ try:
36
+ with zipfile.ZipFile(p) as z: z.extractall(d)
37
+ except Exception: pass
38
+
39
+ def explode(zdir, dest):
40
+ # final submission first
41
+ sub = os.path.join(zdir, "submission.tar")
42
+ if os.path.exists(sub): _safe_tar(sub, dest)
43
+ if not os.listdir(dest):
44
+ for f in glob.glob(os.path.join(zdir, "*.tar")): _safe_tar(f, dest)
45
+ # already-extracted dirs (e.g. a manually opened ass1/)
46
+ for sub in os.listdir(zdir):
47
+ sp = os.path.join(zdir, sub)
48
+ if os.path.isdir(sp):
49
+ shutil.copytree(sp, os.path.join(dest, "_" + sub), dirs_exist_ok=True)
50
+ # nested zip/tar, a couple levels deep
51
+ for _ in range(3):
52
+ for f in glob.glob(os.path.join(dest, "**", "*.zip"), recursive=True):
53
+ if "__MACOSX" not in f: _safe_zip(f, os.path.dirname(f))
54
+ for f in glob.glob(os.path.join(dest, "**", "*.tar"), recursive=True):
55
+ _safe_tar(f, os.path.dirname(f))
56
+
57
+ # ---------- TESTS extraction (tolerant) ----------
58
+ def _balanced(src, start, op, cl):
59
+ depth = 0; q = None
60
+ for j in range(start, len(src)):
61
+ c = src[j]
62
+ if q:
63
+ if c == q and src[j-1] != '\\': q = None
64
+ continue
65
+ if c in '"\'': q = c; continue
66
+ if c == op: depth += 1
67
+ elif c == cl:
68
+ depth -= 1
69
+ if depth == 0: return j
70
+ return None
71
+
72
+ def _perline(block):
73
+ cases = []
74
+ for raw in block.splitlines():
75
+ s = raw.strip()
76
+ if not s or s.startswith('#') or '(' not in s: continue
77
+ i = s.index('('); end = _balanced(s, i, '(', ')')
78
+ if end is None: continue
79
+ try:
80
+ v = ast.literal_eval(s[i:end+1])
81
+ if isinstance(v, tuple) and len(v) == 2: cases.append(v)
82
+ except Exception: continue
83
+ return cases
84
+
85
+ def extract_tests(src):
86
+ m = re.search(r'^[ \t]*tests?\s*=\s*\[', src, re.M | re.I) # tolerant: TESTS/Tests/tests/TEST
87
+ if not m: return None, "no_TESTS"
88
+ start = src.index('[', m.start())
89
+ end = _balanced(src, start, '[', ']')
90
+ if end is not None:
91
+ try:
92
+ v = ast.literal_eval(src[start:end+1])
93
+ if isinstance(v, (list, tuple)): return list(v), "ok"
94
+ except Exception: pass
95
+ block = src[start+1:end] if end else src[start+1:]
96
+ cases = _perline(block)
97
+ if cases: return cases, "recovered" # e.g. missing-comma syntax error
98
+ return None, "parse_fail"
99
+
100
+ # ---------- which question does a TESTS list belong to? (by content) ----------
101
+ def detect_q(cases):
102
+ si = ii = 0
103
+ for case in cases:
104
+ try: args, exp = case
105
+ except Exception: continue
106
+ if not (isinstance(args, (tuple, list)) and len(args) >= 1): continue
107
+ a0 = args[0]
108
+ if isinstance(a0, str): si += 1 # role -> Q2
109
+ elif isinstance(a0, (int, float)) and not isinstance(a0, bool): ii += 1 # students -> Q1
110
+ if ii > si: return 1
111
+ if si > ii: return 2
112
+ return None
113
+
114
+ # ---------- discover Q1/Q2 test cases: filename first, then by content ----------
115
+ def discover(dest):
116
+ files = [] # (path, cases, status, detected_q)
117
+ for p in glob.glob(os.path.join(dest, "**", "*"), recursive=True):
118
+ if not os.path.isfile(p): continue
119
+ b = os.path.basename(p)
120
+ if b.startswith("._") or "__MACOSX" in p: continue
121
+ if not b.lower().endswith((".py", ".txt")): continue
122
+ try: src = open(p, encoding='utf-8', errors='replace').read()
123
+ except Exception: continue
124
+ cases, st = extract_tests(src)
125
+ if cases: files.append((p, cases, st, detect_q(cases)))
126
+ res = {1: (None, "missing"), 2: (None, "missing")}
127
+ used = set()
128
+ # 1) filename-based (a file named q1* / q2*, prefer "test" + .py)
129
+ for qn in (1, 2):
130
+ named = [f for f in files if f"q{qn}" in os.path.basename(f[0]).lower()]
131
+ named.sort(key=lambda t: (0 if "test" in os.path.basename(t[0]).lower() else 1,
132
+ 0 if t[0].lower().endswith(".py") else 1, len(t[0])))
133
+ if named:
134
+ res[qn] = (named[0][1], named[0][2]); used.add(named[0][0])
135
+ # 2) content-based fallback for whatever is still missing
136
+ for qn in (1, 2):
137
+ if res[qn][0] is None:
138
+ for (p, c, st, dq) in files:
139
+ if p not in used and dq == qn:
140
+ res[qn] = (c, st + "/by-content"); used.add(p); break
141
+ return res
142
+
143
+ # ---------- grade (same rules as the playground) ----------
144
+ def grade(mod, cases):
145
+ caught = set()
146
+ for case in cases:
147
+ try: args, exp = case; args = tuple(args)
148
+ except Exception: continue
149
+ try: ref = mod.reference(*args); bb = mod.blackbox(*args)
150
+ except Exception: continue
151
+ if exp != ref: continue # expected must match spec
152
+ if bb != exp:
153
+ for nm, (fn, _) in mod.BUGS.items():
154
+ try:
155
+ if fn(*args) != ref: caught.add(nm); break
156
+ except Exception: pass
157
+ return len(caught)
158
+
159
+ # ---------- run over all students ----------
160
+ wb = openpyxl.load_workbook(XLSX)
161
+ ws = wb.active
162
+ ids = [(r, ws.cell(r, 1).value) for r in range(2, ws.max_row + 1) if ws.cell(r, 1).value is not None]
163
+
164
+ rows = []
165
+ base = tempfile.mkdtemp()
166
+ for row, sid in ids:
167
+ z = str(int(sid)); zdir = os.path.join(ROOT, z)
168
+ dest = os.path.join(base, z); os.makedirs(dest, exist_ok=True)
169
+ n1 = n2 = None; s1 = s2 = "missing"
170
+ if os.path.isdir(zdir):
171
+ explode(zdir, dest)
172
+ found = discover(dest)
173
+ c1, s1 = found[1]; c2, s2 = found[2]
174
+ if c1 is not None: n1 = grade(Q1, c1)
175
+ if c2 is not None: n2 = grade(Q2, c2)
176
+ rows.append((row, z, n1, s1, n2, s2))
177
+ shutil.rmtree(base, ignore_errors=True)
178
+
179
+ # ---------- write back to xlsx (after backup; keep the FIRST/original backup) ----------
180
+ _bak = XLSX.replace(".xlsx", "_backup.xlsx")
181
+ if not os.path.exists(_bak): shutil.copyfile(XLSX, _bak)
182
+ ws.cell(1, 2, "Q1 (/2.5)"); ws.cell(1, 3, "Q2 (/2.5)"); ws.cell(1, 4, "Total (/5)"); ws.cell(1, 5, "notes")
183
+ flagged = []
184
+ for row, z, n1, s1, n2, s2 in rows:
185
+ q1s = (n1 * 0.5) if isinstance(n1, int) else None
186
+ q2s = (n2 * 0.5) if isinstance(n2, int) else None
187
+ ws.cell(row, 2, q1s if q1s is not None else 0)
188
+ ws.cell(row, 3, q2s if q2s is not None else 0)
189
+ ws.cell(row, 4, (q1s or 0) + (q2s or 0))
190
+ note = []
191
+ if n1 is None: note.append("Q1:" + s1)
192
+ elif s1 == "recovered": note.append("Q1:recovered(syntax fixed)")
193
+ if n2 is None: note.append("Q2:" + s2)
194
+ elif s2 == "recovered": note.append("Q2:recovered(syntax fixed)")
195
+ if note: ws.cell(row, 5, "; ".join(note)); flagged.append((z, "; ".join(note)))
196
+ wb.save(XLSX)
197
+
198
+ # ---------- report ----------
199
+ ok = sum(1 for r in rows if isinstance(r[2], int) and isinstance(r[4], int))
200
+ print(f"graded {len(rows)} students; both questions auto-scored for {ok}")
201
+ d1 = collections.Counter(r[2] for r in rows if isinstance(r[2], int))
202
+ d2 = collections.Counter(r[4] for r in rows if isinstance(r[4], int))
203
+ print("Q1 bug-count distribution:", dict(sorted(d1.items())))
204
+ print("Q2 bug-count distribution:", dict(sorted(d2.items())))
205
+ print(f"\nflagged for manual review ({len(flagged)}):")
206
+ for z, note in flagged: print(f" {z}: {note}")
207
+ print(f"\nwrote scores to {XLSX} (backup: {XLSX.replace('.xlsx','_backup.xlsx')})")
index.html CHANGED
@@ -60,6 +60,10 @@
60
  Assignment 2
61
  <span class="sub">Decision tables · CFG · loops</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>
 
60
  Assignment 2
61
  <span class="sub">Decision tables · CFG · loops</span>
62
  </button>
63
+ <button class="item" data-src="assignment3.html">
64
+ Assignment 3
65
+ <span class="sub">Scaffolding · combinatorial · mutation</span>
66
+ </button>
67
  <div class="spacer"></div>
68
  <div class="foot">Pick an assignment on the left.<br>Assignment 2 has an interactive Q4 and a JSON export.</div>
69
  </nav>