Execute code if a test fails with py.test

2019-07-21 18:36发布

问题:

I'm doing UI test automation on Android using Appium and py.test. I'd like to be able to save a bug report using adb after a test fails.

Is there a way to tell if a test fails in my test code so I can then run save the bug report in the teardown?

Originally, I was just going to save the bug report after each test, but it's a bit excessive adding 45 seconds to each test.

回答1:

You can implement a pytest_runtest_logreport hook in your conftest.py like this:

def pytest_runtest_logreport(report):
    if report.when == 'call' and report.failed:
        # save bug report

For more information, see Woking with plugins and conftest files.