gpt4 book ai didi

python - pytest fixture 总是返回一个函数

转载 作者:太空狗 更新时间:2023-10-29 21:26:34 24 4
gpt4 key购买 nike

我希望能够将一个值从一个 fixture 返回到多个测试/测试类,但传递的值是一个函数。

这是我的代码:

import pytest

@pytest.fixture()
def user_setup():
user = {
'name': 'chad',
'id': 1
}
return user

@pytest.mark.usefixtures('user_setup')
class TestThings:
def test_user(self):
assert user_setup['name'] == 'chad'

输出是:

=================================== FAILURES ===================================
_____________________________ TestThings.test_user _____________________________

self = <tests.test_again.TestThings instance at 0x10aed6998>

def test_user(self):
> assert user_setup['name'] == 'chad'
E TypeError: 'function' object has no attribute '__getitem__'

tests/test_again.py:14: TypeError
=========================== 1 failed in 0.02 seconds ===========================

但如果我重写我的测试,使其不使用 usefixtures 装饰器,它会按预期工作:

def test_user(user_setup):
assert user_setup['name'] == 'chad'

知道为什么当我尝试使用装饰器方法时它不起作用吗?

最佳答案

当您使用 @pytest.mark.usefixtures 标记时,如果您希望将该 fixture 注入(inject)到您的测试函数中,您仍然需要提供一个类似命名的输入参数。

py.test docs for fixtures 中所述:

The name of the fixture function can later be referenced to cause its invocation ahead of running tests... Test functions can directly use fixture names as input arguments in which case the fixture instance returned from the fixture function will be injected.

所以只要使用 @pytest.mark.usefixtures 装饰器就只会调用函数。提供输入参数将为您提供该函数的结果。

只有当您想要调用 fixture 但不想将其作为测试的输入参数时,您才真正需要使用 @pytest.mark.usefixtures。如 py.test docs 中所述.

你得到一个关于 user_setup 是一个函数的异常的原因是因为在你的 test_user 函数中,名称 user_setup 实际上指的是您之前在文件中定义的函数。要让您的代码按预期工作,您需要向 test_user 函数添加一个参数:

@pytest.mark.usefixtures('user_setup')
class TestThings:
def test_user(self, user_setup):
assert user_setup['name'] == 'chad'

现在从 test_user 函数的角度来看,名称 user_setup 将引用函数参数,该参数将是 py.test 注入(inject)的 fixture 的返回值。

但实际上您根本不需要使用 @pytest.mark.usefixtures 装饰器。

关于python - pytest fixture 总是返回一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25559265/

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