背景:
我正在使用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')
如何为每个断言失败运行某些方法?
答案 0 :(得分:0)
我个人没有用过,但这可能是你的解决方案: https://pytest.org/latest/example/simple.html#writing-well-integrated-assertion-helpers
这也有助于: https://pytest.org/latest/assert.html#advanced-assertion-introspection
答案 1 :(得分:0)
您必须使用钩子。 https://docs.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
setattr(item, "rep_" + rep.when, rep)
return rep
@pytest.fixture(autouse=True, scope='session')
def driver(platform, request):
""" some driver setup code """
yield driver
if request.node.rep_call.failed:
try:
driver.get_screenshot_as_png()
except:
pass
driver.quit()
如果要将屏幕截图附加到魅力报告中,只需执行以下操作:
@pytest.fixture(autouse=True, scope='session')
def driver(platform, request):
""" some driver setup code """
yield driver
if request.node.rep_call.failed:
# Make the screen-shot if test failed:
try:
allure.attach(
driver.get_screenshot_as_png(),
name=request.function.__name__,
attachment_type=allure.attachment_type.PNG)
except:
""" do something """
driver.quit()
答案 2 :(得分:-1)
我认为screenShotInSelenium页面应该为您提供有关在满足断言条件时如何创建屏幕截图的足够信息。
您缺少的是使用@AfterMethod