scriptmark 0.2.0

Automated grading CLI for student programming assignments
Documentation
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
use std::collections::HashMap;
use std::io::Write;

use scriptmark::models::*;
use scriptmark::runner::orchestrator;
use scriptmark::runner::python::PythonExecutor;

fn setup_test_dir() -> tempfile::TempDir {
	let dir = tempfile::tempdir().unwrap();

	// Student "alice" — correct implementation
	std::fs::write(
		dir.path().join("alice_lab5.py"),
		r#"
def find_larger_number(a, b):
    if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
        raise TypeError("Arguments must be numbers")
    return max(a, b)
"#,
	)
	.unwrap();

	// Student "bob" — buggy implementation (returns min instead of max)
	std::fs::write(
		dir.path().join("bob_lab5.py"),
		r#"
def find_larger_number(a, b):
    if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
        raise TypeError("Arguments must be numbers")
    return min(a, b)
"#,
	)
	.unwrap();

	dir
}

fn test_spec() -> TestSpec {
	toml::from_str(
		r#"
[meta]
name = "find_larger_number"
file = "lab5.py"
function = "find_larger_number"
language = "python"

[[cases]]
name = "3 < 5"
args = [3, 5]
expect = 5

[[cases]]
name = "equal zero"
args = [0, 0]
expect = 0

[[cases]]
name = "negative"
args = [-3, -2]
expect = -2

[[cases]]
name = "invalid type"
args = ["a", 1]
expect_error = "TypeError"
"#,
	)
	.unwrap()
}

#[tokio::test]
async fn test_python_executor_correct_student() {
	let dir = setup_test_dir();
	let executor = PythonExecutor::new();

	let files = vec![StudentFile {
		path: dir.path().join("alice_lab5.py"),
		language: "python".to_string(),
	}];

	let spec = test_spec();

	// Test correct answers
	let result = executor
		.execute_case(&files, &spec, &spec.cases[0], 10)
		.await;
	assert_eq!(result.status, TestStatus::Passed, "case: 3 < 5");

	let result = executor
		.execute_case(&files, &spec, &spec.cases[1], 10)
		.await;
	assert_eq!(result.status, TestStatus::Passed, "case: equal zero");

	let result = executor
		.execute_case(&files, &spec, &spec.cases[2], 10)
		.await;
	assert_eq!(result.status, TestStatus::Passed, "case: negative");

	// Test expected error
	let result = executor
		.execute_case(&files, &spec, &spec.cases[3], 10)
		.await;
	assert_eq!(
		result.status,
		TestStatus::Passed,
		"case: invalid type should raise TypeError"
	);
}

#[tokio::test]
async fn test_python_executor_buggy_student() {
	let dir = setup_test_dir();
	let executor = PythonExecutor::new();

	let files = vec![StudentFile {
		path: dir.path().join("bob_lab5.py"),
		language: "python".to_string(),
	}];

	let spec = test_spec();

	// "3 < 5" — bob returns min(3,5)=3, expected 5 → FAIL
	let result = executor
		.execute_case(&files, &spec, &spec.cases[0], 10)
		.await;
	assert_eq!(
		result.status,
		TestStatus::Failed,
		"bob: 3<5 should fail (returns min)"
	);

	// "equal zero" — min(0,0)=0, expected 0 → PASS (edge case)
	let result = executor
		.execute_case(&files, &spec, &spec.cases[1], 10)
		.await;
	assert_eq!(
		result.status,
		TestStatus::Passed,
		"bob: equal zero still passes"
	);

	// TypeError case — bob has type checking, so this passes
	let result = executor
		.execute_case(&files, &spec, &spec.cases[3], 10)
		.await;
	assert_eq!(
		result.status,
		TestStatus::Passed,
		"bob: TypeError still passes"
	);
}

#[tokio::test]
async fn test_orchestrator_runs_all_students() {
	let dir = setup_test_dir();
	let executor = PythonExecutor::new();

	let submissions = SubmissionSet {
		by_student: HashMap::from([
			(
				"alice".to_string(),
				vec![StudentFile {
					path: dir.path().join("alice_lab5.py"),
					language: "python".to_string(),
				}],
			),
			(
				"bob".to_string(),
				vec![StudentFile {
					path: dir.path().join("bob_lab5.py"),
					language: "python".to_string(),
				}],
			),
		]),
	};

	let specs = vec![test_spec()];

	let results = orchestrator::run_all(&submissions, &specs, &executor, 10, Some(2)).await;

	assert_eq!(results.len(), 2);
	assert!(results.contains_key("alice"));
	assert!(results.contains_key("bob"));

	let alice = &results["alice"];
	assert_eq!(alice.status(), TestStatus::Passed);
	assert_eq!(alice.total_cases(), 4);
	assert_eq!(alice.total_passed(), 4);

	let bob = &results["bob"];
	assert_eq!(bob.status(), TestStatus::Failed);
	assert_eq!(bob.total_cases(), 4);
	// bob returns min instead of max: fails on "3<5" and "negative", passes "equal zero" and "TypeError"
	assert_eq!(bob.total_passed(), 2);
}

