网站备案域名备案,一键生成微信小程序平台,国内做网站公司哪家好,沈阳定制网站开发公司fixture 是 pytest 中非常重要的功能#xff0c;大部分项目都可能会用到 fixture。
pytest 的内置标记 usefixtures 可以帮助用例自动的使用 fixture
1. 创建 fixture
pytest 中的 fixtures 大致有两个用途 在用例执行之前、执行之后#xff0c;自动的执行 通过 fixture … fixture 是 pytest 中非常重要的功能大部分项目都可能会用到 fixture。
pytest 的内置标记 usefixtures 可以帮助用例自动的使用 fixture
1. 创建 fixture
pytest 中的 fixtures 大致有两个用途 在用例执行之前、执行之后自动的执行 通过 fixture 为用例提供数据
pytest.fixture()def print_msg(): print(用例开始执行) # yeild 之前为前置 yieldprint(用例执行结束)# yeild 之后为前置pytest.fixturedef base_url(): yield https://www.baidu.com # yeild 指定返回值
当然了也可以同时实现两种用途
pytest.fixturedef base_url(): print(用例开始执行) # yeild 之前为前置 yield https://www.baidu.com # yeild 指定返回值 print(用例执行结束)# yeild 之后为前置
2. 请求 fixture
用例如果需要使用 fixture可以通过标记 usefixtures 来进行请求。
注意标记名是 s 结尾表明允许同时请求多个 fixture
test_name: 请求fixturemark: - usefixtures: - print_msg - base_urlsteps: - request: method: get url: http://baidu.com 执行结果如下 图 1. 请求 fixture 执行前后置操作
3. 使用 fixture 返回值
在 fixture 的第二个用途中会为用例提供数据。
那么用例该如何获取和使用这个数据呢一共有两种方式
第一种方式
如果该数据是字符串或数字可以直接写入 yaml 中使用的可采用【参数变量】的方式进行使用
test_name: fixture返回值mark: - usefixtures: - print_msg - base_urlsteps: - request: method: get url: ${base_url}/abc.html 执行结果如下 图 2. 使用 fixture 返回值
有结果可知用例使用来 fixture 的返回值来决定服务器地址 第二种方式
如果 fixture 返回值是一个对象不能直接作为 yaml 内容可在 hook 中更灵活的使用 首先创建 fixture
pytest.fixture()def driver(): obj webdriver.Chrome() yield obj 接着在 yaml 中请求 fixture
test_name: 在hook中使用fixturemark: - usefixtures: - driversteps: - request: method: get url: /abc.html 最后在 hook 中指定 fixture 返回值使用方式
def pytest_yaml_run_step(item): step item.current_step request step.get(request) fixture_client item.usefixtures.get(client) # 获取usefixtures中的fixture if fixture_client: fixture_client.request(**request) # 使用fixture发送请求 return
第二种方法为用例的执行方式提供更多的灵活和扩展性适合对 pytest 比较熟悉之后使用。
4. 参数化 fixture
pytest 的 fixture 也可以参数化其效果和 mark.parametrize 相似都会生成更多的用例来执行。
唯一的区别是 mark.parametrize 的参数值由用例提供写在 yaml 中 fixture 参数化的参数值由 fixture 提供写在 python 中
下面是一个参数化的 fixture
pytest.fixture(params[a, b, c])def name(request): return request.param
其返回值不是固定的而是依次将 a、b、c 作为返回值这使得请求该 fixture 的用例也湖执行 3 次。
test_name: fixture返回值mark: - usefixtures: - namesteps: - request: method: get url: https://www.baidu.com/?o${name} 执行结果如下 图 3. 使用参数化 fixture 能看到这里说明是真爱关注一下吧