-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgrader.py
More file actions
3378 lines (2976 loc) · 121 KB
/
grader.py
File metadata and controls
3378 lines (2976 loc) · 121 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 difflib
import io
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import threading
import time
import traceback
import venv
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Protocol, Tuple, Union
def create_venv(venv_path):
if venv_path.exists():
shutil.rmtree(venv_path)
print("Creating virtual environment...", flush=True)
venv.create(venv_path, with_pip=True)
print(f"Virtual environment will be created at: {venv_path}", flush=True)
def install_requirements(venv_path):
pip_path = venv_path / ("Scripts" if sys.platform == "win32" else "bin") / "pip"
requirements_path = Path(__file__).parent / "requirements.txt"
print("Installing dependencies...", flush=True)
subprocess.run(
[
str(pip_path),
"install",
"-r",
str(requirements_path),
"-i",
"https://pypi.tuna.tsinghua.edu.cn/simple",
],
check=True,
)
def ensure_venv():
# 首先检查本地是否已安装必需的包
try:
import rich
import tomli
return True
except ImportError:
pass
venv_dir = Path(__file__).parent / ".venv"
python_path = (
venv_dir / ("Scripts" if sys.platform == "win32" else "bin") / "python"
)
pip_path = venv_dir / ("Scripts" if sys.platform == "win32" else "bin") / "pip"
# 检查是否已在虚拟环境中运行
if os.environ.get("GRADER_VENV"):
try:
install_requirements(venv_dir)
return True
except Exception as e:
print(
f"Error: Failed to set up virtual environment: {str(e)}",
file=sys.stderr,
)
if venv_dir.exists():
shutil.rmtree(venv_dir)
sys.exit(1)
try:
# 如果存在虚拟环境,直接使用
if venv_dir.exists() and python_path.exists() and pip_path.exists():
pass
else:
# 创建新的虚拟环境
create_venv(venv_dir)
install_requirements(venv_dir)
# 使用虚拟环境重新运行脚本
env = os.environ.copy()
env["GRADER_VENV"] = "1"
subprocess.run(
[str(python_path), __file__] + sys.argv[1:], env=env, check=False
)
return False
except Exception as e:
print(f"Error: Failed to set up virtual environment: {str(e)}", file=sys.stderr)
# 如果虚拟环境创建失败,清理现有的虚拟环境
if venv_dir.exists():
shutil.rmtree(venv_dir)
sys.exit(1)
if __name__ == "__main__":
if not ensure_venv():
sys.exit(0)
import tomli # noqa: E402
from rich.console import Console # noqa: E402
from rich.panel import Panel # noqa: E402
from rich.progress import Progress, SpinnerColumn, TextColumn # noqa: E402
from rich.table import Table # 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", "rust"
"show_test_build_hint": True, # 是否在失败时显示 TEST_BUILD 环境变量设置提示
},
}
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",
"show_test_build_hint": True,
},
)
@property
def executables(self) -> Dict[str, str]:
"""获取预定义的可执行文件配置"""
return self._config.get("executables", {})
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 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 SequenceChecker:
"""检查输出中的模式是否按指定顺序出现,支持部分无序"""
def check(
self,
step: Dict[str, Any],
output: str,
error: str,
return_code: int,
test_dir: Path,
) -> Tuple[bool, str, Optional[float]]:
# 检查配置中是否有序列检查相关配置
check_config = step.get("check", {})
if "sequence" not in check_config:
return True, "No sequence check specified", None
# 获取序列检查配置
seq_config = check_config["sequence"]
patterns = seq_config.get("patterns", [])
case_sensitive = seq_config.get("case_sensitive", True)
regex_mode = seq_config.get("regex_mode", True)
allow_partial = seq_config.get("allow_partial", False)
verify_end = seq_config.get("verify_end", False)
whitespace_chars = seq_config.get("whitespace_chars", " \t\n\r")
# 执行序列检查
success, score_ratio, message = self._check_sequence(
output,
patterns,
case_sensitive,
regex_mode,
allow_partial,
verify_end,
whitespace_chars,
)
if success:
score = step.get("score", 0.0) * score_ratio
else:
score = 0.0
return success, message, score
def _check_sequence(
self,
text: str,
patterns: List[Dict[str, Any]],
case_sensitive: bool,
regex_mode: bool,
allow_partial: bool,
verify_end: bool = False,
whitespace_chars: str = " \t\n\r",
) -> Tuple[bool, float, str]:
"""
Checks if the text matches the sequence of patterns.
Args:
text: The text to check.
patterns: A list of patterns.
case_sensitive: Whether to distinguish case sensitivity.
regex_mode: Whether to use regular expressions.
allow_partial: Whether to allow partial matching.
verify_end: Whether to verify that there is no more output after the last pattern.
whitespace_chars: The set of characters considered whitespace.
Returns:
A tuple containing (success, match score ratio, error message).
"""
if not case_sensitive:
text = text.lower()
current_pos = 0
matched_count = 0
total_items = 0
total_weight = 0
matched_weight = 0
errors = []
for pattern_item in patterns:
if "pattern" in pattern_item:
# 单个模式
pattern = pattern_item["pattern"]
required = pattern_item.get("required", True)
weight = pattern_item.get("weight", 1.0)
description = pattern_item.get("description", f"Pattern: {pattern}")
total_items += 1
total_weight += weight
# 处理大小写敏感性
if not case_sensitive and regex_mode:
pattern = f"(?i){pattern}"
elif not case_sensitive:
pattern = pattern.lower()
# 在当前位置之后搜索模式
match_pos = self._find_pattern(text, pattern, current_pos, regex_mode)
if match_pos >= 0:
# 找到匹配,更新位置并计数
current_pos = match_pos
matched_count += 1
matched_weight += weight
elif required:
# 必需的模式没找到
error_msg = f"Required pattern not found: {description}"
errors.append(error_msg)
if not allow_partial:
return False, 0.0, error_msg
elif "unordered" in pattern_item:
# 无序组
unordered_patterns = pattern_item["unordered"]
required = pattern_item.get("required", True)
group_weight = pattern_item.get("weight", len(unordered_patterns))
group_description = pattern_item.get(
"description", "Unordered pattern group"
)
total_items += len(unordered_patterns)
total_weight += group_weight
# 处理无序组
(
result,
end_pos,
matched_item_count,
group_matched_weight,
unmatched_patterns,
) = self._match_unordered_group(
text,
unordered_patterns,
current_pos,
case_sensitive,
regex_mode,
)
if result:
# 找到所有无序模式
current_pos = end_pos
matched_count += matched_item_count
# 按比例分配组权重
if len(unordered_patterns) > 0:
matched_weight += group_weight * (
matched_item_count / len(unordered_patterns)
)
elif required:
# 必需的无序组没找到
error_msg = f"Required unordered group not fully matched: {group_description} - {matched_item_count}/{len(unordered_patterns)} patterns"
# 如果有没匹配的模式,添加它们的描述
if unmatched_patterns:
error_msg += "\nUnmatched patterns:"
for p in unmatched_patterns:
p_desc = p.get(
"description", f"Pattern: {p.get('pattern')}"
)
error_msg += f"\n - {p_desc}"
errors.append(error_msg)
if not allow_partial:
return False, 0.0, error_msg
if verify_end and matched_count == total_items and current_pos < len(text):
# 检查剩余文本是否只包含空白字符
remaining_text = text[current_pos:]
if any(c not in whitespace_chars for c in remaining_text):
# 发现非空白字符
return (
False,
0.0,
f"Unexpected output after the last pattern: '{remaining_text.strip()}'",
)
# 计算匹配分数
score_ratio = matched_weight / total_weight if total_weight > 0 else 0.0
# 判断匹配结果和计算得分
if matched_count == total_items:
# 完全匹配
return True, 1.0, "All patterns matched in sequence"
elif allow_partial and matched_count > 0:
# 部分匹配且允许部分得分
score_ratio = matched_weight / total_weight if total_weight > 0 else 0.0
return (
True,
score_ratio,
f"Partial match: {matched_count}/{total_items} patterns",
)
else:
# 部分匹配但不允许部分得分,或完全不匹配
error_detail = "\n".join(errors) if errors else ""
return (
False,
0.0,
f"Only {matched_count}/{total_items} patterns matched\n{error_detail}",
)
def _find_pattern(
self, text: str, pattern: str, start_pos: int, regex_mode: bool
) -> int:
"""
在文本中从指定位置开始查找模式的第一次出现
返回:
匹配结束的位置,未找到则返回-1
"""
if regex_mode:
match = re.search(pattern, text[start_pos:], re.MULTILINE)
if match:
match_end = start_pos + match.end()
return match_end
return -1
else:
# 字符串精确匹配
pos = text.find(pattern, start_pos)
if pos >= 0:
return pos + len(pattern)
return -1
def _match_unordered_group(
self,
text: str,
patterns: List[Any],
start_pos: int,
case_sensitive: bool,
regex_mode: bool,
) -> Tuple[bool, int, int, float, List[Dict[str, Any]]]:
"""
尝试匹配无序组中的所有模式
返回:
(是否全部匹配成功, 最后匹配位置, 匹配的模式数量, 匹配的权重总和, 未匹配的模式)
"""
# 转换模式格式和提取权重
processed_patterns = []
for p in patterns:
if isinstance(p, dict):
pattern = p.get("pattern", "")
weight = p.get("weight", 1.0)
# 保存原始模式对象的引用
original_pattern = p
else:
pattern = p
weight = 1.0
# 为字符串模式创建一个简单的字典
original_pattern = {"pattern": p}
if not case_sensitive and regex_mode:
pattern = f"(?i){pattern}"
elif not case_sensitive:
pattern = pattern.lower()
processed_patterns.append(
{
"pattern": pattern,
"matched": False,
"weight": weight,
"original": original_pattern,
}
)
# 当前搜索范围
current_text = text[start_pos:]
last_match_end = 0
matched_count = 0
matched_weight = 0
# 尝试匹配所有模式
for _ in range(len(processed_patterns)):
best_match = None
best_pattern_idx = -1
# 在所有未匹配的模式中找最早出现的
for i, state in enumerate(processed_patterns):
if state["matched"]:
continue
if regex_mode:
match = re.search(state["pattern"], current_text)
if match and (best_match is None or match.start() < best_match[0]):
best_match = (match.start(), match.end())
best_pattern_idx = i
else:
pos = current_text.find(state["pattern"])
if pos >= 0 and (best_match is None or pos < best_match[0]):
best_match = (pos, pos + len(state["pattern"]))
best_pattern_idx = i
if best_pattern_idx >= 0:
# 标记为已匹配
processed_patterns[best_pattern_idx]["matched"] = True
matched_weight += processed_patterns[best_pattern_idx]["weight"]
matched_count += 1
# 更新最后匹配位置
last_match_end = max(last_match_end, best_match[1])
else:
# 找不到更多匹配
break
# 收集所有未匹配的模式
unmatched_patterns = [
p["original"] for p in processed_patterns if not p["matched"]
]
# 检查是否所有模式都已匹配
all_matched = matched_count == len(processed_patterns)
return (
all_matched,
start_pos + last_match_end,
matched_count,
matched_weight,
unmatched_patterns,
)
class CompositeChecker:
def __init__(self):
self.checkers = [
StandardOutputChecker(),
SpecialJudgeChecker(),
PatternChecker(),
SequenceChecker(),
]
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 InteractiveProcess:
"""管理与进程的交互会话"""
def __init__(
self,
cmd: List[str],
cwd: str,
timeout: float = 30.0,
stderr_to_stdout: bool = False,
):
self.cmd = cmd
self.cwd = cwd
self.timeout = timeout
self.process = None
self.stdout_buffer = io.StringIO()
self.stderr_buffer = io.StringIO()
self.stdout_data = "" # 存储当前已读取的所有输出
self.stderr_data = ""
self.closed = False
self.start_time = None
self.prompt = "> " # Shell 提示符
self.stderr_to_stdout = stderr_to_stdout
# 用于同步的事件和锁
self.output_lock = threading.Lock()
self.output_event = threading.Event() # 用于检测输出是否稳定
def start(self):
"""启动交互式进程"""
self.process = subprocess.Popen(
self.cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE if not self.stderr_to_stdout else subprocess.STDOUT,
text=True,
bufsize=0, # 无缓冲
cwd=self.cwd,
)
self.start_time = time.time()
# 启动读取线程
self._start_reading_threads()
def _start_reading_threads(self):
"""启动读取输出的线程"""
self.stdout_thread = threading.Thread(
target=self._read_output,
args=(self.process.stdout, self.stdout_buffer, "stdout"),
)
self.stdout_thread.daemon = True
self.stdout_thread.start()
if not self.stderr_to_stdout:
self.stderr_thread = threading.Thread(
target=self._read_output,
args=(self.process.stderr, self.stderr_buffer, "stderr"),
)
self.stderr_thread.daemon = True
self.stderr_thread.start()
def _read_output(self, pipe, buffer, stream_name):
"""持续读取管道输出到缓冲区"""
for line in iter(pipe.readline, ""):
with self.output_lock:
buffer.write(line)
if stream_name == "stdout":
self.stdout_data += line
else:
self.stderr_data += line
# 通知有新输出
self.output_event.set()
def send_input(self, text: str, echo: bool = True, wait_for_output: bool = True):
"""
发送文本到进程的标准输入
Args:
text: 要发送的文本
echo: 是否在输出中显示命令 (默认: True)
wait_for_output: 是否等待程序输出稳定 (默认: True)
"""
if self.closed or self.process.stdin.closed:
raise IOError("Standard input is closed")
# 在发送前记录当前输出长度
current_stdout_length = len(self.stdout_data)
# 如果需要回显,使用提示符格式
if echo:
with self.output_lock:
self.stdout_buffer.write(f"{self.prompt}{text}\n")
self.stdout_data += f"{self.prompt}{text}\n"
# 发送实际输入到进程
self.process.stdin.write(text + "\n")
self.process.stdin.flush()
# 等待输出稳定 (如果需要)
if wait_for_output:
self._wait_for_output_stabilize(current_stdout_length)
def _wait_for_output_stabilize(
self, previous_length, timeout=2.0, check_interval=0.05
):
"""
等待输出稳定 (没有新输出一段时间后认为已稳定)
Args:
previous_length: 发送命令前的输出长度
timeout: 最长等待时间 (秒)
check_interval: 检查间隔 (秒)
"""
start_wait = time.time()
last_change_time = start_wait
last_length = previous_length
while time.time() - start_wait < timeout:
# 等待通知有新输出
self.output_event.wait(check_interval)
self.output_event.clear()
# 检查输出是否有变化
current_length = len(self.stdout_data)
if current_length > last_length:
last_length = current_length
last_change_time = time.time()
# 如果超过200ms没有新输出,且与输入前相比有变化,认为输出已稳定
if (
time.time() - last_change_time > 0.2
and current_length > previous_length
):
return
def close_input(self):
"""关闭标准输入,发送EOF"""
if not self.closed and self.process.stdin and not self.process.stdin.closed:
self.process.stdin.close()
self.closed = True
def send_signal(self, sig: str):
"""发送信号给进程"""
if not self.process:
return
signal_map = {
"INT": signal.SIGINT,
"TSTP": signal.SIGTSTP,
"QUIT": signal.SIGQUIT,
"KILL": signal.SIGKILL,
"TERM": signal.SIGTERM,
}
if sig in signal_map:
# 记录发送信号前的状态
current_stdout_length = len(self.stdout_data)
was_running = self.is_running()
# 发送信号
self.process.send_signal(signal_map[sig])
# 对于可能终止进程的信号,检查进程状态
if sig in ["INT", "TERM", "KILL"]:
# 先给进程一点时间来处理信号
time.sleep(0.1)
# 检查进程状态是否改变
if was_running and not self.is_running():
# 进程已终止,不需要等待输出
return
# 固定等待一段时间,让信号处理和可能的输出有时间完成
time.sleep(0.2)
# 然后再尝试等待输出稳定(如果有新输出的话)
if len(self.stdout_data) > current_stdout_length:
self._wait_for_output_stabilize(current_stdout_length, timeout=2.0)
def wait(self, timeout: Optional[float] = None):
"""等待进程终止"""
if not self.process:
return None
try:
return self.process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
return None
def get_outputs(self) -> Tuple[str, str]:
"""获取当前累积的标准输出和标准错误"""
stdout = self.stdout_buffer.getvalue()
stderr = self.stderr_buffer.getvalue()
return stdout, stderr
def is_running(self) -> bool:
"""检查进程是否仍在运行"""
if not self.process:
return False
return self.process.poll() is None
def check_timeout(self) -> bool:
"""检查是否超时"""
if not self.start_time:
return False
return time.time() - self.start_time > self.timeout
def terminate(self):
"""终止进程"""
if self.process and self.is_running():
self.close_input()
self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
def print_verbose(self, console: Console):
console.print(f"[bold cyan]Command: {' '.join(self.cmd)}[/bold cyan]")
console.print(f"[bold cyan]Current working directory: {self.cwd}[/bold cyan]")
stdout, stderr = self.get_outputs()
if stdout.strip():
console.print("[bold cyan]Standard Output:[/bold cyan]")
console.print(stdout)
if stderr.strip():
console.print("[bold cyan]Standard Error:[/bold cyan]")
console.print(stderr)
class TestRunner:
def __init__(
self,
config: Config,
console: Optional[Console] = None,
verbose: bool = False,
dry_run: bool = False,
no_check: bool = False,
compare: bool = False,
):
self.config = config
self.console = console
self.checker = CompositeChecker()
self.verbose = verbose
self.dry_run = dry_run
self.no_check = no_check
self.compare = compare
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)
if total_steps == 1:
task_description = f"Running {test.meta['name']}..."
else:
task_description = (
f"Running {test.meta['name']} [0/{total_steps}]..."
)
task = progress.add_task(
task_description,
total=total_steps,
)