今天在学习使用HTMLTestRunner生成测试报告时遇到一个报错,如图所示:
网上搜索了下“No module named 'StringIO'”解决方法,原来我用的是Python 3.X版本,而下载的HTMLTestRunner适用于Python2.X(下载链接:http://tungwaiyip.info/software/HTMLTestRunner.html)
于是这里再做次“搬运工”,了解下如何在Python3中使用HTMLTestRunner报No module named 'StringIO'解决方法。
修改HTMLTestRunner.py文件:
(1)第94行,将import StringIO修改成import io
(2)第539行,将self.outputBuffer = StringIO.StringIO()修改成self.outputBuffer = io.StringIO()
(3)第631行,将print >>sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime)修改成print(sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime))
(4)第642行,将if not rmap.has_key(cls): 修改成if not cls in rmap:
(5)第766行,将uo = o.decode('latin-1')修改成uo = e
(6)第772行,将ue = e.decode('latin-1')修改成ue = e
HTMLTestRunner修改后,重新运行脚本发现一切正常并在相应路径下生成了测试报告,如图所示:
执行脚本代码参考:
# coding=utf-8 import unittest
import os
import HTMLTestRunner # 用例路径
case_path = os.path.join(os.getcwd(), "case")
# 报告存放路径
report_path = os.path.join(os.getcwd(), "report") def all_case():
discover = unittest.defaultTestLoader.discover(case_path,
pattern="test*.py",
top_level_dir=None)
print(discover)
return discover if __name__ == '__main__':
# 返回实例
# runner = unittest.TextTestRunner()
# runner.run(all_case()) # html报告文件路径
report_abspath = os.path.join(report_path, 'result.html')
fp = open(report_abspath, "wb")
runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
title=u'自动化测试报告,测试结果如下: ',
description=u'用例执行情况: ') # 调用add_case函数返回值
runner.run(all_case())
fp.close()