Selenium Pytest+Allure+Selenium 实现失败用例自动截图

better than yesterday · 2022年04月23日 · 最后由 清水 回复于 2024年01月17日 · 3473 次阅读

😀 以前都是在社区潜水,这次也想为社区做点贡献(其实是想把以前 CSDN 上的博客文章搬到社区,哈哈哈)
前言
好久都没有更新我的博客了,最近由于项目组变更,原来的项目的自动化工作停止了,我本人感到非常的遗憾和失落,毕竟这个自动化项目是我从零到一搭建起来的,我本人也是首次接触 Web 自动化测试,遇到不少坑,也是一路学习过来了,还是决定写一点东西记录一下吧。
Pytest 如何实现失败用例自动截图
要实现这个功能具体使用到了 pytest 中的 pytest_runtest_makereport 函数,该函数会在 pytest 生成测试报告的时候被调用,通过重写改方法加入截图功能,具体到代码如下:

def _fail_picture():    
    driver.fail_picture()    

#失败用例自动截图函数
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    hook pytest失败
    :param item:
    :param call:
    :return:
    '''
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")
        _fail_picture()



其中,_fail_picture 函数为截图函数,调用 get_screenshot_as_file 函数 ,get_screenshot_as_file 函数封装的是具体的 webdriver 截图功能实现。

def fail_picture(self):
    f = self.get_screenshot_as_file()
    self.log.debug('失败用例截图:{filename}'.format(filename=f))
    allure.attach.file(f, '失败用例截图:{filename}'.format(filename=f),   allure.attachment_type.PNG)

def get_screenshot_as_file(self):
    '''在本地截图函数'''
    try:
        pic_pth = self.conf.pic_path
        filename = pic_pth + str(time.time()).split('.')[0] + '.png'
        filename = filename.replace('\\', '/')
        self.webdriver.get_screenshot_as_file(filename)
        self.log.debug('get_screenshot_as_file {filename}'.format(filename=filename))
        return filename
    except Exception as e:
        self.log.error(e)
        return None

最后在 confest.py 文件中初始化用例即可:

//confest.py

driver = None
#  module confest
#初始化用例
@pytest.fixture(scope='module', autouse=False)
def Sys_user_manage_page():     
    print('初始化用例')
    global driver
    if driver is None:
        driver = Sys_user_manage('Chrome')      
        driver.login('superadmin', '123456')
    yield driver    
    print('结束用例')
    driver.close_Browser()  
    driver = None

# confest.py中定义截图函数
def _fail_picture():    
    driver.fail_picture()   

# 编写钩子函数
#失败用例自动截图函数
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    hook pytest失败
    :param item:
    :param call:
    :return:
    '''
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")
        _fail_picture()  #调用截图函数



由于我代码中的 driver 是封装过的,可能有些读者看不懂,请参考微博:
https://www.cnblogs.com/guo2733/p/10525755.html
这里需要注意的是因为不同的博主使用的报告插件不同(我用的是 allure,有些可能用 htmlout),造成 pytest_runtest_makereport 具体实现有些差异。

共收到 2 条回复 时间 点赞

大佬,看了你总结自动化成功落地感到开心,同时我也在学习 web 自动化框架,可以分享下源码吗

僅樓主可見
需要 登录 後方可回應,如果你還沒有帳號按這裡 注册