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

pytest fixture,每个测试都运行scope会话

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

    如果我错了,纠正我,但是如果一个固定装置定义为 scope="session" ,难道不应该只运行一次吗 pytest 跑?

    例如:

    import pytest
    
    @pytest.fixture
    def foo(scope="session"):
        print('foooooo')
    
    
    def test_foo(foo):
        assert False
    
    def test_bar(foo):
        assert False
    

    我有一些测试依赖于从一些API中检索的数据,而不是在每个测试中查询API,而是有一个fixture可以一次获取所有数据,然后每个测试使用它需要的数据。但是,我注意到,对于每个测试,都会向API发出一个请求。

    1 回复  |  直到 6 年前
        1
  •  2
  •   hoefling    6 年前

    那是因为你宣布的赛程不对。 scope 应该进入 pytest.fixture decorar参数:

    @pytest.fixture(scope="session")
    def foo():
        print('foooooo')
    

    在代码中,作用域保留为默认值 function ,这就是为什么每次测试都要运行fixture。