为不同的测试赋予 Pytest 设备不同的范围 [英] Give Pytest fixtures different scopes for different tests

查看:53
本文介绍了为不同的测试赋予 Pytest 设备不同的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my test suite, I have certain data-generation fixtures which are used with many parameterized tests. Some of these tests would want these fixtures to run only once per session, while others need them to run every function. For example, I may have a fixture similar to:

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

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

and 2 parameterized tests, one which wants to use the same person for each test condition and one which wants a new person each time. Is there any way for this fixture to have scope="session" for one test and scope="function" for another?

推荐答案

James 的回答 没问题,但没有如果您从夹具代码中yield,则无济于事.这是一个更好的方法:

James' answer is okay, but it doesn't help if you yield from your fixture code. This is a better way to do it:

from contextlib import contextmanager

@pytest.fixture(session='session')
def multiple_usecase_fixture():
    yield "Some string"

@pytest.fixture(session='function')
def my_fixture_fun(multiple_usecase_fixture):
    with _fixture_impl(multiple_usecase_fixture) as result:
        yield result

@pytest.fixture(scope='module')
def my_fixture_mod(multiple_usecase_fixture):
    with _fixture_impl(multiple_usecase_fixture) as result:
        yield result

@pytest.fixture(scope='session')
def my_fixture_ses(multiple_usecase_fixture):
    with _fixture_impl(multiple_usecase_fixture) as result:
        yield result

@contextmanager
def _fixture_impl(multiple_usecase_fixture):
    # Rather long on complicated fixture implementation here
    print('SETUP: Fixture implmentation')
    yield
    print('TEARDOWN: Fixture implmentation')

通过这种方式,您仍然可以处理上下文固定装置.

This way you can still handle contextual fixtures.

Github issue 供参考:https://github.com/pytest-dev/pytest/issues/3425

Github issue for reference: https://github.com/pytest-dev/pytest/issues/3425

这篇关于为不同的测试赋予 Pytest 设备不同的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