Python3中使用HTMLTestRunner报No module named 'StringIO'解决方法

今天在学习使用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修改后,重新运行脚本发现一切正常并在相应路径下生成了测试报告,如图所示:

执行脚本代码参考:

 1 # coding=utf-8
 2 
 3 import unittest
 4 import os
 5 import HTMLTestRunner
 6 
 7 
 8 # 用例路径
 9 case_path = os.path.join(os.getcwd(), "case")
10 # 报告存放路径
11 report_path = os.path.join(os.getcwd(), "report")
12 
13 def all_case():
14     discover = unittest.defaultTestLoader.discover(case_path,
15                                                     pattern="test*.py",
16                                                     top_level_dir=None)
17     print(discover)
18     return discover
19 
20 if __name__ == '__main__':
21     # 返回实例
22     # runner = unittest.TextTestRunner()
23     # runner.run(all_case())
24 
25     # html报告文件路径
26     report_abspath = os.path.join(report_path, 'result.html')
27     fp = open(report_abspath, "wb")
28     runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
29                                            title=u'自动化测试报告,测试结果如下: ',
30                                            description=u'用例执行情况: ')
31 
32     # 调用add_case函数返回值
33     runner.run(all_case())
34     fp.close()

 

posted @ 2018-03-01 16:48  Mr.Gavin  阅读(636)  评论(0编辑  收藏  举报