jeudi 13 février 2020

How to capture screenshot on test case failure with PyTest

Currently I am using the following solution to take a screenshot in the end of every test function with PyTest. How can I make sure that the screenshots are taken only in case if a test fails? This is a question about PyTest mechanics. This question is NOT about selenium or appium.

I found similar questions here on Stackoverflow, but not exactly the same. Solutions provided to those other questions do not answer my question. Since taking a screenshot on a test failure with PyTest is a common problem, I believe that it deserves a separate and a quite specific answer.

@pytest.fixture(scope="function", autouse=True)
def take_screenshot(self, appium_driver):
    yield
    time.sleep(1)
    current_filename_clean = os.path.basename(__file__).replace("test_", "").replace(".py", "")
    current_test_name = os.environ.get("PYTEST_CURRENT_TEST").split(":")[-1].split(" ")[0].replace("test_", "")
    appium_driver.get_screenshot_as_file(
        f'test_reports/{current_filename_clean}_android_{current_test_name}_{datetime.today().strftime("%Y-%m-%d")}.png')

Aucun commentaire:

Enregistrer un commentaire