如何使用基于命令行参数的不同夹具实现?



我正在测试一个具有用户配置文件的应用程序。 通常,我在每次测试后都会撕毁配置文件, 但它很慢,所以我想可以选择通过以下方式更快地运行测试 保留配置文件,但在每次测试后拆除更改。

这就是我现在拥有的,它工作正常:

@pytest.fixture(scope="session")
def session_scope_app():
with empty_app_started() as app:
yield app

@pytest.fixture(scope="session")
def session_scope_app_with_profile_loaded(session_scope_app):
with profile_loaded(session_scope_app):
yield session_scope_app

if TEAR_DOWN_PROFILE_AFTER_EACH_TEST:
@pytest.fixture
def setup(session_scope_app):
with profile_loaded(session_scope_app):
yield session_scope_app
else:
@pytest.fixture
def setup(session_scope_app_with_profile_loaded):
with profile_state_preserved(session_scope_app_with_profile_loaded):
yield session_scope_app_with_profile_loaded

这会产生一个夹具setup,就其他测试而言, 无论配置文件在每次测试后是否被拆除,其行为方式都相同。

现在,我想TEAR_DOWN_PROFILE_AFTER_EACH_TEST变成命令行 选择。我该怎么做?命令行选项在测试收集阶段尚不可用, 而且我不能只是将if放入夹具功能主体中,因为setup的两种变体依赖于不同的夹具。

有两种方法可以做到这一点,但首先,让我们添加命令选项本身。

def pytest_addoption(parser):
parser.addoption("--tear-down-profile-after-each-test",
action="store_true",
default=True)
parser.addoption("--no-tear-down-profile-after-each-test", "-T",
action="store_false",
dest="tear_down_profile_after_each_test")

现在,我们可以动态调用夹具,也可以创建一个小插件来洗牌我们的夹具。

动态调用灯具

这很简单。而不是通过函数参数依赖于夹具, 我们可以从夹具内部呼叫request.getfixturevalue(name)

@pytest.fixture
def setup(session_scope_app):
if request.config.option.tear_down_profile_after_each_test:
with profile_loaded(session_scope_app):
yield session_scope_app
else:
session = request.getfixturevalue(
session_scope_app_with_profile_loaded.__name__
)
with profile_state_preserved(session):
yield session

(依赖session_scope_app是可以的,因为无论如何session_scope_app_with_profile_loaded都依赖于它。

优点:PyCharm很高兴。缺点:你不会在--setup-plan看到session_scope_app_with_profile_loaded.

制作一个简单的插件

插件的好处是可以访问配置。

def pytest_configure(config):
class Plugin:
if config.option.tear_down_profile_after_each_test:
@pytest.fixture
def setup(self, session_scope_app):
with profile_loaded(session_scope_app):
yield session_scope_app
else:
@pytest.fixture
def setup(self, session_scope_app_with_profile_loaded):
with profile_state_preserved(session_scope_app_with_profile_loaded):
yield session_scope_app_with_profile_loaded
config.pluginmanager.register(Plugin())

优点:你会得到优秀的--setup-plan。缺点:PyCharm不会重新承认setup是一个固定装置。

最新更新