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

标签 python testing fixtures pytest

我希望能够将一个值从一个 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/

相关文章:

javascript - 以编程方式检索页面上的 javascript 错误计数

Symfony2 测试 : Why should I use fixtures instead of managing data directly in test?

python - 使用 PyTorch 实现自定义数据集

python - 生成器类的实例(递归)

python - datetime.datetime.strptime 将字符串转换为日期时间时出现错误 未转换日期 remands : 2

ruby-on-rails - 功能测试中的请求格式

node.js - 使用 Lambda 的测试功能进行测试时获得响应 "Null"

ruby-on-rails - 使用错误的外键加载固定装置

python - 过滤 pytest 固定装置

python - 如何将多个查询集组合/合并为单个查询集 django