How to call method on every py.test assertion failure?

Submitted 4 years, 7 months ago
Ticket #163
Views 329
Language/Framework Python
Priority Low
Status Closed

Background:

I'm using py.test together with pytest-selenium, now I would like to take a screenshot of page when assertion fails.

Currently I have defined small helper method in my base page object class:

class PageBase(object):
    def __init__(self,driver):
        self.driver = driver
        self.fake = Factory.create()

    def screenshot(self,name):
        self.driver.save_screenshot(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + 'scr_'+name+'.png')

    @contextmanager
    def wait_for_page_load(self, timeout=45):
        old_page = self.driver.find_element_by_tag_name('html')
        yield
        WebDriverWait(self.driver, timeout).until(
            EC.staleness_of(old_page)
        )

The problem is that I would like to make it automated mechanism instead of "manual" usage: (test class example):

class TestLogin:
    @allure.feature('Ability to login into admin panel')
    def test_admin_login(self, prepare, page):

        print URLMap.admin('test')
        driver = prepare
        driver.get(URLMap.admin(page))

        login_page = LoginPage(driver)
        assert login_page.is_page_correct(),'Login page not loaded correctly'

        login_page.fill_login_data('testadmin','testadmin')
        login_page.click_login_button()
        assert login_page.is_user_logged_in(),'User cannot log in with provided credentials'
        login_page.screenshot(page+'_logged_in')

How to run certain method for every assertion failure?

Submitted on Sep 13, 20
add a comment

1 Answer

Verified

You can achieve exactly what you want without absolutely any code modification with pytest --pdb.

With your example:

import pytest
def test_abc():
    a = 9
    assert a == 10, "some error message"

Run with --pdb:

py.test --pdb
collected 1 item

test_abc.py F
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> traceback >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    def test_abc():
        a = 9
>       assert a == 10, "some error message"
E       AssertionError: some error message
E       assert 9 == 10

test_abc.py:4: AssertionError
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> /private/tmp/a/test_abc.py(4)test_abc()
-> assert a == 10, "some error message"
(Pdb) p a
9
(Pdb)

As soon as a test fails, you can debug it with the builtin python debugger. If you're done debugging, you can continue with the rest of the tests.

Submitted 4 years, 6 months ago


Latest Blogs