import os import subprocess import sys import time class Color: GREEN = '\033[92m' RED = '\033[91m' RESET = '\033[0m' def test_compiler(test_dir, should_fail): total_files = 0 passed_files = 0 has_failed_tests = False print(f'开始测试 {test_dir}:') for file in os.listdir(test_dir): if file.endswith('.ac'): total_files += 1 file_path = os.path.join(test_dir, file) start_time = time.time() result = subprocess.run(['./acpa', file_path], capture_output=True, text=True) elapsed_time = time.time() - start_time if should_fail: if 'error' not in result.stdout: print(f' {Color.RED}测试失败:{Color.RESET} {file_path} 应该编译失败,但是没有发现错误') has_failed_tests = True else: print(f' {Color.GREEN}测试通过:{Color.RESET} {file_path}') passed_files += 1 else: if 'error' in result.stdout: print(f' {Color.RED}测试失败:{Color.RESET} {file_path} 应该编译通过,但是发现错误。') has_failed_tests = True else: print(f' {Color.GREEN}测试通过:{Color.RESET} {file_path}') passed_files += 1 print(f' - 编译时间: {elapsed_time:.3f} 秒') print(f'在 {test_dir} 中共有 {total_files} 个测试文件,通过了 {passed_files} 个。\n') return has_failed_tests if __name__ == '__main__': has_failed_tests = test_compiler('tests/ok/', should_fail=False) has_failed_tests |= test_compiler('tests/fail/', should_fail=True) if has_failed_tests: sys.exit(1)