#[tokio::test]
async fn test_missing_file() {
	let _dir = setup_test_dir();
	let executor = PythonExecutor::new();

	// Empty file list — no matching file
	let files: Vec<StudentFile> = vec![];
	let spec = test_spec();

	let result = executor
		.execute_case(&files, &spec, &spec.cases[0], 10)
		.await;
	assert_eq!(result.status, TestStatus::Error);
	assert!(result.failure.unwrap().message.contains("No file matching"));
}

#[tokio::test]
async fn test_fixtures_and_refs() {
	let dir = tempfile::tempdir().unwrap();

	// Student code with two functions: make_pair returns [a,b], sum_pair sums a pair
	std::fs::write(
		dir.path().join("alice_math.py"),
		r#"
def make_pair(a, b):
    return [a, b]

def sum_pair(pair):
    return pair[0] + pair[1]
"#,
	)
	.unwrap();

	// TOML spec with setup + $ref
	let spec: TestSpec = toml::from_str(
		r#"
[meta]
name = "math_pipeline"
file = "math.py"
language = "python"

[[setup]]
id = "pair"
function = "make_pair"
args = [3, 7]

[[cases]]
name = "sum of setup pair"
function = "sum_pair"
args = ["$pair"]
expect = 10
"#,
	)
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_math.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;

	let alice = &results["alice"];
	assert_eq!(alice.total_cases(), 1);
	assert_eq!(
		alice.test_results[0].cases[0].status,
		TestStatus::Passed,
		"sum_pair($pair) should pass with fixture pair=[3,7] → sum=10"
	);
}

#[tokio::test]
async fn test_vars_as_refs() {
	let dir = tempfile::tempdir().unwrap();

	std::fs::write(
		dir.path().join("alice_echo.py"),
		r#"
def echo(x):
    return x
"#,
	)
	.unwrap();

	let spec: TestSpec = toml::from_str(
		r#"
[meta]
name = "echo_test"
file = "echo.py"
language = "python"

[vars]
msg = "hello world"

[[cases]]
name = "echo var ref"
function = "echo"
args = ["$msg"]
expect = "hello world"
"#,
	)
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_echo.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];
	assert_eq!(alice.test_results[0].cases[0].status, TestStatus::Passed);
}

#[tokio::test]
async fn test_vars_injected_as_python_globals() {
	let dir = tempfile::tempdir().unwrap();

	// Student code accesses a global variable defined by the teacher
	std::fs::write(
		dir.path().join("alice_config.py"),
		r#"
def get_epsilon():
    return EPSILON  # This global is injected by vars
"#,
	)
	.unwrap();

	let spec: TestSpec = toml::from_str(
		r#"
[meta]
name = "config_test"
file = "config.py"
language = "python"

[vars]
EPSILON = 0.001

[[cases]]
name = "student reads injected global"
function = "get_epsilon"
args = []
expect = 0.001
"#,
	)
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_config.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];
	assert_eq!(
		alice.test_results[0].cases[0].status,
		TestStatus::Passed,
		"Student should be able to access EPSILON global injected by vars"
	);
}

#[tokio::test]
async fn test_parametrize_with_reference_oracle() {
	let dir = tempfile::tempdir().unwrap();

	// Student — correct max implementation
	std::fs::write(
		dir.path().join("alice_lab5.py"),
		"def find_max(a, b):\n    return max(a, b)\n",
	)
	.unwrap();

	// Teacher reference implementation (the oracle)
	let solutions_dir = dir.path().join("solutions");
	std::fs::create_dir(&solutions_dir).unwrap();
	std::fs::write(
		solutions_dir.join("lab5.py"),
		"def find_max(a, b):\n    return max(a, b)\n",
	)
	.unwrap();

	let spec: TestSpec = toml::from_str(&format!(
		r#"
[meta]
name = "parametrized_max"
file = "lab5.py"
function = "find_max"
language = "python"

[[cases]]
name = "random max"

[cases.parametrize]
count = 10
seed = 42

[cases.parametrize.args]
a = "int(-50, 50)"
b = "int(-50, 50)"

[cases.parametrize.oracle]
reference = "{}/solutions/lab5.py"
"#,
		dir.path().display()
	))
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_lab5.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];

	assert_eq!(alice.total_cases(), 10, "Should have 10 generated cases");
	assert_eq!(
		alice.total_passed(),
		10,
		"Correct implementation should pass all generated cases"
	);
}

