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

前言

好久都没有更新我的博客了,最近由于项目组变更,原来的项目的自动化工作停止了,我本人感到非常的遗憾和失落,毕竟这个自动化项目是我从零到一搭建起来的,我本人也是首次接触Web自动化测试,遇到不少坑,也是一路学习过来了,还是决定写一点东西记录一下吧。

Pytest如何实现失败用例自动截图

要实现这个功能具体使用到了pytest中的hook函数,所谓的hook函数通俗一点就是可以编写自己的插件函数,具体到代码如下:

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 具体实现有些差异。

你可能感兴趣的:(selenium,单元自动化框架)