pytest-yaml-sanmu(七):使用fixture返回值

图片

fixture 是 pytest 中非常重要的功能,大部分项目都可能会用到 fixture。

pytest 的内置标记 usefixtures 可以帮助用例自动的使用 fixture

1. 创建 fixture

pytest 中的 fixtures 大致有两个用途

  1. 在用例执行之前、执行之后,自动的执行

  2. 通过 fixture 为用例提供数据

@pytest.fixture()def print_msg():    print('用例开始执行') #  yeild 之前为前置    yield
    print('用例执行结束')#  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

其返回值不是固定的,而是依次将 abc 作为返回值,这使得请求该 fixture 的用例也湖执行 3 次。

test_name: fixture返回值mark:  - usefixtures:      - namesteps:  - request:      method: get      url: https://www.baidu.com/?o=${name}

执行结果如下:

图片

图 3. 使用参数化 fixture

能看到这里说明是真爱,关注一下吧

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值