pytest
1、查看版本
import pytest print(pytest.__version__) 运行结果:8.4.1 print(pytest.version_tuple) 运行结果:(8, 4, 1)
2、常用函数
- pytest.skip
方法1: # 使用带有可选 skip 装饰器标记,该装饰器可以传递一个可选的 reason 参数: @pytest.mark.skip(reason="no way of currently testing this") def test_the_unknown(): ... 方法2: # 在测试执行或设置过程中通过调用 pytest.skip(reason) 函数来显式跳过 def test_function(): if not valid_config(): pytest.skip("unsupported configuration")
- pytest.skip
# 根据条件跳过某些内容 import sys @pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.10 or higher") def test_function(): ...
- pytest.fail——标记测试函数为预期失败
方法1: @pytest.mark.xfail(reason="xxxxx") def test_function(): ... 方法2: def test_function(): if not valid_config(): pytest.xfail("failing configuration (but should work)")
- pytest.exit()——结束测试进程
- pytest.param()——在 pytest.mark.parametrize 调用或 参数化 fixture 中指定参数。
- pytest.raises——异常断言
3、常用标记
pytest.mark.parametrize——参数化
pytest.mark.skip——跳过
pytest.mark.skipif——有条件的跳过
pytest.mark.usefixtures——将测试函数标记为使用指定的 fixture 名称
pytest.mark.xfail——标记为预期失败
4、测试夹具
@pytest.fixture
scope –该 fixture 共享的范围
params – 一个可选的参数列表
autouse – 如果为 True,则 fixture func 对所有能看见它的测试都生效
name – 固定装置的名称