-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgrader.py
More file actions
2035 lines (1796 loc) · 74.2 KB
/
grader.py
File metadata and controls
2035 lines (1796 loc) · 74.2 KB
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import json
import os
import re
import subprocess
import sys
import time
import traceback
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Protocol, Tuple
# --- BOOTSTRAP: Auto-setup environment ---
import bootstrap
bootstrap.initialize()
# -----------------------------------------
import tomli # noqa: E402
from rich.console import Console, RenderableType # noqa: E402
from rich.panel import Panel # noqa: E402
from rich.progress import Progress, SpinnerColumn, Task, TextColumn # noqa: E402
from rich.table import Table # noqa: E402
from rich.text import Text # noqa: E402
@dataclass
class TestResult:
success: bool
message: str
time: float
score: float
max_score: float
step_scores: List[Tuple[str, float, float]] = None
error_details: Optional[List[Dict[str, Any]]] = None
@property
def status(self) -> str:
if not self.success:
return "FAIL"
if self.score == self.max_score:
return "PASS"
return "PARTIAL"
def to_dict(self):
return {
"success": self.success,
"status": self.status,
"message": self.message,
"time": self.time,
"score": self.score,
"max_score": self.max_score,
"step_scores": self.step_scores,
"error_details": self.error_details,
}
@dataclass
class TestCase:
path: Path
meta: Dict[str, Any]
run_steps: List[Dict[str, Any]]
class Config:
def __init__(self, project_root: Path):
self.project_root = project_root
self._config = self._load_config()
def _load_config(self) -> Dict[str, Any]:
config_path = self.project_root / "grader_config.toml"
if not config_path.exists():
return {
"paths": {
"tests_dir": "tests",
"cases_dir": "tests/cases",
"common_dir": "tests/common",
},
"debug": {
"default_type": "gdb", # or "lldb", "python"
},
}
with open(config_path, "rb") as f:
return tomli.load(f)
@property
def paths(self) -> Dict[str, Path]:
return {
"tests_dir": self.project_root / self._config["paths"]["tests_dir"],
"cases_dir": self.project_root / self._config["paths"]["cases_dir"],
"common_dir": self.project_root / self._config["paths"]["common_dir"],
}
@property
def setup_steps(self) -> List[Dict[str, Any]]:
return self._config.get("setup", {}).get("steps", [])
@property
def groups(self) -> Dict[str, List[str]]:
"""获取测试组配置"""
return self._config.get("groups", {})
@property
def debug_config(self) -> Dict[str, Any]:
"""Get debug configuration from config file"""
return self._config.get(
"debug",
{
"default_type": "gdb",
},
)
class OutputChecker(Protocol):
def check(
self,
step: Dict[str, Any],
output: str,
error: str,
return_code: int,
test_dir: Path,
) -> Tuple[bool, str, Optional[float]]:
pass
class StandardOutputChecker:
def check(
self,
step: Dict[str, Any],
output: str,
error: str,
return_code: int,
test_dir: Path,
) -> Tuple[bool, str, Optional[float]]:
check = step.get("check", {})
# 检查返回值
if "return_code" in check and return_code != check["return_code"]:
return (
False,
f"Expected return code {check['return_code']}, got {return_code}",
None,
)
# 检查文件是否存在
if "files" in check:
for file_path in check["files"]:
resolved_path = Path(self._resolve_path(file_path, test_dir))
if not resolved_path.exists():
return False, f"Required file '{file_path}' not found", None
# 检查标准输出
if "stdout" in check:
expect_file = test_dir / check["stdout"]
if not expect_file.exists():
return False, f"Expected output file {check['stdout']} not found", None
with open(expect_file) as f:
expected = f.read()
if check.get("ignore_whitespace", False):
output = " ".join(output.split())
expected = " ".join(expected.split())
if output.rstrip() != expected.rstrip():
return False, "Output does not match expected content", None
# 检查标准错误
if "stderr" in check:
expect_file = test_dir / check["stderr"]
if not expect_file.exists():
return False, f"Expected error file {check['stderr']} not found", None
with open(expect_file) as f:
expected = f.read()
if check.get("ignore_whitespace", False):
error = " ".join(error.split())
expected = " ".join(expected.split())
if error.rstrip() != expected.rstrip():
return False, "Error output does not match expected content", None
return True, "All checks passed", None
def _resolve_path(self, path: str, test_dir: Path) -> str:
build_dir = test_dir / "build"
build_dir.mkdir(exist_ok=True)
replacements = {
"${test_dir}": str(test_dir),
"${build_dir}": str(build_dir),
}
for var, value in replacements.items():
path = path.replace(var, value)
return path
class StatusSpinnerColumn(SpinnerColumn):
"""Spinner that swaps to a custom status icon when provided."""
def render(self, task: Task) -> RenderableType:
icon = task.fields.get("status_icon")
if icon:
return Text.from_markup(icon)
return super().render(task)
class SpecialJudgeChecker:
def check(
self,
step: Dict[str, Any],
output: str,
error: str,
return_code: int,
test_dir: Path,
) -> Tuple[bool, str, Optional[float]]:
check = step.get("check", {})
if "special_judge" not in check:
return True, "No special judge specified", None
judge_script = test_dir / check["special_judge"]
if not judge_script.exists():
return (
False,
f"Special judge script {check['special_judge']} not found",
None,
)
input_data = {
"stdout": output,
"stderr": error,
"return_code": return_code,
"test_dir": str(test_dir),
"max_score": step.get("score", 0),
}
try:
process = subprocess.run(
[sys.executable, str(judge_script)],
input=json.dumps(input_data),
capture_output=True,
text=True,
)
result = json.loads(process.stdout)
if "score" in result:
result["score"] = min(result["score"], step.get("score", 0))
return (
result["success"],
result.get("message", "No message provided"),
result.get("score", None),
)
except Exception as e:
return False, f"Special judge failed: {str(e)}", None
class PatternChecker:
def check(
self,
step: Dict[str, Any],
output: str,
error: str,
return_code: int,
test_dir: Path,
) -> Tuple[bool, str, Optional[float]]:
check = step.get("check", {})
if "stdout_pattern" in check:
if not re.search(check["stdout_pattern"], output, re.MULTILINE):
return (
False,
f"Output does not match pattern {check['stdout_pattern']!r}",
None,
)
if "stderr_pattern" in check:
if not re.search(check["stderr_pattern"], error, re.MULTILINE):
return (
False,
f"Error output does not match pattern {check['stderr_pattern']!r}",
None,
)
return True, "All pattern checks passed", None
class CompositeChecker:
def __init__(self):
self.checkers = [
StandardOutputChecker(),
SpecialJudgeChecker(),
PatternChecker(),
]
def check(
self,
step: Dict[str, Any],
output: str,
error: str,
return_code: int,
test_dir: Path,
) -> Tuple[bool, str, Optional[float]]:
for checker in self.checkers:
success, message, score = checker.check(
step, output, error, return_code, test_dir
)
if not success:
return success, message, score
return True, "All checks passed", None
class TestRunner:
def __init__(
self,
config: Config,
console: Optional[Console] = None,
verbose: bool = False,
dry_run: bool = False,
no_check: bool = False,
):
self.config = config
self.console = console
self.checker = CompositeChecker()
self.verbose = verbose
self.dry_run = dry_run
self.no_check = no_check
def run_test(self, test: TestCase) -> TestResult:
start_time = time.perf_counter()
try:
# 清理和创建构建目录
build_dir = test.path / "build"
if build_dir.exists():
for file in build_dir.iterdir():
if file.is_file():
file.unlink()
build_dir.mkdir(exist_ok=True)
# 在dry-run模式下,显示测试点信息
if self.dry_run:
if self.console and not isinstance(self.console, type):
self.console.print(f"[bold]Test case:[/bold] {test.meta['name']}")
if "description" in test.meta:
self.console.print(
f"[bold]Description:[/bold] {test.meta['description']}"
)
return self._execute_test_steps(test)
result = None
if self.console and not isinstance(self.console, type):
# 在 rich 环境下显示进度条
status_icons = {
"PASS": "[green]✓[/green]",
"PARTIAL": "[yellow]~[/yellow]",
"FAIL": "[red]✗[/red]",
}
with Progress(
SpinnerColumn(finished_text=status_icons["FAIL"]),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
total_steps = len(test.run_steps)
task = progress.add_task(
f"Running {test.meta['name']} [0/{total_steps}]...",
total=total_steps,
)
result = self._execute_test_steps(test, progress, task)
# 根据状态设置图标
progress.columns[0].finished_text = status_icons[result.status]
# 更新最终状态,移除Running字样,加上结果提示
final_status = {
"PASS": "[green]Passed[/green]",
"PARTIAL": "[yellow]Partial[/yellow]",
"FAIL": "[red]Failed[/red]",
}[result.status]
progress.update(
task,
completed=total_steps,
description=f"{test.meta['name']} [{total_steps}/{total_steps}]: {final_status}",
)
# 如果测试失败,在进度显示完成后输出失败信息
if not result.success and not self.dry_run:
for error_details in result.error_details:
# 获取失败的步骤信息
step_index = error_details["step"]
self.console.print(
f"\n[red]Test '{test.meta['name']}' failed at step {step_index}:[/red]"
)
self.console.print(f"Command: {error_details['command']}")
if "stdout" in error_details:
self.console.print("\nActual output:")
self.console.print(error_details["stdout"].strip())
if "stderr" in error_details:
self.console.print("\nError output:")
self.console.print(error_details["stderr"].strip())
if "expected_output" in error_details:
self.console.print("\nExpected output:")
self.console.print(error_details["expected_output"])
if "error_message" in error_details:
self.console.print("\nError details:")
self.console.print(f" {error_details['error_message']}")
if "return_code" in error_details:
self.console.print(
f"\nReturn code: {error_details['return_code']}"
)
self.console.print() # 添加一个空行作为分隔
return result
else:
# 在非 rich 环境下直接执行
return self._execute_test_steps(test)
except Exception as e:
print(e)
print(traceback.format_exc())
return TestResult(
success=False,
message=f"Error: {str(e)}",
time=time.perf_counter() - start_time,
score=0,
max_score=test.meta["score"],
)
def _execute_test_steps(
self,
test: TestCase,
progress: Optional[Progress] = None,
task: Optional[Any] = None,
) -> TestResult:
start_time = time.perf_counter()
step_scores = []
total_score = 0
has_step_scores = any("score" in step for step in test.run_steps)
max_possible_score = (
sum(step.get("score", 0) for step in test.run_steps)
if has_step_scores
else test.meta["score"]
)
steps_error_details = []
for i, step in enumerate(test.run_steps, 1):
if progress is not None and task is not None:
step_name = step.get("name", step["command"])
progress.update(
task,
description=f"Running {test.meta['name']} [{i}/{len(test.run_steps)}]: {step_name}",
completed=i - 1,
)
result = self._execute_single_step(test, step, i)
if not result.success and not self.dry_run:
steps_error_details.append(result.error_details)
if progress is not None and task is not None:
progress.update(task, completed=i)
if step.get("must_pass", True):
# 返回包含所有已收集的错误详情的结果
return TestResult(
success=False,
message=result.message,
time=time.perf_counter() - start_time,
score=total_score,
max_score=max_possible_score,
step_scores=step_scores,
error_details=steps_error_details,
)
total_score += result.score
if result.step_scores:
step_scores.extend(result.step_scores)
if progress is not None and task is not None:
progress.update(
task,
description=f"Running {test.meta['name']} [{i}/{len(test.run_steps)}]: {step_name}",
completed=i,
)
# 如果有分步给分,确保总分不超过测试用例的总分
if has_step_scores:
total_score = min(total_score, test.meta["score"])
else:
total_score = test.meta["score"]
step_scores = None
success = True if self.dry_run else total_score > 0
return TestResult(
success=success,
message="All steps completed" if success else "Some steps failed",
time=time.perf_counter() - start_time,
score=total_score,
max_score=max_possible_score,
step_scores=step_scores,
error_details=steps_error_details if steps_error_details else None,
)
def _execute_single_step(
self, test: TestCase, step: Dict[str, Any], step_index: int
) -> TestResult:
start_time = time.perf_counter()
# 在dry-run模式下,只打印命令
if self.dry_run:
cmd = [self._resolve_path(step["command"], test.path)]
args = [
self._resolve_path(str(arg), test.path) for arg in step.get("args", [])
]
if self.console and not isinstance(self.console, type):
self.console.print(f"\n[bold cyan]Step {step_index}:[/bold cyan]")
if "name" in step:
self.console.print(f"[bold]Name:[/bold] {step['name']}")
self.console.print(f"[bold]Command:[/bold] {' '.join(cmd + args)}")
if "stdin" in step:
self.console.print(f"[bold]Input file:[/bold] {step['stdin']}")
if "check" in step and not self.no_check:
self.console.print("[bold]Checks:[/bold]")
for check_type, check_value in step["check"].items():
if check_type == "files":
check_value = [
self._resolve_path(file, test.path)
for file in check_value
]
self.console.print(f" - {check_type}: {check_value}")
return TestResult(
success=True,
message="Dry run",
time=time.perf_counter() - start_time,
score=0,
max_score=0,
)
# 获取相对于测试目录的命令路径
cmd = [self._resolve_path(step["command"], test.path, test.path)]
args = [
self._resolve_path(str(arg), test.path, test.path)
for arg in step.get("args", [])
]
# 构建环境变量
step_env = os.environ.copy()
if "env" in step:
for key, value in step["env"].items():
step_env[key] = self._resolve_path(str(value), test.path, test.path)
try:
process = subprocess.run(
cmd + args,
cwd=test.path,
input=self._get_stdin_data(test, step),
capture_output=True,
text=True,
timeout=step.get("timeout", 5.0),
env=step_env,
)
# 如果启用了详细输出模式
if self.verbose and self.console and not isinstance(self.console, type):
self.console.print(f"[bold cyan]Step {step_index} Output:[/bold cyan]")
self.console.print("[bold]Command:[/bold]", " ".join(cmd + args))
if process.stdout:
self.console.print("[bold]Standard Output:[/bold]")
self.console.print(process.stdout)
if process.stderr:
self.console.print("[bold]Standard Error:[/bold]")
self.console.print(process.stderr)
self.console.print(f"[bold]Return Code:[/bold] {process.returncode}\n")
except subprocess.TimeoutExpired as e:
return self._create_timeout_result(
test, step, step_index, start_time, e.stdout, e.stderr
)
# 在no_check模式下,只要命令执行成功就认为通过
if self.no_check:
return self._create_success_result(
test,
step,
step.get("score", test.meta["score"]) if process.returncode == 0 else 0,
start_time,
)
if "check" in step:
success, message, score = self.checker.check(
step,
process.stdout,
process.stderr,
process.returncode,
test.path,
)
if not success:
return self._create_failure_result(
test,
step,
step_index,
message,
start_time,
process.stdout,
process.stderr,
process.returncode,
process.stdout
if "expected_output" in step.get("check", {})
else "",
)
return self._create_success_result(test, step, score, start_time)
def _resolve_relative_path(self, path: str, cwd: Path = Path.cwd()) -> str:
result = path
if isinstance(path, Path):
result = str(path.resolve())
try:
result = str(path.relative_to(cwd, walk_up=True))
except:
try:
result = str(path.relative_to(cwd))
except:
result = str(path)
if len(result) > len(str(path)):
result = str(path)
return result
def _resolve_path(self, path: str, test_dir: Path, cwd: Path = Path.cwd()) -> str:
build_dir = test_dir / "build"
build_dir.mkdir(exist_ok=True)
replacements = {
"${test_dir}": self._resolve_relative_path(test_dir, cwd),
"${common_dir}": self._resolve_relative_path(
self.config.paths["common_dir"], cwd
),
"${root_dir}": self._resolve_relative_path(self.config.project_root, cwd),
"${build_dir}": self._resolve_relative_path(build_dir, cwd),
}
for var, value in replacements.items():
path = path.replace(var, value)
return path
def _get_stdin_data(self, test: TestCase, step: Dict[str, Any]) -> Optional[str]:
if "stdin" not in step:
return None
stdin_file = test.path / step["stdin"]
if not stdin_file.exists():
raise FileNotFoundError(f"Input file {step['stdin']} not found")
with open(stdin_file) as f:
return f.read()
def _create_timeout_result(
self,
test: TestCase,
step: Dict[str, Any],
step_index: int,
start_time: float,
stdout: Optional[str] = None,
stderr: Optional[str] = None,
) -> TestResult:
error_message = f"Step {step_index} '{step.get('name', step['command'])}' timed out after {step.get('timeout', 5.0)}s"
# 构造命令字符串
cmd = [self._resolve_path(step["command"], test.path, os.getcwd())]
if "args" in step:
cmd.extend(
[
self._resolve_path(str(arg), test.path, os.getcwd())
for arg in step.get("args", [])
]
)
command_str = " ".join(cmd)
error_details = {
"step": step_index,
"step_name": step.get("name", step["command"]),
"error_message": error_message,
"command": command_str, # 添加实际运行的命令
}
if stdout:
error_details["stdout"] = stdout
if stderr:
error_details["stderr"] = stderr
return TestResult(
success=False,
message=error_message,
time=time.perf_counter() - start_time,
score=0,
max_score=step.get("score", test.meta["score"]),
error_details=error_details,
)
def _create_failure_result(
self,
test: TestCase,
step: Dict[str, Any],
step_index: int,
message: str,
start_time: float,
stdout: str = "",
stderr: str = "",
return_code: Optional[int] = None,
expected_output: str = "",
) -> TestResult:
# 构造命令字符串
cmd = [self._resolve_path(step["command"], test.path, os.getcwd())]
if "args" in step:
cmd.extend(
[
self._resolve_path(str(arg), test.path, os.getcwd())
for arg in step.get("args", [])
]
)
command_str = " ".join(cmd)
error_details = {
"step": step_index,
"step_name": step.get("name", step["command"]),
"error_message": message,
"command": command_str, # 添加实际运行的命令
}
if stdout:
error_details["stdout"] = stdout
if stderr:
error_details["stderr"] = stderr
if return_code is not None:
error_details["return_code"] = return_code
if expected_output:
error_details["expected_output"] = expected_output
return TestResult(
success=False,
message=f"Step {step_index} '{step.get('name', step['command'])}' failed: {message}",
time=time.perf_counter() - start_time,
score=0,
max_score=step.get("score", test.meta["score"]),
error_details=error_details,
)
def _create_success_result(
self,
test: TestCase,
step: Dict[str, Any],
score: Optional[float],
start_time: float,
) -> TestResult:
step_score = score if score is not None else step.get("score", 0)
return TestResult(
success=True,
message="Step completed successfully",
time=time.perf_counter() - start_time,
score=step_score,
max_score=step.get("score", test.meta["score"]),
step_scores=[
(step.get("name", step["command"]), step_score, step.get("score", 0))
]
if step.get("score", 0) > 0
else None,
)
class ResultFormatter(ABC):
@abstractmethod
def format_results(
self,
test_cases: List[TestCase],
results: List[Dict[str, Any]],
total_score: float,
max_score: float,
) -> None:
pass
class JsonFormatter(ResultFormatter):
def format_results(
self,
test_cases: List[TestCase],
results: List[Dict[str, Any]],
total_score: float,
max_score: float,
) -> None:
json_result = {
"total_score": round(total_score, 1),
"max_score": round(max_score, 1),
"percentage": round(total_score / max_score * 100, 1),
"tests": results,
}
print(json.dumps(json_result, ensure_ascii=False))
class TableFormatter(ResultFormatter):
def __init__(self, console: Console):
self.console = console
def format_results(
self,
test_cases: List[TestCase],
results: List[Dict[str, Any]],
total_score: float,
max_score: float,
) -> None:
self._format_rich_table(test_cases, results, total_score, max_score)
def _format_rich_table(
self,
test_cases: List[TestCase],
results: List[Dict[str, Any]],
total_score: float,
max_score: float,
) -> None:
table = Table(show_header=True, header_style="bold")
table.add_column("Test Case", style="cyan")
table.add_column("Result", justify="center")
table.add_column("Time", justify="right")
table.add_column("Score", justify="right")
table.add_column("Message")
status_style = {
"PASS": "[green]PASS[/green]",
"PARTIAL": "[yellow]PARTIAL[/yellow]",
"FAIL": "[red]FAIL[/red]",
}
for test, result in zip(test_cases, results):
table.add_row(
test.meta["name"],
status_style[result["status"]],
f"{result['time']:.2f}s",
f"{result['score']:.1f}/{result['max_score']:.1f}",
result["message"],
)
self.console.print(table)
self._print_summary(total_score, max_score)
def _format_basic_table(
self,
test_cases: List[TestCase],
results: List[Dict[str, Any]],
total_score: float,
max_score: float,
) -> None:
# 定义列宽
col_widths = {
"name": max(len(test.meta["name"]) for test in test_cases),
"status": 8, # PASS/PARTIAL/FAIL
"time": 10, # XX.XXs
"score": 15, # XX.X/XX.X
"message": 40,
}
# 打印表头
header = (
f"{'Test Case':<{col_widths['name']}} "
f"{'Result':<{col_widths['status']}} "
f"{'Time':>{col_widths['time']}} "
f"{'Score':>{col_widths['score']}} "
f"{'Message':<{col_widths['message']}}"
)
self.console.print("-" * len(header))
self.console.print(header)
self.console.print("-" * len(header))
# 打印每一行
status_text = {
"PASS": "PASS",
"PARTIAL": "PARTIAL",
"FAIL": "FAIL",
}
for test, result in zip(test_cases, results):
row = (
f"{test.meta['name']:<{col_widths['name']}} "
f"{status_text[result['status']]:<{col_widths['status']}} "
f"{result['time']:.2f}s".rjust(col_widths["time"])
+ f" {result['score']:.1f}/{result['max_score']}".rjust(
col_widths["score"]
)
+ " "
f"{result['message'][: col_widths['message']]:<{col_widths['message']}}"
)
self.console.print(row)
self.console.print("-" * len(header))
self._print_basic_summary(total_score, max_score)
def _print_summary(self, total_score: float, max_score: float) -> None:
summary = Panel(
f"[bold]Total Score: {total_score:.1f}/{max_score:.1f} "
f"({total_score / max_score * 100:.1f}%)[/bold]",
border_style="green" if total_score == max_score else "yellow",
)
self.console.print()
self.console.print(summary)
self.console.print()
def _print_basic_summary(self, total_score: float, max_score: float) -> None:
self.console.print()
self.console.print(
f"Total Score: {total_score:.1f}/{max_score:.1f} "
f"({total_score / max_score * 100:.1f}%)"
)
self.console.print()
class VSCodeConfigGenerator:
"""Generate and manage VS Code debug configurations"""
def __init__(self, project_root: Path, config: Config, verbose: bool = False):
self.project_root = project_root
self.config = config
self.verbose = verbose
self.vscode_dir = project_root / ".vscode"
self.launch_file = self.vscode_dir / "launch.json"
self.tasks_file = self.vscode_dir / "tasks.json"
def generate_configs(
self, failed_steps: List[Tuple[TestCase, Dict[str, Any]]], merge: bool = True
) -> None:
"""Generate VS Code configurations for debugging a failed test step"""
self.vscode_dir.mkdir(exist_ok=True)
launch_config = []
tasks_config = []
for test_case, failed_step in failed_steps:
launch_config.extend(self._generate_launch_config(test_case, failed_step))
tasks_config.extend(self._generate_tasks_config(test_case))
launch_config = {"version": "0.2.0", "configurations": launch_config}
tasks_config = {"version": "2.0.0", "tasks": tasks_config}
self._write_or_merge_json(
self.launch_file, launch_config, "configurations", merge
)
self._write_or_merge_json(self.tasks_file, tasks_config, "tasks", merge)
def _generate_launch_config(
self, test_case: TestCase, failed_step: Dict[str, Any]
) -> List[Dict[str, Any]]:
"""Generate launch configuration based on debug type"""
target_step = failed_step
if "debug_step" in failed_step:
step_name = failed_step["debug_step"]
# 在测试步骤中查找匹配名字的步骤
found_step = next(
(s for s in test_case.run_steps if s.get("name") == step_name), None
)
if found_step:
if self.verbose:
print(
f"Step '{failed_step.get('name')}' failed. Using debug step '{step_name}'."
)
target_step = found_step
else:
print(f"Warning: debug step '{step_name}' not found in steps.")
debug_type = (
target_step.get("debug", {}).get("type")
or test_case.meta.get("debug", {}).get("type")
or self.config.debug_config["default_type"]
)
cwd = str(self.config.project_root)
program = self._resolve_path(
target_step["command"], test_case.path, self.config.project_root
)
args = [
self._resolve_path(arg, test_case.path, self.config.project_root)
for arg in target_step.get("args", [])
]
if debug_type == "cpp":
configs = []
base_name = f"Debug {test_case.meta['name']} - Step {target_step.get('name', 'failed step')}"
# Add GDB configuration
configs.append(
{
"name": f"{base_name} (GDB)",
"type": "cppdbg",
"request": "launch",
"program": program,
"args": args,
"stopOnEntry": True,
"cwd": cwd,
"environment": [],
"internalConsoleOptions": "neverOpen",
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",