python - 如何为其他 fixture 的每次运行运行一次 fixture

标签 python pytest fixtures

Conftest.py

@pytest.fixture(scope="module")
def fixture2(request):
    do something

@pytest.fixture(scope="session", params=[ 1, 2, 3 ])
def fixture1(request):
    do something else

测试文件.py

@pytest.mark.usefixtures('fixture2', 'fixture1')
class TestSomething1(object):
    def test_1(self):
        pass

    def test_2(self):
        pass

@pytest.mark.usefixtures('fixture1')
class TestSomething2(object):
    def test_3(self):
        pass

    def test_4(self):
        pass

发生的情况是我得到了 3 组测试(每次调用 Fixture1 各一组),但 Fixture2 仅针对所有 3 组测试运行一次(至少这是我的理解)。我不确定如何让它在每次运行fixture1时运行一次(而不是每次测试运行一次)。

我最终做了什么:

@pytest.fixture(scope="module")
def fixture2(request, fixture1):
    do something

@pytest.fixture(scope="session", params=[ 1, 2, 3 ])
def fixture1(request):
    do something else

最佳答案

@pytest.fixture(scope="module") 更改为其他内容,例如 @pytest.fixture(scope="class")@pytest .fixture(范围=“函数”)。 模块范围意味着每个模块运行一次。

来自 fixture 参数文档:

scope – the scope for which this fixture is shared, one of "function" (default), "class", "module", "package" or "session".

"package" is considered experimental at this time.

Pytest documentation on scopes

如果您希望每次调用一个固定装置时调用另一个固定装置一次,请使固定装置 1 依赖于固定装置 2 并使用相同的作用域。

关于python - 如何为其他 fixture 的每次运行运行一次 fixture ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54043472/

相关文章:

python - Pandas:如何根据系列模式进行分组

python - 需要帮助在 pygame 中创建按钮

python - 是否有必要在 tensorflow InteractiveSession() 之后关闭 session

python - 如何将额外的参数传递给我的 py.test 设置方法?

python - 无法在使用 Fixtures 的 Pytest 函数中实例化 Python 数据类(卡住)

python - 使用伪造的 mongoDB 进行 pytest 测试

python - 使用 BeautifulSoup Python 抓取网页

python - 报告 pyTest 中的断言数

python - 导入的类看不到 Pytest 环境装置

python - 如何在运行 Django 测试之前加载测试 yaml 文件?