"""
完整错误处理测试
"""
import sys
import io

# 设置UTF-8编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

sys.path.insert(0, 'g:/codeartswork/newlisp')

from repl import REPL

repl = REPL()

print("\n" + "="*60)
print("【文言心】完整错误处理测试")
print("="*60)

test_cases = [
    # Lexer错误
    ("英文逗号", "10加5,乘2。", "Lexer错误"),
    ("未闭合引号", "「1加2。", "Lexer错误"),

    # 正常代码
    ("基本运算", "1加2。", "正常"),
    ("管道操作", "10加5,乘2。", "正常"),
    ("列表构造", "列1 2 3。", "正常"),
    ("变量定义", "定x为10。", "正常"),
    ("条件表达式", "若1则2否则3。", "正常"),
    ("同像性", "行「1加2」。", "正常"),

    # Runtime错误
    ("未定义函数", "未知函数5。", "Runtime错误"),
]

passed = 0
failed = 0

for name, code, expected_type in test_cases:
    print(f"\n测试: {name}")
    print(f"代码: {code}")
    print("-" * 40)

    result = repl.execute(code)

    if expected_type == "正常":
        if "[错误]" not in str(result) and "错误:" not in str(result):
            print(f"结果: {result}")
            print("[OK] 通过")
            passed += 1
        else:
            print(f"结果: {result}")
            print("[FAIL] 失败")
            failed += 1
    else:
        if "[错误]" in str(result) or "错误:" in str(result):
            print(f"结果:\n{result}")
            print("[OK] 正确检测到错误")
            passed += 1
        else:
            print(f"结果: {result}")
            print("[FAIL] 未检测到错误")
            failed += 1

print("\n" + "="*60)
print(f"测试结果: {passed}通过, {failed}失败")
print(f"通过率: {passed/(passed+failed)*100:.1f}%")
print("="*60)

if failed == 0:
    print("\n[SUCCESS] 所有测试通过!错误处理系统完善!")
else:
    print(f"\n[WARNING] {failed}个测试失败")