python - 如何使用autouse=True 生成由fixture 提供的对象?

标签 python pytest

是否有某种方法可以从自动使用装置中获取生成的对象,而无需在测试函数中显式提供它作为输入参数?

比如说,我有这样的东西:

@pytest.fixture(scope="function", autouse=True)
def setup_something():
    something = Something()
    something.do_something(thing=1)
    yield something

然后,当我想访问这个对象时,我会这样做:

def test_scenario(self):
    something.do_something_else()

原因是可能有很多设置/拆卸装置,它们提供一些对象或执行其他操作,并且将它们全部作为参数提及可能太麻烦。

最佳答案

您可以设置测试类实例的属性,但我不确定这是否是一个好主意。

import pytest

@pytest.fixture(scope="function", autouse=True)
def something(request):
    request.instance.something = Something()
    request.instance.something.do_something(thing=1)
    yield request.instance.something

class Test:
    def test_scenario(self):
        self.something.do_something_else()

关于python - 如何使用autouse=True 生成由fixture 提供的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59032607/

相关文章:

python - import numpy 和 import math 有什么区别

python - 为什么我的 IDE 无法自动完成 python-docx?

python - 如何将递归函数的中间结果放入列表中?

python - 如何在argparse中将store_true和值存储在互斥组中?

debugging - pytest:如何在测试的函数中显示来自logging.debug的消息

django - 当fixture范围为 'module'时,pytest + django给我一个数据库错误

python - 如何安装py.test?

python - 如何在pytest中测试类层次结构?

python - 我们可以在 pytest 的 setup_module() 或 setup_class 中打印命令行参数吗?

python - 我的 python 程序在 Windows 7 中运行良好并打印到控制台,但在 Linux Mint 中出现错误?