pytest - 为不同的测试赋予 Pytest 设备不同的范围

标签 pytest fixtures

在我的测试套件中,我有一些数据生成装置,用于许多参数化测试。其中一些测试希望这些装置在每个 session 中只运行一次,而另一些则需要它们运行每个功能。例如,我可能有一个类似于:

@pytest.fixture
def get_random_person():
    return random.choice(list_of_people)

和 2 个参数化测试,一个想要在每个测试条件下使用同一个人,另一个想要每次都使用一个新人。这个装置有什么办法可以让一个测试的 scope="session"和另一个测试的 scope="function"?

最佳答案

这样做的一种方法是将实现分离出来,然后让 2 个不同范围的装置返回它。所以像:

def _random_person():
    return random.choice(list_of_people)

@pytest.fixture(scope='function')
def get_random_person_function_scope():
    return _random_person()

@pytest.fixture(scope='session')
def get_random_person_session_scope():
    return _random_person()

关于pytest - 为不同的测试赋予 Pytest 设备不同的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53749291/

相关文章:

python - Django 自然键不适用于固定装置?

python - ImportError 出现在 py.test 中,但在运行应用程序时不会出现

python - 如何恢复模拟

ruby-on-rails - 我如何将 rspec 与已清理的 YAML 固定装置一起使用?

unit-testing - Rails3 : Find method not working with fixtures in test environment

python - pytest-将 fixture 传递给mark.parametrize

python - 当日志在不同进程中发出时,caplog 中的空消息

python - 使用两个不同的 pytest 装置运行测试

python - 如何对具有覆盖范围的 sphinxdoc 扩展进行单元测试(在 PyCharm 中)?

python-3.x - python模式验证问题