#[tokio::test]
async fn test_parametrize_with_rhai_oracle() {
	let dir = tempfile::tempdir().unwrap();

	std::fs::write(
		dir.path().join("alice_lab5.py"),
		"def find_max(a, b):\n    return max(a, b)\n",
	)
	.unwrap();

	let spec: TestSpec = toml::from_str(
		r#"
[meta]
name = "rhai_oracle_max"
file = "lab5.py"
function = "find_max"
language = "python"

[[cases]]
name = "rhai oracle"

[cases.parametrize]
count = 5
seed = 123

[cases.parametrize.args]
a = "int(0, 100)"
b = "int(0, 100)"

[cases.parametrize.oracle]
rhai = "if a >= b { a } else { b }"
"#,
	)
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_lab5.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];

	assert_eq!(alice.total_cases(), 5, "Should have 5 generated cases");
	assert_eq!(
		alice.total_passed(),
		5,
		"Correct max implementation should match Rhai oracle"
	);
}

#[tokio::test]
async fn test_setup_file_source() {
	let dir = tempfile::tempdir().unwrap();

	// Teacher generator script — outputs JSON to stdout
	std::fs::write(
		dir.path().join("gen_data.py"),
		r#"
import json
data = {"values": [10, 20, 30], "name": "test_data"}
print(json.dumps(data))
"#,
	)
	.unwrap();

	// Student code — reads the generated data
	std::fs::write(
		dir.path().join("alice_proc.py"),
		r#"
def sum_values(data):
    return sum(data["values"])
"#,
	)
	.unwrap();

	let spec: TestSpec = toml::from_str(&format!(
		r#"
[meta]
name = "file_source_test"
file = "proc.py"
function = "sum_values"
language = "python"

[[setup]]
id = "data"
file = "{}/gen_data.py"

[[cases]]
name = "sum generated values"
args = ["$data"]
expect = 60
"#,
		dir.path().display()
	))
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_proc.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];

	assert_eq!(alice.total_cases(), 1);
	assert_eq!(
		alice.test_results[0].cases[0].status,
		TestStatus::Passed,
		"Should pass: teacher script generates data, student sums it correctly"
	);
}

// ============================================================
// Chain mode tests
// ============================================================

/// Helper to write a file and return its path as a string.
fn write_file(dir: &std::path::Path, name: &str, content: &str) -> String {
	let path = dir.join(name);
	if let Some(parent) = path.parent() {
		std::fs::create_dir_all(parent).unwrap();
	}
	let mut f = std::fs::File::create(&path).unwrap();
	f.write_all(content.as_bytes()).unwrap();
	path.to_string_lossy().to_string()
}

#[tokio::test]
async fn test_chain_basic_imports() {
	let dir = tempfile::tempdir().unwrap();

	// Teacher module: provides DATA
	let teacher_path = write_file(
		dir.path(),
		"teacher.py",
		r#"
class Dataset:
    def __init__(self, values):
        self.values = values

DATA = Dataset([10, 20, 30])
"#,
	);

	// Student: processes the teacher's DATA
	write_file(
		dir.path(),
		"alice_hw.py",
		r#"
def total(data):
    return sum(data.values)

def average(data):
    return sum(data.values) / len(data.values)
"#,
	);

	let spec: TestSpec = toml::from_str(&format!(
		r#"
[meta]
name = "chain_basic"
file = "hw.py"
language = "python"
imports = ["{teacher_path}"]

[[cases]]
name = "sum values"
function = "total"
args = ["$DATA"]
expect = 60

[[cases]]
name = "average values"
function = "average"
args = ["$DATA"]
expect = 20.0
"#,
	))
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_hw.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];

	assert_eq!(alice.total_cases(), 2);
	assert_eq!(
		alice.test_results[0].cases[0].status,
		TestStatus::Passed,
		"total($DATA) should be 60"
	);
	assert_eq!(
		alice.test_results[0].cases[1].status,
		TestStatus::Passed,
		"average($DATA) should be 20.0"
	);
}

#[tokio::test]
async fn test_chain_decorator_checker() {
	let dir = tempfile::tempdir().unwrap();

	// Teacher module: DATA + @checker for validate
	let teacher_path = write_file(
		dir.path(),
		"teacher.py",
		r#"
DATA = list(range(10))

@checker
def check_subset(result, expected, DATA):
    """Auto-injected DATA from _ctx."""
    if not isinstance(result, list):
        return False, f"Expected list, got {type(result).__name__}"
    for item in result:
        if item not in DATA:
            return False, f"{item} not in DATA"
    return True, ""
"#,
	);

	// Student returns a subset
	write_file(
		dir.path(),
		"alice_hw.py",
		r#"
def subset(data, n):
    return data[:n]
"#,
	);

	let spec: TestSpec = toml::from_str(&format!(
		r#"
[meta]
name = "checker_test"
file = "hw.py"
language = "python"
imports = ["{teacher_path}"]

[[cases]]
name = "first 3 elements"
function = "subset"
args = ["$DATA", 3]
expect = [0, 1, 2]
"#,
	))
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_hw.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];

	assert_eq!(alice.total_cases(), 1);
	assert_eq!(
		alice.test_results[0].cases[0].status,
		TestStatus::Passed,
		"@checker should validate subset against DATA"
	);
}

