gpt4 book ai didi

python - 如何将固定装置传递给 pytest.mark.parametrize?

转载 作者:太空狗 更新时间:2023-10-30 00:58:53 28 4
gpt4 key购买 nike

我正在尝试将三个不同的固定装置传递给我的 pytest.mark.parameterize 装饰器,如下所示:

@pytest.mark.parametrize("credentials, return_code", [
(user1, 200),
#(user2, 200),
#(user3, 401)
])
def test_login():
assert True
# Actual test uses response.return_code == return_code

但是,我收到一条错误消息:

NameError: name 'user1' is not defined

虽然这是不正确的,我已经在 conftest.py 中定义了它:

user1_info = [('user1', 'password')]
@pytest.fixture(params=user1_info)
def user1(request):
return request.param

如果我把我的测试改成这样, fixture 就可以工作了:

def test_login(user1):
assert True
# Actual test uses response.return_code == return_code

问题是,如果我这样做,我必须编写三个单独的测试,一个用于每个 fixture ,一个用于每个 status_code 检查。如果我可以使用 parameterize,我可以使用一个函数并检查用户/预期的返回代码。

我如何利用我的固定装置作为 pytest.mark.parameterize 装饰器的一部分?

最佳答案

要将灯具作为参数化参数传递,请将它们作为字符串引用并使用关键字参数 indirect=['arg_name', ...]

然后使用参数名称 credentialsreturn_code 作为测试函数的参数。

@pytest.mark.parametrize(
"credentials, return_code",
[
("user1", 200),
("user2", 200),
("user3", 401),
],
# Only the `credentials` parameter is a reference to the
# fixture. The `return_code` should be passed as is.
indirect=["credentials"],
)
def test_login(credentials, return_code):
return True

pytest 的 parametrize 魔法与 indirect 的文档可以在这里找到: https://docs.pytest.org/en/stable/example/parametrize.html#apply-indirect-on-particular-arguments

关于python - 如何将固定装置传递给 pytest.mark.parametrize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47726000/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com