python web自动化测试中失败截图方法汇总

在使用web自动化测试中,用例失败则自动截图的网上也有,但实际能落地的却没看到,现总结在在实际应用中失败截图的几种方法:

一、使用unittest框架截图方法:

  1、在tearDown中写入截图的功能,如下:

      

import sys
class
SeleniumTest(unittest2.TestCase): ... def tearDown(self): if sys.exc_info()[0]: test_method_name = self._testMethodName self.driver.save_screenshot("Screenshots/%s.png" % test_method_name) super(SeleniumTest, self).tearDown()

注意,self._testMethodName是unittest特有的,在其它框架中不使用

        在测试中,如果用例失败,就会自动以对应的测试函数名为文件名截图存储

 

2、自定义函数,重写unittest中的run方法:

class ScreenShotUtil:
    "Screenshot Utility Class"

    @staticmethod
    def take_screenshot(webdriver, file_name="error.png"):
        """
        @param webdriver: WebDriver.
        @type webdriver: WebDriver
        @param file_name: Name to label this screenshot.
        @type file_name: str 
        """
        if isinstance(webdriver, remote.webdriver.WebDriver):
            # Get Screenshot over the wire as base64
            base64_data = webdriver.get_screenshot_as_base64()
            screenshot_data = base64.decodestring(base64_data)
            screenshot_file = open(filename, "w")
            screenshot_file.write(screenshot_data)
            screenshot_file.close()
        else:
            webdriver.save_screenshot(filename)

在引中unittest时,重写run方法:

...
class ScreenCaptureTestCase(unittest.TestCase):
...
    # Defining an init method so we can pass it a webdriver.
    def __init__(self, methodName='runTest', webdriver=None, screenshot_util=None):
        super(WDBaseTest, self).__init__(methodName)
        
        if webdriver_provider == None:
            self._webdriver = WebDriverSingleton.get_instance()
        else:
            self._webdriver = webdriver

        if screenshot_util == None:
            self._screenshot_util = WebScreenShotUtil
        else:
            self._screenshot_util = screenshot_util 
    ...
def run(self, result=None):
        """
        这里重写run方法
        """
        orig_result = result
        if result is None:
            result = self.defaultTestResult()
            startTestRun = getattr(result, 'startTestRun', None)
            if startTestRun is not None:
                startTestRun()
            ... more pyunit code ...
                except self.failureException:
                    # Insert our Take Screenshot on test failure code.
                    fname = str(self).replace("(", "").replace(")", "").replace(" ", "_")
                    fmt='%y-%m-%d_%H.%M.%S_.PNG'
                    filename = datetime.datetime.now().strftime(fmt)
                    self._screenshot_util.take_screenshot(self._webdriver, filename)
                    result.addFailure(self, sys.exc_info())
            ... more pyunit code...
                except:
                    # Do the same thing again for errors.
                    fname = str(self).replace("(", "").replace(")", "").replace(" ", "_")
                    fmt='%y-%m-%d_%H.%M.%S_.PNG'
                    filename = datetime.datetime.now().strftime(fmt)
                    self._screenshot_util.take_screenshot(self._webdriver, filename)
                    result.addError(self, sys.exc_info())

...

完成后,测试时,失败则会已时间来截图,当然你也可以将filename按你喜好定义

 

二、nose框架失败截图

nose框架是unittest的优化,在实际使用中可以继承unittest.TestCase的方法后继续使用中的方法1,如果没导入unittest.TestCase时,也可以使用方法1,但要作小改动,如下:

1、tearDown写截图

class SeleniumTest(unittest2.TestCase):
    ...

    def tearDown(self):
        if sys.exc_info()[0]:
            test_method_name = test_names = [n for n in dir(self) if n.startswith('test_')][0]   #注意了,这里与unittest的不一样
            self.driver.save_screenshot("Screenshots/%s.png" % test_method_name)
        super(SeleniumTest, self).tearDown()

2、修改nose源码,未完待续

posted @ 2017-03-17 15:25  Believer007  阅读(5675)  评论(2编辑  收藏  举报