Python2:重写unittest.fail()

时间:2015-07-23 07:36:46

标签: python python-unittest

我有一个相当大的测试套件,需要改变unittest.fail()

的行为

具体来说,我想在测试失败的时候保存所有应用程序日志:

class SomeTests(unittest.TestCase):    
    [....]
    def fail(self, msg=None):
        self.save_all_logs()
        <<call regular unittest.fail()>>

如何正确实施&#34;调用常规unittest.fail()&#34; 行?

另外,如果以这种方式覆盖unittest.fail(),那么当测试通过例如unittest.assertTrue()失败时,是否会调用此overriden方法?

1 个答案:

答案 0 :(得分:1)

以供将来参考,代码如下所示:

def fail(self, msg=None, calling_method=None):
    # save all logs with fail() caller test name and timestamp
    fail_timestamp = lib.generate_now_timestamp()
    if not calling_method:
        # probably the fail() won't be deeper in stack than 10
        for depth in xrange(10):
            try:
                calling_method = str(sys._getframe(depth).f_code.co_name)
            except ValueError:
                print 'Error: test method not found in calling stack. ' \
                      'Fix your testing code or this fail() override.'
                super(SomeTest, self).fail(msg)
            if 'test' in calling_method:
                break

    print 'DEBUG: calling method: ' + calling_method
    logs_location = self.save_all_logs(calling_method, fail_timestamp)

    super(SomeTest, self).fail(msg + '\nLogs are located in: ' + logs_location)