Python 测试入门
Alexander Levin
Data Scientist
常见问题:
这些问题都可能显著增加修复成本。
测试有助于:
我们需要测试以确保其满足规定的需求
测试用例:用于验证软件或系统正确性的步骤
assert 语句以飞机为例:
以上都是测试!目的是保障安全。

assert condition:用于测试 condition 是否为 True。False,Python 将抛出 AssertionError。pytest:一个流行的 Python 测试框架,便于编写测试。
使用 pytest 编写的"assert"测试示例:
import pytest
# A function to test
def squared(number):
return number * number
# A test function always starts with "test"
def test_squared():
assert squared(-2) == squared(2)
with 语句使用的 Python 对象# 写文件示例
with open("hello_world.txt", 'w') as hello_file:
hello_file.write("Hello world \n")
pytest.raises:当预期测试会抛出 Exception 时使用
import pytest
# A function to test
def division(a, b):
return a / b
# A test function
def test_raises():
with pytest.raises(ZeroDivisionError):
division(a=25, b=0)
测试:
测试实现:
pytest:强大的 Python 框架,简化测试流程assert:Python 关键字,在 pytest 中用于校验条件编写基础测试pytest.raises:上下文管理器,用于编写预期抛出 Exception 的测试Python 测试入门