Pytest在一个函数中使用相同的fixture两次

我用Dummy类来实现fixture功能。那就从你的测试中打出来。提供明确的方法名称,以便更好地理解您的测试在做什么。 在

import pytest
@pytest.fixture
def login():
class Dummy:
def make_user(self):
return 'New user name'
return Dummy()
def test_something(login):
a = login.make_user()
b = login.make_user()
assert a == b

诀窍是利用标记参数化使用“间接”开关,因此:

@pytest.fixture
def data_repeated(request):
return [deepcopy({'a': 1, 'b': 2}) for _ in range(request.param)]
@pytest.mark.parametrize('data_repeated', [3], indirect=['data_repeated'])
def test(data_repeated):
assert data_repeated == [
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2}]

pytest.mark.parametrize里面indirect参数详细解释
@pytest.mark.parametrize里面indirect参数,默认是False
False: 就是parametrize里面argnames 参数当作一个普通的变量,不会去找变量对应函数的名的方法
True: 就是parametrize里面argnames 参数当作函数执行,它会去找对应的函数,去执行

另一种方法是复制fixture函数。这既简单又正确地处理了参数化fixture,并使用两个fixture的所有参数组合调用test函数。下面的示例代码引发了9个断言:

import pytest
@pytest.fixture(params=[0, 1, 2])
def first(request):
return request.param
second = first
def test_double_fixture(first, second):
assert False, '{} {}'.format(first, second)
posted @   hanfe1  阅读(98)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2020-12-24 jwt揭秘(含源码示例和视频)
2020-12-24 jquery操作cookie
点击右上角即可分享
微信分享提示