86 lines
2.2 KiB
Python
86 lines
2.2 KiB
Python
import subprocess
|
|
import os
|
|
from pathlib import Path
|
|
|
|
# 配置参数
|
|
TEST_DIR = Path(".")
|
|
CC_PATH = Path("../../ccompiler.exe")
|
|
VM_PATH = Path("../../rv32-vm.exe")
|
|
WORKSPACE = Path(".") # 测试工作目录
|
|
|
|
# 测试用例映射表(示例)
|
|
TEST_CASE_MAP = {
|
|
"./01_return.c": 65536,
|
|
"./02_decl_expr.c": 1,
|
|
"./03_decl_init.c": 11,
|
|
"./04_if.c": 1,
|
|
"./05_else.c": 2,
|
|
"./06_fcall.c": 3,
|
|
"./07_while.c": 10,
|
|
"./08_do_while.c": 128,
|
|
"./09_for.c": 10,
|
|
"./10_main.c": 3,
|
|
"./11_recursive.c": 120,
|
|
}
|
|
|
|
def run_command(cmd, capture_stderr=True):
|
|
"""执行命令并捕获stderr"""
|
|
result = subprocess.run(
|
|
cmd,
|
|
cwd=WORKSPACE,
|
|
stderr=subprocess.PIPE if capture_stderr else None,
|
|
text=True,
|
|
timeout=1,
|
|
)
|
|
return result.stderr.strip() if capture_stderr else None
|
|
|
|
def run_test(test_file, expected):
|
|
print(f"\nTesting {test_file}...")
|
|
|
|
# 1. 编译生成flat.bin
|
|
compile_cmd = [str(CC_PATH), str(test_file)]
|
|
compile_err = run_command(compile_cmd)
|
|
|
|
if not (WORKSPACE / "flat.bin").exists():
|
|
print(f" Compilation failed: {compile_err}")
|
|
return False
|
|
|
|
# 2. 执行虚拟机
|
|
vm_cmd = [str(VM_PATH), "flat.bin"]
|
|
|
|
# 3. 解析返回值(假设最后一行是返回值)
|
|
try:
|
|
vm_err = run_command(vm_cmd)
|
|
actual = int(vm_err.split()[-1])
|
|
except (ValueError, IndexError) as e:
|
|
print(f" Invalid VM output: {vm_err}")
|
|
return False
|
|
except subprocess.TimeoutExpired:
|
|
print(" Timeout expired")
|
|
return False
|
|
|
|
# 4. 验证结果
|
|
if actual == expected:
|
|
print(f" PASSED {test_file}")
|
|
return True
|
|
else:
|
|
print(f" FAILED: Expected {expected}, got {actual}")
|
|
return False
|
|
|
|
def main():
|
|
passed = 0
|
|
total = 0
|
|
|
|
for test_file, expected in TEST_CASE_MAP.items():
|
|
total += 1
|
|
if run_test(TEST_DIR / test_file, expected):
|
|
passed += 1
|
|
|
|
# 清理中间文件
|
|
if (WORKSPACE / "flat.bin").exists():
|
|
os.remove(WORKSPACE / "flat.bin")
|
|
|
|
print(f"\nTest Summary: {passed}/{total} passed")
|
|
|
|
if __name__ == "__main__":
|
|
main() |