【问题标题】:How to use pytest fixture in class constructor如何在类构造函数中使用 pytest 夹具
【发布时间】:2019-02-25 14:15:01
【问题描述】:

我正在使用 pytest 并尝试创建应该在我的项目的许多类中使用的对象。 我正在尝试将对象传递给其中一个类,但 pycharm 显示“未解析的引用 'custom_inst'。

这是我的代码:

conftest.py:

@pytest.fixture(scope="function", autouse=True)
def fixture_example(request):
    custom_inst = FixtureClass()
    yield custom_inst
    custom_inst.do_something()

某类:

@pytest.mark.usefixtures('fixture_example')
class DummyClass(object):
    def __init__(self, arg1=None, arg2=None):
        self.arg1 = arg1
        self.arg2 = arg2
        self.custom_inst = fixture_example

如何将实例“custom_inst”作为类成员传递给我的 DummyClass?

谢谢。

【问题讨论】:

  • 明白,谢谢

标签: pytest fixtures


【解决方案1】:

问题是你尝试混合 pytest 实体(fixture)和非 pytest 实体(类 DummyClass)。

在这种情况下,DummyClass 永远不会被 pytest 执行,因为 pytest runner 收集并执行 start from "Test" keyword only 的类。 另一方面,如果你直接调用 DummyClass(),fixture_example 将不会执行,因为只有 pytest runner 使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    相关资源
    最近更新 更多