feat: 新增 timer.py 计时器程序
This commit is contained in:
107
test_calculator.py
Normal file
107
test_calculator.py
Normal file
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
计算器功能测试
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from calculator import add, subtract, multiply, divide, calculate
|
||||
|
||||
def test_basic_operations():
|
||||
"""测试基本运算"""
|
||||
print("测试基本运算...")
|
||||
|
||||
# 测试加法
|
||||
assert add(5, 3) == 8
|
||||
assert add(-2, 3) == 1
|
||||
assert add(0, 0) == 0
|
||||
|
||||
# 测试减法
|
||||
assert subtract(10, 4) == 6
|
||||
assert subtract(3, 7) == -4
|
||||
assert subtract(0, 5) == -5
|
||||
|
||||
# 测试乘法
|
||||
assert multiply(4, 5) == 20
|
||||
assert multiply(-3, 2) == -6
|
||||
assert multiply(0, 100) == 0
|
||||
|
||||
# 测试除法
|
||||
assert divide(10, 2) == 5
|
||||
assert divide(7, 2) == 3.5
|
||||
assert divide(-12, 3) == -4
|
||||
|
||||
print("基本运算测试通过!")
|
||||
|
||||
def test_divide_by_zero():
|
||||
"""测试除零错误"""
|
||||
print("测试除零错误...")
|
||||
try:
|
||||
divide(5, 0)
|
||||
print("错误: 除零异常未触发")
|
||||
return False
|
||||
except ValueError as e:
|
||||
assert str(e) == "除数不能为零"
|
||||
print("除零错误测试通过!")
|
||||
return True
|
||||
|
||||
def test_calculate_function():
|
||||
"""测试计算函数"""
|
||||
print("测试calculate函数...")
|
||||
|
||||
# 测试有效表达式
|
||||
assert calculate("5 + 3") == 8
|
||||
assert calculate("10 - 4") == 6
|
||||
assert calculate("4 * 5") == 20
|
||||
assert calculate("10 / 2") == 5
|
||||
assert calculate("7.5 + 2.5") == 10.0
|
||||
assert calculate("-3 * 4") == -12
|
||||
|
||||
# 测试无效表达式
|
||||
test_cases = [
|
||||
("5 +", "表达式格式错误"),
|
||||
("+ 3", "表达式格式错误"),
|
||||
("5 + 3 4", "表达式格式错误"),
|
||||
("5 & 3", "不支持的运算符"),
|
||||
("abc + 3", "操作数必须是数字"),
|
||||
("5 / 0", "除数不能为零"),
|
||||
]
|
||||
|
||||
for expr, expected_error in test_cases:
|
||||
try:
|
||||
calculate(expr)
|
||||
print(f"错误: 表达式 '{expr}' 应触发错误但未触发")
|
||||
return False
|
||||
except (ValueError, RuntimeError) as e:
|
||||
if expected_error not in str(e):
|
||||
print(f"错误: 表达式 '{expr}' 返回错误 '{e}',但期望包含 '{expected_error}'")
|
||||
return False
|
||||
|
||||
print("calculate函数测试通过!")
|
||||
return True
|
||||
|
||||
def main():
|
||||
"""运行所有测试"""
|
||||
print("开始计算器测试...")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
test_basic_operations()
|
||||
test_divide_by_zero()
|
||||
test_calculate_function()
|
||||
|
||||
print("=" * 50)
|
||||
print("所有测试通过!")
|
||||
return 0
|
||||
except AssertionError as e:
|
||||
print(f"测试失败: {e}")
|
||||
return 1
|
||||
except Exception as e:
|
||||
print(f"测试过程中出现未知错误: {e}")
|
||||
return 1
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user