2021-12-18 08:30:20
pytest测试框架01
pytest是一个功能全面的Python测试工具,兼容unittest测试框架,可以结合requests实现接口测试,支持三百多种插件,功能强大。以下是pytest测试框架的详细介绍:
安装:
使用pip安装pytest:pip install pytest
查看版本:pytest --version
用例识别与运行:
测试用例以test_开头或_test结尾。
测试类以Test开头,不能带有__init__方法。
测试函数以test_开头。
断言使用assert。
示例代码:
def add(x, y): return x + ydef test_add(): assert add(1, 10) == 11 assert add(1, 3) == 4 assert add(30, 20) == 50class TestClass: def test_one(self): x = 'this' assert 'h' in x def test_two(self): x = 'hello' assert hasattr(x, 'check')结果分析:
F代表轿仿岩用例未通过,.代表用例通过。
运行参数大哪:
pytest -v:打印日志。
pytest -s:打印输出。
pytest -k:执行含某个关键字的参数。
pytest -x:用例失败立即停止。
pytest -maxfail:用例失败达到一定值停止运行。
pytest -m:执行有@pytest.mark.[标记]的测试案例。
运行模式:
pytest test_.py
pytest test_.py::类名
pytest test_.py::类名::方法名
调用结构顺序:
模块级:setup_module/teardown_module,在模块始末调用。
函数级:setup_function/teardown_function,在函数始末调用。
类级:setup_class/teardown_class,在方法始末调用。
方法级:setup_method/teardown_method,在方法始末调用。
方法级:setup/teardown,在方法始末调用。
调用顺序:setup_module/teardown_module在整个模块使用一次,setup_class/teardown_class在类里面使用一次,setup_method/teardown_method每个方法前都会调用。一般用的最多的是setup/teardown和setup_class/teardown_class。
装饰器:
import pytest@pytest.fixture()def login(): print("登录方法")@pytest.fixture()def test_case(login): print(login)fixture里面有一个参数实现范围共享:@pytest.fixture(scope='module')。
usefixtures传入前置函数。
conftest文件:
可以将一些固定配置写闭御到这个文件里面。
conftest文件固定不可更改,与执行用例在一个文件夹下面,包含__init__文件,不需要导入,pytest会自动识别。
放到根目录下全局有效。