File size: 26,773 Bytes
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae252bf
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae252bf
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
ae252bf
443f404
 
ae252bf
443f404
 
 
ae252bf
443f404
 
 
 
 
 
 
 
 
ae252bf
443f404
 
 
 
 
 
ae252bf
443f404
 
 
ae252bf
443f404
 
 
 
 
 
ae252bf
443f404
 
 
 
 
 
 
 
ae252bf
443f404
 
 
 
 
ae252bf
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae252bf
443f404
 
 
ae252bf
443f404
 
 
 
 
 
 
ae252bf
443f404
 
 
ae252bf
443f404
 
 
 
 
 
 
 
ae252bf
 
 
 
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
7d0ac5e
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69619e7
 
 
 
 
 
 
 
 
 
 
 
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69619e7
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7255c53
 
9d8645a
 
 
7255c53
 
9d8645a
443f404
 
 
 
 
7255c53
 
 
 
 
 
 
 
 
 
 
 
 
443f404
 
9d8645a
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b89117c
 
 
 
 
 
 
 
 
443f404
 
 
b89117c
 
 
 
 
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assignment 3 — Software Testing</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css">
<style>
  :root {
    --bg:#1e1e2e; --panel:#252535; --card:#22222f; --border:#353550;
    --accent:#89b4fa; --accent-hover:#74a0f0;
    --text:#cdd6f4; --muted:#7f849c; --err:#f38ba8; --ok:#a6e3a1; --warn:#f9e2af;
  }
  * { box-sizing:border-box; }
  html,body { margin:0; }
  body {
    font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
    background:var(--bg); color:var(--text); line-height:1.55; font-size:14px;
  }
  .wrap { max-width:980px; margin:0 auto; padding:24px 28px 120px; }
  h1 { font-size:22px; margin:0 0 4px; }
  h2 { font-size:18px; margin:34px 0 6px; padding-top:14px; border-top:1px solid var(--border); }
  h3 { font-size:14px; color:var(--accent); margin:18px 0 6px; }
  .pts { font-size:12px; color:var(--muted); font-weight:500; }
  p { margin:8px 0; }
  code, .mono { font-family:"SF Mono",Menlo,Consolas,monospace; }
  pre { background:#181825; border:1px solid var(--border); border-radius:8px; padding:12px 14px; overflow:auto; font-size:13px; }
  .muted { color:var(--muted); }
  table.spec { border-collapse:collapse; font-size:13px; margin:8px 0; }
  table.spec th, table.spec td { border:1px solid var(--border); padding:5px 10px; text-align:left; }
  table.spec th { background:var(--panel); }
  a { color:var(--accent); }

  /* option card with radio/checkbox */
  .opt {
    border:1px solid var(--border); border-radius:10px; padding:10px 14px; margin:10px 0;
    background:var(--card); transition:border-color .12s, background .12s;
  }
  .opt.sel { border-color:var(--accent); background:#262a3f; }
  .opt-head { display:flex; align-items:center; gap:10px; cursor:pointer; font-weight:600; }
  .opt-head input { width:16px; height:16px; accent-color:var(--accent); cursor:pointer; }
  .opt-body { margin-top:8px; overflow:auto; }
  .opt-body pre { margin:0; }

  /* fill-in blanks */
  input.blank {
    width:220px; text-align:center; background:#181825; color:var(--ok);
    border:1px solid var(--border); border-radius:5px; padding:2px 6px;
    font-family:"SF Mono",Menlo,Consolas,monospace; font-size:13px; font-weight:600;
  }
  input.blank:focus { outline:none; border-color:var(--accent); }
  input.blank.short { width:70px; }
  input.txt {
    background:#181825; color:var(--text); border:1px solid var(--border);
    border-radius:6px; padding:7px 10px; font-size:13px;
    font-family:"SF Mono",Menlo,Consolas,monospace;
  }
  input.txt:focus { outline:none; border-color:var(--accent); }

  button {
    background:var(--accent); color:#11111b; border:none; padding:8px 16px;
    border-radius:7px; font-size:13px; font-weight:700; cursor:pointer; transition:background .15s;
  }
  button:hover:not(:disabled){ background:var(--accent-hover); }
  button:disabled { opacity:.5; cursor:not-allowed; }
  button.ghost { background:transparent; color:var(--muted); border:1px solid var(--border); }
  button.ghost:hover:not(:disabled){ color:var(--text); }

  /* Q4.2 code editor */
  .pg { border:1px solid var(--border); border-radius:10px; overflow:hidden; margin:12px 0; background:var(--card); }
  .pg-head { display:flex; align-items:center; gap:10px; padding:8px 12px; background:var(--panel); border-bottom:1px solid var(--border); flex-wrap:wrap; }
  .CodeMirror { height:auto; min-height:170px; font-size:13px; font-family:"SF Mono",Menlo,Consolas,monospace; }

  /* sticky export bar */
  .exportbar {
    position:fixed; left:0; right:0; bottom:0; background:var(--panel);
    border-top:1px solid var(--border); padding:10px 28px;
    display:flex; align-items:center; gap:14px; z-index:10;
  }
  .exportbar .sid { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--muted); }
  .exportbar .spacer { flex:1; }
  .toast { font-size:12px; color:var(--ok); }

  /* ===== left vertical tabs (Ant style) ===== */
  .layout { display:flex; gap:20px; align-items:flex-start; margin-top:16px; }
  .tabs { flex:0 0 190px; display:flex; flex-direction:column; gap:5px;
          position:sticky; top:16px; }
  .tabs button { background:transparent; color:var(--muted); border:none;
          border-left:3px solid transparent; border-radius:8px;
          padding:11px 14px; font-size:14px; font-weight:600; cursor:pointer;
          text-align:left; width:100%; white-space:nowrap;
          transition:color .15s, background .15s, border-color .15s; }
  .tabs button:hover:not(:disabled) { background:var(--panel); color:var(--text); }
  .tabs button.active { color:var(--accent); background:var(--card);
          border-left-color:var(--accent); border-radius:0 8px 8px 0; }
  .panes { flex:1; min-width:0; }
  .pane { display:none; }
  .pane.active { display:block; animation:tabfade .22s ease;
          background:var(--panel); border:1px solid var(--border);
          border-radius:12px; padding:20px 24px; }
  @keyframes tabfade { from{opacity:0; transform:translateY(4px)} to{opacity:1; transform:none} }
  .pane h2:first-child { margin-top:0; border-top:none; padding-top:0; }
</style>
</head>
<body>
<div class="wrap">
  <h1>Assignment 3: Software Testing <span class="pts" style="font-size:13px">[25 pts total]</span></h1>
  <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>

  <div class="layout">
  <div class="tabs" id="tabbar">
    <button data-tab="q1" class="active">Q1 · Test Scaffolding</button>
    <button data-tab="q2">Q2 · Combinatorial</button>
    <button data-tab="q3">Q3 · Integration</button>
    <button data-tab="q4">Q4 · Metamorphic &amp; Mutation</button>
    <button data-tab="q5">Q5 · Coverage Fuzzing</button>
  </div>
  <div class="panes">

  <!-- ============ Q1 ============ -->
  <section class="pane active" data-tab="q1">
  <h2>Q1 Test Scaffolding Concepts <span class="pts">[2 pts]</span></h2>
  <p class="muted">Multiple answers may apply unless otherwise stated.</p>

  <h3>Q1.1 <span class="pts">[1 pt]</span></h3>
  <p>Which of the following may be used as test scaffolding?</p>
  <div id="q11opts"></div>

  <h3>Q1.2 <span class="pts">[1 pt]</span></h3>
  <p>Consider the following test scaffolding code.</p>
  <pre id="q12code"></pre>
  <p>The real data source has not yet been integrated. During the test, <code>FixedDataSource</code> supplies predefined records to <code>ReportGenerator</code>.</p>
  <p>How should <code>FixedDataSource</code> be classified?</p>
  <div id="q12opts"></div>
  </section>

  <!-- ============ Q2 ============ -->
  <section class="pane" data-tab="q2">
  <h2>Q2 Combinatorial Testing <span class="pts">[4 pts]</span></h2>
  <p>A web application supports the following parameters:</p>
  <pre>Browser:        Chrome, Firefox
Authentication: Password, SSO
Region:         AU, US</pre>
  <p>Exactly one option is correct for each question.</p>

  <h3>Q2.1 Selecting a Pairwise Covering Array <span class="pts">[2 pts]</span></h3>
  <p>Which option is a smallest pairwise covering array?</p>
  <div id="q21opts"></div>

  <h3>Q2.2 Increasing the Interaction Strength <span class="pts">[2 pts]</span></h3>
  <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>
  <div id="q22opts"></div>
  </section>

  <!-- ============ Q3 ============ -->
  <section class="pane" data-tab="q3">
  <h2>Q3 Integration Testing <span class="pts">[5 pts]</span></h2>
  <p>Consider a system with the following dependencies:</p>
  <pre>CheckoutController
        |
        v
OrderService
   |           |
   v           v
InventoryService   PaymentGateway</pre>
  <p>Fill in the blanks. <span class="pts">[1 pt each, 5 blanks]</span></p>
  <div id="q3block" style="line-height:2.2"></div>
  </section>

  <!-- ============ Q4 ============ -->
  <section class="pane" data-tab="q4">
  <h2>Q4 Metamorphic Oracle and Mutation Testing <span class="pts">[8 pts]</span></h2>
  <p>Consider the following program.</p>
  <pre id="q4prog"></pre>

  <p>Initial test suite:</p>
  <pre id="q4tests"></pre>

  <p>Assume that none of the following mutants is equivalent to the original program.</p>
  <table class="spec">
    <tr><th>Mutant</th><th>Change</th></tr>
    <tr><td>M1</td><td><code>hours &gt;= 8</code> &rarr; <code>hours &gt; 8</code></td></tr>
    <tr><td>M2</td><td><code>fee = 14</code> &rarr; <code>fee = 15</code></td></tr>
    <tr><td>M3</td><td><code>if weekend</code> &rarr; <code>if not weekend</code></td></tr>
    <tr><td>M4</td><td><code>fee -= 2</code> &rarr; <code>fee -= 1</code></td></tr>
  </table>

  <h3>Q4.1 Mutant Status <span class="pts">[2 pts]</span></h3>
  <p>For each mutant, write <code>Killed</code> or <code>Survived</code> under the initial test suite.</p>
  <div id="q41block" style="line-height:2.2"></div>

  <h3>Q4.2 Metamorphic Test Oracle <span class="pts">[2 pts]</span></h3>
  <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>
  <p>Complete the metamorphic oracle. It may call <code>parking_fee</code> exactly twice and must not directly assert a particular fee value.</p>
  <div class="pg">
    <div class="pg-head"><b>Your answer</b></div>
    <textarea id="q42code"></textarea>
  </div>

  <h3>Q4.3 Mutation Score <span class="pts">[2 pts]</span></h3>
  <p>Compute the mutation score of the initial test suite.</p>
  <div id="q43block" style="line-height:2.2"></div>

  <h3>Q4.4 Improving the Test Suite <span class="pts">[2 pts]</span></h3>
  <p>Give one source input and its metamorphic follow-up that kill every mutant surviving the initial test suite.</p>
  <div id="q44block" style="line-height:2.2"></div>
  <p>Then write the corresponding direct regression test.</p>
  <div id="q44assert" style="line-height:2.2"></div>
  </section>

  <!-- ============ Q5 ============ -->
  <section class="pane" data-tab="q5" style="padding:0;overflow:hidden">
  <div style="padding:24px 28px 0">
    <h2 style="margin-top:0;padding-top:0;border-top:none">Q5 Coverage-Guided Fuzzing <span class="pts">[6 pts]</span></h2>
    <p class="muted">2.5 pts for each of the two bugs found, plus 1 pt for reaching full edge coverage.</p>
  </div>
  <iframe src="coverage_fuzzing/index.html" title="Q5 Coverage-Guided Fuzzing"
          style="width:100%;height:1500px;border:0;display:block;border-radius:12px"></iframe>
  </section>

  </div><!-- /.panes -->
  </div><!-- /.layout -->
</div>

<!-- ============ sticky export bar ============ -->
<div class="exportbar">
  <div class="sid">Student ID <input class="txt" id="studentId" placeholder="z1234567" style="width:130px"></div>
  <div class="spacer"></div>
  <span class="toast" id="toast"></span>
  <button class="ghost" id="clearBtn">Clear saved</button>
  <button class="ghost" id="previewBtn">Force save</button>
  <button class="ghost" id="copyBtn">Copy JSON</button>
  <button id="exportBtn">⤓ Export JSON</button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script>
<script>
const answers = { q11:[], q12:null, q21:null, q22:null, q3:{}, q41:{}, q43:{}, q44:{}, q44assert:{} };

function buildChoice(host, name, items, onSel){
  host.innerHTML = "";
  for (const it of items){
    const card = document.createElement("div"); card.className = "opt";
    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>` : ""}`;
    const radio = card.querySelector("input");
    radio.onchange = () => {
      [...host.querySelectorAll(".opt")].forEach(o=>o.classList.remove("sel"));
      card.classList.add("sel"); onSel(it.val);
    };
    host.appendChild(card);
  }
}
function buildMulti(host, name, items, arr, onChange){
  host.innerHTML = "";
  for (const it of items){
    const card = document.createElement("div"); card.className = "opt";
    card.innerHTML = `<label class="opt-head"><input type="checkbox" name="${name}" value="${it.val}"><span>${it.label}</span></label>`;
    const cb = card.querySelector("input");
    cb.onchange = () => {
      card.classList.toggle("sel", cb.checked);
      const i = arr.indexOf(it.val);
      if (cb.checked && i === -1) arr.push(it.val);
      if (!cb.checked && i !== -1) arr.splice(i,1);
      onChange();
    };
    host.appendChild(card);
  }
}

// ============ Q1.1 (multi-select) ============
buildMulti(document.getElementById("q11opts"), "q11", [
  {val:"a", label:"a. A production database containing real customer data"},
  {val:"b", label:"b. A driver that invokes a program unit whose caller is not yet available"},
  {val:"c", label:"c. A stub that substitutes for unavailable system functionality"},
  {val:"d", label:"d. Code that must remain permanently in the deployed product"},
], answers.q11, saveSession);

// ============ Q1.2 ============
document.getElementById("q12code").textContent =
`class ReportGenerator:
    def __init__(self, data_source):
        self.data_source = data_source

    def generate_summary(self, report_id):
        records = self.data_source.fetch_records(report_id)

        if len(records) == 0:
            return "No records found"

        total = sum(record["value"] for record in records)
        return f"{len(records)} records, total value: {total}"


class FixedDataSource:
    def fetch_records(self, report_id):
        return [
            {"name": "Item A", "value": 20},
            {"name": "Item B", "value": 30},
        ]


def test_generate_summary():
    data_source = FixedDataSource()
    generator = ReportGenerator(data_source)

    result = generator.generate_summary("weekly-report")

    assert result == "2 records, total value: 50"`;

buildChoice(document.getElementById("q12opts"), "q12", [
  {val:"a", label:"a. stub"},
  {val:"b", label:"b. driver"},
], v => { answers.q12 = v; saveSession(); });

// ============ Q2.1 ============
const Q21_BLOCKS = {
  A: "Chrome   Password   AU\nChrome   SSO        US\nFirefox  Password   US",
  B: "Chrome   Password   AU\nChrome   SSO        US\nFirefox  Password   US\nFirefox  SSO        AU",
  C: "Chrome   Password   AU\nChrome   Password   US\nFirefox  SSO        AU\nFirefox  SSO        US",
  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",
};
buildChoice(document.getElementById("q21opts"), "q21",
  ["A","B","C","D"].map(k => ({val:k, label:k, body:`<pre>${Q21_BLOCKS[k]}</pre>`})),
  v => { answers.q21 = v; saveSession(); });

// ============ Q2.2 ============
buildChoice(document.getElementById("q22opts"), "q22", [
  {val:"a", label:"a. 4"},
  {val:"b", label:"b. 6"},
  {val:"c", label:"c. 8"},
  {val:"d", label:"d. 12"},
], v => { answers.q22 = v; saveSession(); });

// ============ generic blank-template builder ============
// Template text with @n@ placeholders -> replaced with <input class="blank">.
// widthClass: "short" for small numeric-ish blanks, "" (default) for long blanks.
function buildBlanks(host, text, store, widthClass){
  host.innerHTML = ""; host.style.whiteSpace = "pre-wrap";
  const parts = text.split(/@(\d+)@/);
  for (let i=0;i<parts.length;i++){
    if (i % 2 === 0){ host.appendChild(document.createTextNode(parts[i])); }
    else {
      const n = parts[i];
      const inp = document.createElement("input");
      inp.className = "blank" + (widthClass ? " " + widthClass : "");
      inp.dataset.n = n; inp.title = "blank " + n;
      inp.oninput = () => { store[n] = inp.value; saveSession(); };
      host.appendChild(inp);
    }
  }
}

// ============ Q3: 5 fill-in blanks ============
const Q3_TEXT =
`1. Integrating and testing high-level modules before lower-level modules is called @1@ integration testing.

2. During this strategy, unavailable lower-level modules are commonly replaced by @2@.

3. Integrating low-level modules first commonly requires @3@ to invoke them before their callers are available.

4. Integrating all components at the same time is called @4@ integration testing.

5. Restricting one integration test session to only \`OrderService\` and \`PaymentGateway\` corresponds to @5@ integration.`;
buildBlanks(document.getElementById("q3block"), Q3_TEXT, answers.q3);

// ============ Q4 reference program + tests (static) ============
document.getElementById("q4prog").textContent =
`def parking_fee(
    hours: int,
    weekend: bool,
    member: bool,
) -> int:
    if hours <= 0:
        raise ValueError("hours must be positive")

    if hours >= 8:
        fee = 20
    elif hours >= 4:
        fee = 14
    else:
        fee = 8

    if weekend:
        fee += 3

    if member:
        fee -= 2

    return fee`;

document.getElementById("q4tests").textContent =
`TESTS = [
    ((10, False, False), 20),
    ((5, False, False), 14),
    ((2, True, False), 11),
    ((5, False, True), 12),
]`;

// ============ Q4.1: 4 blanks ============
const Q41_TEXT = `M1: @1@
M2: @2@
M3: @3@
M4: @4@`;
buildBlanks(document.getElementById("q41block"), Q41_TEXT, answers.q41, "short");

// ============ Q4.2: code editor ============
const Q42_SKELETON =
`def capped_parking_fee_mr_oracle(
    hours: int,
    increase: int,
    weekend: bool,
    member: bool,
) -> bool:
    if hours < 8 or increase <= 0:
        raise ValueError("invalid metamorphic test input")

    # Complete this function
    pass`;
const q42editor = CodeMirror.fromTextArea(document.getElementById("q42code"), {
  mode:"python", theme:"material-darker", lineNumbers:true, indentUnit:4, tabSize:4,
  extraKeys:{ Tab:cm=>cm.replaceSelection("    ") },
});
q42editor.setValue(Q42_SKELETON);
q42editor.on("change", () => saveSession());

// ============ Q4.3: 3 blanks (mutation score) ============
const Q43_TEXT =
`mutation score = killed non-equivalent mutants / total non-equivalent mutants
               = @1@ / @2@
               = @3@ %`;
buildBlanks(document.getElementById("q43block"), Q43_TEXT, answers.q43, "short");

// ============ Q4.4: source/follow-up blanks + regression assert ============
const Q44_TEXT =
`source input:
    hours = @1@
    weekend = @2@
    member = @3@

transformation:
    increase = @4@

follow-up input:
    hours = @5@
    weekend = @6@
    member = @7@

source output from the surviving mutant = @8@
follow-up output from the surviving mutant = @9@`;
buildBlanks(document.getElementById("q44block"), Q44_TEXT, answers.q44, "short");

const Q44_ASSERT_TEXT = `assert parking_fee(@1@, @2@, @3@) == @4@`;
buildBlanks(document.getElementById("q44assert"), Q44_ASSERT_TEXT, answers.q44assert, "short");

// ============ JSON export ============
function getQ5State(){
  try {
    const win = document.querySelector('iframe[title="Q5 Coverage-Guided Fuzzing"]').contentWindow;
    return {
      fuzz_py: win.__editor ? win.__editor.getValue() : "",
      crash_bug1_hex: (win.__crashes && win.__crashes.bug1) || "",
      crash_bug2_hex: (win.__crashes && win.__crashes.bug2) || "",
    };
  } catch (_) {
    return { fuzz_py: "", crash_bug1_hex: "", crash_bug2_hex: "" };
  }
}
function buildJSON(){
  return {
    assignment: "Assignment 3: Software Testing",
    student_id: document.getElementById("studentId").value.trim(),
    answers: {
      q1: {
        1: answers.q11.slice(),
        2: answers.q12 || "",
      },
      q2: {
        1: answers.q21 || "",
        2: answers.q22 || "",
      },
      q3: Object.assign({1:"",2:"",3:"",4:"",5:""}, answers.q3),
      q4: {
        1: Object.assign({1:"",2:"",3:"",4:""}, answers.q41),
        2: q42editor.getValue(),
        3: Object.assign({1:"",2:"",3:""}, answers.q43),
        4: {
          source_followup: Object.assign({1:"",2:"",3:"",4:"",5:"",6:"",7:"",8:"",9:""}, answers.q44),
          regression_assert: Object.assign({1:"",2:"",3:"",4:""}, answers.q44assert),
        },
      },
      q5: getQ5State(),
    }
  };
}
function toast(msg){ const t=document.getElementById("toast"); t.textContent=msg; setTimeout(()=>t.textContent="",2500); }
document.getElementById("exportBtn").onclick = () => {
  const data = JSON.stringify(buildJSON(), null, 2);
  const blob = new Blob([data], {type:"application/json"});
  const a = document.createElement("a");
  const sid = document.getElementById("studentId").value.trim() || "submission";
  a.href = URL.createObjectURL(blob); a.download = `assignment3_${sid}.json`;
  a.click(); URL.revokeObjectURL(a.href); toast("Exported ✓");
};
document.getElementById("copyBtn").onclick = async () => {
  try { await navigator.clipboard.writeText(JSON.stringify(buildJSON(), null, 2)); toast("Copied ✓"); }
  catch(_){ toast("Copy failed"); }
};

// ============ force-save ============
// If you're ever unsure whether Copy/Export reflects your latest edit, click
// this: it writes the session immediately instead of waiting for the debounce.
document.getElementById("previewBtn").onclick = () => {
  flushSession();
  toast("Saved ✓");
};

// ============ local session (auto-save / restore) ============
const SESSION_KEY = "st_a3_session_v1";
let __saveTimer = null;
function flushSession(){
  clearTimeout(__saveTimer);
  try {
    const d = {
      ts: Date.now(),
      studentId: document.getElementById("studentId").value,
      q11: answers.q11, q12: answers.q12, q21: answers.q21, q22: answers.q22,
      q3: answers.q3, q41: answers.q41, q43: answers.q43, q44: answers.q44, q44assert: answers.q44assert,
      q42code: q42editor.getValue(),
    };
    localStorage.setItem(SESSION_KEY, JSON.stringify(d));
  } catch(_){}
}
function saveSession(){
  clearTimeout(__saveTimer);
  __saveTimer = setTimeout(flushSession, 250);
}
function restoreRadio(name, val){
  if (!val) return;
  const r = document.querySelector(`input[name="${name}"][value="${val}"]`);
  if (r){ r.checked = true; const opt = r.closest(".opt"); if (opt) opt.classList.add("sel"); }
}
function restoreCheckboxes(name, arr){
  if (!arr || !arr.length) return;
  for (const v of arr){
    const cb = document.querySelector(`input[name="${name}"][value="${v}"]`);
    if (cb){ cb.checked = true; const opt = cb.closest(".opt"); if (opt) opt.classList.add("sel"); }
  }
}
function restoreBlanks(host, obj){
  if (!obj) return;
  host.querySelectorAll("input.blank").forEach(inp => { const v = obj[inp.dataset.n]; if (v != null) inp.value = v; });
}
function loadSession(){
  let d;
  try { d = JSON.parse(localStorage.getItem(SESSION_KEY)); } catch(_){ return; }
  if (!d) return;
  document.getElementById("studentId").value = d.studentId || "";
  // Mutate the EXISTING answers.qXX object/array in place (Object.assign(target, ...)
  // / length=0+push) rather than reassigning answers.qXX to a brand-new one. The
  // input/checkbox event handlers wired up earlier (buildBlanks, buildMulti) closed
  // over the original object by reference; reassigning answers.qXX here would silently
  // orphan that reference, so every future keystroke/click would write into the old,
  // now-unreachable object while answers.qXX (and thus buildJSON()) stayed frozen at
  // whatever was restored here -- exactly the bug that made Copy/Export appear to
  // "stop updating" after a page reload.
  if (d.q11){ answers.q11.length = 0; answers.q11.push(...d.q11); restoreCheckboxes("q11", d.q11); }
  answers.q12 = d.q12 || null; restoreRadio("q12", d.q12);
  answers.q21 = d.q21 || null; restoreRadio("q21", d.q21);
  answers.q22 = d.q22 || null; restoreRadio("q22", d.q22);
  if (d.q3){ Object.assign(answers.q3, d.q3); restoreBlanks(document.getElementById("q3block"), d.q3); }
  if (d.q41){ Object.assign(answers.q41, d.q41); restoreBlanks(document.getElementById("q41block"), d.q41); }
  if (d.q43){ Object.assign(answers.q43, d.q43); restoreBlanks(document.getElementById("q43block"), d.q43); }
  if (d.q44){ Object.assign(answers.q44, d.q44); restoreBlanks(document.getElementById("q44block"), d.q44); }
  if (d.q44assert){ Object.assign(answers.q44assert, d.q44assert); restoreBlanks(document.getElementById("q44assert"), d.q44assert); }
  if (d.q42code) q42editor.setValue(d.q42code);

  let ago = "earlier";
  if (d.ts){ const mins = Math.round((Date.now() - d.ts) / 60000);
    ago = mins < 1 ? "just now" : mins < 60 ? mins + " min ago" : mins < 1440 ? Math.round(mins/60) + " h ago" : Math.round(mins/1440) + " d ago"; }
  const b = document.createElement("div");
  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)";
  b.innerHTML = `↺ Restored your answers from this browser (saved ${ago}). They stay saved in this browser until you press Clear. `;
  const x = document.createElement("button"); x.textContent = "Clear & start fresh"; x.className = "ghost";
  x.style.cssText = "padding:3px 10px;font-size:11px;margin-left:6px";
  x.onclick = clearSession;
  b.appendChild(x);
  const wrap = document.querySelector(".wrap");
  wrap.insertBefore(b, wrap.children[2]);
}
function clearSession(){ localStorage.removeItem(SESSION_KEY); location.reload(); }
document.getElementById("studentId").addEventListener("input", saveSession);
document.getElementById("clearBtn").onclick = clearSession;
loadSession();

// ============ tabs (one per question) ============
(function initTabs(){
  const TAB_KEY = "st_a3_tab";
  const btns  = [...document.querySelectorAll("#tabbar button")];
  const panes = [...document.querySelectorAll(".pane")];
  function show(id){
    if (!btns.some(b => b.dataset.tab === id)) id = "q1";
    btns.forEach(b => b.classList.toggle("active", b.dataset.tab === id));
    panes.forEach(p => p.classList.toggle("active", p.dataset.tab === id));
    try { localStorage.setItem(TAB_KEY, id); } catch(_){}
    if (id === "q4" && typeof q42editor !== "undefined" && q42editor) setTimeout(() => q42editor.refresh(), 0);
    window.scrollTo(0, 0);
  }
  btns.forEach(b => b.onclick = () => show(b.dataset.tab));
  show(localStorage.getItem(TAB_KEY) || "q1");
})();
</script>
</body>
</html>