Skip to main content
 首页 » 编程设计

python 在 tearDown() 方法中截取测试失败的屏幕截图

2024年10月24日13lonelyxmas

我正在尝试在失败的测试结束时截取屏幕截图

我做了一些有用的事情,但是有一个问题: 它会截取失败后发生的每个测试的屏幕截图 - 例如: 1.测试通过:无截图 2.测试失败:截图 3.测试通过:截图 - 所以在第一个错误之后所有的测试都会得到一个截图

我知道这是 _resultForDoCleanups 方法的一个问题,在我的例子中不能用 _outcomeForDoCleanups.success 代替,因为我使用的是 python 2.7,而不是 3。

我的代码:

    def tearDown(self): 
            if self._test_has_failed(): 
                if not os.path.exists(SCREEN_DUMP_LOCATION): 
                    os.makedirs(SCREEN_DUMP_LOCATION) 
                for ix, handle in enumerate(self.driver.window_handles): 
                    self._windowid = ix 
                    self.driver.switch_to.window(handle) 
                    self.take_screenshot() 
            self.driver.quit() 
 
def _test_has_failed(self): 
        for method, error in self._resultForDoCleanups.errors: 
            if error: 
                return True 
        return False 
 
def _get_filename(self): 
    timestamp = datetime.now().isoformat().replace(':', '.')[:19] 
    return "{folder}/{classname}.{method}-window{windowid}-{timestamp}".format( 
        folder=SCREEN_DUMP_LOCATION, 
        classname=self.__class__.__name__, 
        method=self._testMethodName, 
        windowid=self._windowid, 
        timestamp=timestamp 
    ) 
 
def take_screenshot(self): 
    filename = self._get_filename() + ".png" 
    print "\n{method} SCREENSHOT AND HTML:\n".format( 
        method=self._testMethodName) 
    print 'screenshot:', filename 
    self.driver.get_screenshot_as_file(filename) 

请您参考如下方法:

您的代码非常接近您希望发生的事情。

此代码使用了@jonrsharpe 的注释

def tally(self): 
    return len(self._resultForDoCleanups.errors) + len(self._resultForDoCleanups.failures) 
 
def setUp(self): 
    self.errors_and_failures = self.tally() 
 
def tearDown(self): 
    if self.tally() > self.errors_and_failures: 
        # Take a screenshot 

在每个测试方法开始时,我们会发现有多少错误和失败。当我们到达 tearDown 方法时,我们的测试方法已经执行,我们将知道是否有错误。 tally 方法会比我们在测试方法之前设置的 self.errors_and_failures 变量高 1。

希望这就是您要找的。