背景:

我将 py.test 与 pytest-selenium 一起使用,现在我想在断言失败时截取页面的屏幕截图。

目前我已经在我的基页对象类中定义了小助手方法:

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)
        )

问题是我想让它自动化机制而不是“手动”使用:
(测试类示例):
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')

如何为每个断言失败运行某些方法?

最佳答案

我个人没有使用过,但这可能是您的解决方案:
https://pytest.org/latest/example/simple.html#writing-well-integrated-assertion-helpers

这也可以帮助:
https://pytest.org/latest/assert.html#advanced-assertion-introspection

关于python - 如何在每个 py.test 断言失败时调用方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37340865/

10-09 15:52