1.fixture重命名

格式 @pytest.fixture(name=xxx) # name为别名,testcase可以引用别名
说明 【命令行】pytest —fixtures test_xxx.py # pytest将列举所有可供测试使用的fixture(包含重命名name)

  1. JsonData=myJsonData(filePath="../fixtureDemo/resource/my.json") # 数据与脚本分离
  2. @pytest.fixture(params=JsonData,name="jsondata") # name为别名,testcase可以引用别名
  3. def getJsonData(request):
  4. return request.param
  5. def test_hello2(jsondata):
  6. assert add(jsondata["a"], jsondata["b"]) == jsondata["result"]

image.png

2.fixture的hook函数

1.作用

通过命令行的方式,动态传入参数数据到testcase中

2.hook函数与参数化的区别

hook 【命令行】动态传参
参数化 不具备动态传参【参数化的数据是写死了的】
  1. # conftest.py
  2. def pytest_addoption(parser):
  3. parser.addoption('--foo',action='store',default='cooling',help='') # 根据实际的“参数值”进行定义
  4. @pytest.fixture()
  5. def getFoo(request):
  6. return request.config.getoption('--foo') # 根据实际的“参数值”进行定义
  7. # -----------------------------------------------------------------------------
  8. def test_hello1(getFoo):
  9. print("目前:\t",getFoo)

foo.png

3.fixture的cache

1.作用

会话重复(即记录失败的用例)。

2.应用场景

针对错误测试用例的定位上。

3.参数说明

  • —lf参数:只会运行上次“失败的测试用例”
  • —ff参数:首先运行上次“失败的用测”,然后运行其他测试用例

1.png

  • —cache-show参数 : 回顾错误的信息【说明:—cache-show后面不能带任何值】

2.png

  • —cache-clear参数 : 用于在测试用例开始之前清空cache的内容

格式 pytest —cache-clear 测试目录/测试文件等
clear.png

4.pytest.ini配置cache位置

  1. [pytest]
  2. cache_dir = .pytest-cache2021 # 自定义pytest-cache的存放位置,【推荐】位置放在项目根目录

dir.png