HTMLTestRunner添加logging信息
作者:互联网
如果要在报告中加入每一个测试用例执行的logging信息,则需要改HTMLTestRunner的源码
1、初始化定义logging信息,
class _TestResult(TestResult): # note: _TestResult is a pure representation of results. # It lacks the output and reporting ability compares to unittest._TextTestResult. def __init__(self, verbosity=1): TestResult.__init__(self) self.stdout0 = None self.stderr0 = None self.success_count = 0 self.failure_count = 0 self.error_count = 0 self.verbosity = verbosity # result is a list of result in 4 tuple # ( # result code (0: success; 1: fail; 2: error), # TestCase object, # Test output (byte string), # stack trace, # ) self.result = [] #增加一个测试通过率 --Findyou self.passrate=float(0) #加入这行代码----------------------------------------------- self.logger = logging.getLogger('mylog') #已封装的log名称
2、在startTest函数中初始化logging.Handler,记录到内存中
def startTest(self, test): TestResult.startTest(self, test) # just one buffer for both stdout and stderr self.outputBuffer = io.StringIO() stdout_redirector.fp = self.outputBuffer stderr_redirector.fp = self.outputBuffer self.stdout0 = sys.stdout self.stderr0 = sys.stderr sys.stdout = stdout_redirector sys.stderr = stderr_redirector #----add logging output----fengf233,这个类加入以下部分 self.log_cap = io.StringIO() self.ch = logging.StreamHandler(self.log_cap) self.ch.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(levelname)s][%(asctime)s] [%(filename)s]->[%(funcName)s] line:%(lineno)d ---> %(message)s') self.ch.setFormatter(formatter) self.logger.addHandler(self.ch)
3、在complete_output函数的返回值中加入logging存在内存中的输出,用换行符隔开
def complete_output(self): """ Disconnect output redirection and return buffer. Safe to call multiple times. """ if self.stdout0: sys.stdout = self.stdout0 sys.stderr = self.stderr0 self.stdout0 = None self.stderr0 = None #add log out put ---fengf233修改 return self.outputBuffer.getvalue()+'\n'+self.log_cap.getvalue()
4、每个用例执行完后,最好清除handler,在stopTest函数中加入
def stopTest(self, test): # Usually one of addSuccess, addError or addFailure would have been called. # But there are some path in unittest that would bypass this. # We must disconnect stdout in stopTest(), which is guaranteed to be called. a = self.complete_output() #清除log的handle---fengf修改 self.logger.removeHandler(self.ch) return a
标签:logging,log,stdout,self,HTMLTestRunner,添加,stderr,output 来源: https://www.cnblogs.com/buchi-baicai/p/15980827.html