unittest:python自带的单元测试框架,兼容性好
pytest:单元测试框架,比自带框架更简洁高效
安装:
pip install pytest
入门案例
- 使用pycharm的terminal运行:
这里的文件名只能以test_开头,如果想运行所有的test_,建议使用命令行
import pytest
# 默认只能用test开头
def test_a():
print("test_a")
return 1 * 0
def test_b():
print("test_b")
return 1 / 0
# if __name__ == '__main__':
# pytest.main(["-s","test_py1.py"]) # 显示程序中打印的信息
pytest配置文件
[pytest]
addopts = -s 打印
testpaths = ./script 测试模块所在目录
python_files = test_*.py *test.py 测试模块文件名称规则 多个内容用空格分隔
python_classes = Demo* 测试类名称规则
python_functions = demo_* 测试函数或者方法的名称规则
断言
# 标记跳过
@pytest.mark.skip(reason='我先跳过')
def test_b():
print("test_b---++++---")
return 1 / 0
# 标记失败
@pytest.mark.xfail(raises=AssertionError)
def test_c():
print("test_c---++++---")
return 1 / 0
参数化
# 参数化
@pytest.mark.parametrize(["a", "b"], [(1, 2), (10, 20), (100, 20