代码之家  ›  专栏  ›  技术社区  ›  The Illusive Man

我怎样才能以不同的方式编写它,使fixture不总是被调用?

  •  1
  • The Illusive Man  · 技术社区  · 6 年前

    我的测试套件有一个由所有测试共享的夹具。

    @pytest.fixture(scope="session")
    def foo_fixture():
        data = get_data()
        if not data:
            pytest.fail('ERROR: Could not get data', pytrace=False)
    

    然后我做了很多测试,基本上可以归结为:

    def test_foo(foo_fixture):
        assert something, pytest.fail('ERROR: ...', pytrace=False)
    
    def test_bar(foo_fixture):
        assert something, pytest.fail('ERROR: ...', pytrace=False)
    

    get_data() 不返回任何内容,每次测试都会调用fixture。我为什么知道这个?因为输出是:

    ____________________________________________________________________ ERROR at setup of test_foo ____________________________________________________________________
    ERROR: Could not get data
    ____________________________________________________________________ ERROR at setup of test_bar____________________________________________________________________
    ERROR: Could not get data
    

    正如你所看到的,我正在用 scope="session" pytest.fail

    那么,我如何以不同的方式编写它,使fixture只调用一次呢?什么时候 获取_数据() 实际上返回了一些东西,我可以注意到由于测试持续时间的原因,fixture只运行了一次。但正如我所说,当没有数据时,它会为每个测试运行,问题是 获取_数据()

    0 回复  |  直到 6 年前