当前正值职业转换期,观察到 pytest
已成为自动化测试的主流框架。为了更好地学习实践并巩固知识,特此记录搭建 pytest
测试环境及基础使用的完整过程
pytest环境设置
pytest是python环境下的自动化测试框架, 需要安装python 3.8+.
安装python
1. 根据系统下载合适的python安装包Python Download
2. 执行python --version命令查看python是否安装成功。
安装pytest
1. 执行如下命令安装pytest自动化测试框架
pip install -U pytest
2. 执行如下命令查看pytest是否安装成功
pytest --version
创建并执行pytest脚本
pytest的默认规则
- python模块必须加上"test"前缀或者后缀, 比如"test_*.py"或者"*_test.py"
- 如果测试脚本在class类之外必须加"test_"前缀, 比如“test_add” 方法。
- 如果测试脚本在class类之内, class名要加上"Test"前缀同时测试方法也需要加上"test_"前缀
第一个pytest测试脚本
def add(a: int, b: int) -> int:
return a + b
class TestCalculator:
def test_add(self):
assert add(1,2) == 3
执行pytest测试脚本
在Terminal中执行pytest命令,pytest会根据默认规则找到所有的测试脚本并执行
验证期望的异常错误
可以使用pytest.raises关键字来验证测试脚本是否抛出期望的异常错误
import pytest
def my_function():
raise ZeroDivisionError("This is for pytest demo")
def test_my_function():
with pytest.raises(ZeroDivisionError):
my_function()
注意: pytest.raises会匹配给定的exception已经所有的子类, 测试过程中尽量给出准确的exception类型。
比如如下代码
def test_foo_not_implemented():
def foo():
raise NotImplementedError
with pytest.raises(RuntimeError) as excinfo:
foo()
assert excinfo.type is RuntimeError
该测试用例也会执行成功, 因为NotImplementedError是RuntimeError的子类。
class NotImplementedError(RuntimeError))
若想要获取具体的exception实列, 可以使用as关键字, 方法如下。 exception_info是ExceptionInfo类的实例。
import pytest
def my_function():
raise ZeroDivisionError("This is for pytest demo")
def test_my_function():
with pytest.raises(ZeroDivisionError) as exception_info:
my_function()
print(f"exception info: {exception_info}")
assert "pytest demo" in str(exception_info)
class ExceptionInfo(Generic[E]):
"""Wraps sys.exc_info() objects and offers help for navigating the traceback."""
输出log