#[tokio::test]
async fn test_chain_decorator_checker_fails() {
	let dir = tempfile::tempdir().unwrap();

	let teacher_path = write_file(
		dir.path(),
		"teacher.py",
		r#"
DATA = [1, 2, 3]

@checker("get_items")
def validate_items(result, expected, DATA):
    for item in result:
        if item not in DATA:
            return False, f"{item} not in DATA"
    return True, ""
"#,
	);

	// Student returns items not in DATA
	write_file(
		dir.path(),
		"alice_hw.py",
		r#"
def get_items():
    return [1, 2, 99]
"#,
	);

	let spec: TestSpec = toml::from_str(&format!(
		r#"
[meta]
name = "checker_fail_test"
file = "hw.py"
language = "python"
imports = ["{teacher_path}"]

[[cases]]
name = "bad items"
function = "get_items"
args = []
"#,
	))
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_hw.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];

	assert_eq!(
		alice.test_results[0].cases[0].status,
		TestStatus::Failed,
		"@checker('get_items') should detect 99 not in DATA"
	);
	assert!(
		alice.test_results[0].cases[0]
			.failure
			.as_ref()
			.unwrap()
			.message
			.contains("99"),
		"Error message should mention the invalid item"
	);
}

#[tokio::test]
async fn test_chain_setup_failure() {
	let dir = tempfile::tempdir().unwrap();

	let teacher_path = write_file(dir.path(), "teacher.py", "GREETING = 'hello'\n");

	// Student has no load_data function
	write_file(
		dir.path(),
		"alice_hw.py",
		r#"
def process(data):
    return len(data)
"#,
	);

	let spec: TestSpec = toml::from_str(&format!(
		r#"
[meta]
name = "setup_fail"
file = "hw.py"
language = "python"
imports = ["{teacher_path}"]

[[setup]]
id = "data"
function = "load_data"
args = ["test.csv"]

[[cases]]
name = "should be skipped"
function = "process"
args = ["$data"]
expect = 10
"#,
	))
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_hw.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];

	assert_eq!(
		alice.test_results[0].cases[0].status,
		TestStatus::Error,
		"All cases should error when setup fails"
	);
	let msg = &alice.test_results[0].cases[0]
		.failure
		.as_ref()
		.unwrap()
		.message;
	assert!(
		msg.contains("setup") || msg.contains("Setup") || msg.contains("not found"),
		"Error should mention setup failure, got: {msg}"
	);
}

#[tokio::test]
async fn test_chain_copy_refs_prevents_mutation() {
	let dir = tempfile::tempdir().unwrap();

	let teacher_path = write_file(dir.path(), "teacher.py", "DATA = [1, 2, 3, 4, 5]\n");

	// Student mutates the input!
	write_file(
		dir.path(),
		"alice_hw.py",
		r#"
def pop_and_sum(data):
    data.pop()  # mutates!
    return sum(data)

def length(data):
    return len(data)
"#,
	);

	let spec: TestSpec = toml::from_str(&format!(
		r#"
[meta]
name = "mutation_test"
file = "hw.py"
language = "python"
imports = ["{teacher_path}"]

[[cases]]
name = "pop_and_sum"
function = "pop_and_sum"
args = ["$DATA"]
expect = 10

[[cases]]
name = "length after mutation"
function = "length"
args = ["$DATA"]
expect = 5
"#,
	))
	.unwrap();

	let executor = PythonExecutor::new();
	let submissions = SubmissionSet {
		by_student: HashMap::from([(
			"alice".to_string(),
			vec![StudentFile {
				path: dir.path().join("alice_hw.py"),
				language: "python".to_string(),
			}],
		)]),
	};

	let results = orchestrator::run_all(&submissions, &[spec], &executor, 10, Some(1)).await;
	let alice = &results["alice"];

	// With copy_refs=true (default), second case should still see original DATA
	assert_eq!(
		alice.test_results[0].cases[0].status,
		TestStatus::Passed,
		"pop_and_sum should work on copied data"
	);
	assert_eq!(
		alice.test_results[0].cases[1].status,
		TestStatus::Passed,
		"length should still be 5 because DATA was deepcopied per case"
	);
}