如何仅在测试失败时运行夹具?
我有以下示例:
conftest.py:
@pytest.fixture:
def my_fixture_1(main_device)
yield
if FAILED:
-- code lines --
else:
pass
main.py:
def my_test(my_fixture_1):
main_device = ...
-- code lines --
assert 0
-- code lines --
assert 1
例如,当断言 0 时,测试应该失败并执行 my_fixture_1。如果测试通过,则夹具不得执行。我尝试使用hookimpl但没有找到解决方案,即使测试通过,夹具也始终在执行。
请注意,main_device 是运行测试的连接设备。
I have the following example:
conftest.py:
@pytest.fixture:
def my_fixture_1(main_device)
yield
if FAILED:
-- code lines --
else:
pass
main.py:
def my_test(my_fixture_1):
main_device = ...
-- code lines --
assert 0
-- code lines --
assert 1
When assert 0, for example, the test should fail and execute my_fixture_1. If the test pass, the fixture must not execute. I tried using hookimpl but didn't found a solution, the fixture is always executing even if the test pass.
Note that main_device is the device connected where my test is running.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Simon Hawe 的回答中,
request.session.testsfailed
表示该特定中的测试失败数量试运行。这是我能想到的替代解决方案。
您可以直接在 pytest_runtest_logreport 挂钩本身中进行实现。但缺点是除了报告之外您无法访问其他装置。
因此,如果您需要
main_device
,则必须使用如上所示的自定义固定装置。使用 @pytest.fixture(scope='function', autouse=True) 它将自动为每个测试用例运行它。您不必在所有测试函数中提供
main_device
作为参数。In Simon Hawe's answer,
request.session.testsfailed
denotes the number of test failures in that particular test run.Here is an alternative solution that I can think of.
You can do your implementations directly in the
pytest_runtest_logreport
hook itself. But the drawback is that you won't get access to the fixtures other than the report.So, if you need
main_device
, you have to go with a custom fixture like as shown above.Use
@pytest.fixture(scope='function', autouse=True)
which will automatically run it for every test case. you don't have to givemain_device
in all test functions as an argument.您可以使用
request
作为您的装置的参数。由此,您可以检查相应测试的状态,即是否失败。如果失败,您可以执行您希望在失败时执行的代码。在代码中,当然,固定装置将始终运行,但只有在相应的测试失败时才会执行分支。
You could use
request
as an argument to your fixture. From that, you can check the status of the corresponding tests, i.e. if it has failed or not. In case it failed, you can execute the code you want to get executed on failure. In code that reads asOf course, the fixture will always run but the branch will only be executed if the corresponding test failed.