关于python:Pythonunittestrequests-接口自动化测试框架搭建-完整的框架搭建过程-实战

1次阅读

共计 40197 个字符,预计需要花费 101 分钟才能阅读完成。

残缺的框架源码下载 https://gitee.com/submi_to/in…,欢送增加我的微信,互相学习探讨~1305618688,qq 交换群:849102042

一、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_00——框架结构简解

 首先配置好开发环境,下载安装 Python 并下载安装 pycharm,在 pycharm 中创立我的项目性能目录。如果不会的能够百度 Google 一下,该内容网上的解说还是比拟多比拟全的!

大家能够先简略理解下该项目标目录构造介绍,前面会针对每个文件有具体注解和代码。

common:

——configDb.py:这个文件次要编写数据库连接池的相干内容,本我的项目暂未思考应用数据库来存储读取数据,此文件可疏忽,或者不创立。自己是留着当前如果有相干操作时,方便使用。

——configEmail.py:这个文件次要是配置发送邮件的主题、注释等,将测试报告发送并抄送到相干人邮箱的逻辑。

——configHttp.py:这个文件次要来通过 get、post、put、delete 等办法来进行 http 申请,并拿到申请响应。

——HTMLTestRunner.py:次要是生成测试报告相干

——Log.py:调用该类的办法,用来打印生成日志

result:

——logs:生成的日志文件

——report.html:生成的测试报告

testCase:

——test01case.py:读取 userCase.xlsx 中的用例,应用 unittest 来进行断言校验

testFile/case:

——userCase.xlsx:对上面 test_api.py 接口服务里的接口,设计了三条简略的测试用例,如参数为 null,参数不正确等

caselist.txt:配置将要执行 testCase 目录下的哪些用例文件,前加 #代表不进行执行。当我的项目过于宏大,用例足够多的时候,咱们能够通过这个开关,来确定本次执行哪些接口的哪些用例。

config.ini:数据库、邮箱、接口等的配置项,用于不便的调用读取。

getpathInfo.py:获取我的项目绝对路径

geturlParams.py:获取接口的 URL、参数、method 等

readConfig.py:读取配置文件的办法,并返回文件中内容

readExcel.py:读取 Excel 的办法

runAll.py:开始执行接口自动化,我的项目工程部署结束后间接运行该文件即可

test_api.py:本人写的提供本地测试的接口服务

test_sql.py:测试数据库连接池的文件,本次我的项目未用到数据库,能够疏忽

二、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_01——测试接口服务

首先,咱们想搭建一个接口自动化测试框架,前提咱们必须要有一个可反对测试的接口服务。有人可能会说,当初咱们的环境不论测试环境,还是生产环境有现成的接口。然而,个别工作环境中的接口,不太满足咱们框架的各种条件。举例如,接口 a 可能是 get 接口 b 可能又是 post,等等等等。因而我决定本人写一个简略的接口!用于咱们这个框架的测试!

按第一讲的目录创立好文件,关上 test_api.py,写入如下代码

1.  import flask
    
2.  import json
    
3.  from flask import request
    

5.  '''
    
6.  flask:web 框架,通过 flask 提供的装璜器 @server.route() 将一般函数转换为服
    
7.  '''
    
8.  # 创立一个服务,把以后这个 python 文件当做一个服务
    
9.  server = flask.Flask(__name__)
    
10.  # @server.route() 能够将一般函数转变为服务 登录接口的门路、申请形式
    
11.  @server.route('/login', methods=['get', 'post'])
    
12.  def login():
    
13.      # 获取通过 url 申请传参的数据
    
14.      username = request.values.get('name')
    
15.      # 获取 url 申请传的明码,明文
    
16.      pwd = request.values.get('pwd')
    
17.      # 判断用户名、明码都不为空
    
18.      if username and pwd:
    
19.          if username == 'xiaoming' and pwd == '111':
    
20.              resu = {'code': 200, 'message': '登录胜利'}
    
21.              return json.dumps(resu, ensure_ascii=False)  # 将字典转换字符串
    
22.          else:
    
23.              resu = {'code': -1, 'message': '账号密码谬误'}
    
24.              return json.dumps(resu, ensure_ascii=False)
    
25.      else:
    
26.          resu = {'code': 10001, 'message': '参数不能为空!'}
    
27.          return json.dumps(resu, ensure_ascii=False)
    

29.  if __name__ == '__main__':
    
30.      server.run(debug=True, port=8888, host='127.0.0.1') 

执行 test_api.py,在浏览器中输出 http://127.0.0.1:8888/login?name=xiaoming&pwd=11199 回车,验证咱们的接口服务是否失常~

变更咱们的参数,查看不同的响应后果确认接口服务一切正常

三、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_02——配置文件读取

在咱们第二讲中,咱们曾经通过 flask 这个 web 框架创立好了咱们用于测试的接口服务,因而咱们能够把这个接口抽出来一些参数放到配置文件,而后通过一个读取配置文件的办法,不便后续的应用。同样还有邮件的相干配置~

按第一讲的目录创立好 config.ini 文件,关上该文件写入如下:



1.  # -*- coding: utf-8 -*-
    
2.  [HTTP]
    
3.  scheme = http
    
4.  baseurl = 127.0.0.1
    
5.  port = 8888
    
6.  timeout = 10.0
    

10.  [EMAIL]
    
11.  on_off = on;
    
12.  subject = 接口自动化测试报告
    
13.  app = Outlook
    
14.  addressee = songxiaobao@qq.com
    
15.  cc = zhaobenshan@qq.com
    

在 HTTP 中,协定 http,baseURL,端口,超时工夫。

在邮件中 on_off 是设置的一个开关,=on 关上,发送邮件,= 其余不发送邮件。subject 邮件主题,addressee 收件人,cc 抄送人。

在咱们编写 readConfig.py 文件前,咱们先写一个获取我的项目某门路下某文件绝对路径的一个办法。按第一讲的目录构造创立好 getpathInfo.py,关上该文件



1.  import os
    

3.  def get_Path():
    
4.      path = os.path.split(os.path.realpath(__file__))[0]
    
5.      return path
    

7.  if __name__ == '__main__':# 执行该文件,测试下是否 OK
    
8.      print('测试门路是否 OK, 门路为:', get_Path())
    

填写如上代码并执行后,查看输入后果,打印出了该项目标绝对路径:

持续往下走,同理,按第一讲目录创立好 readConfig.py 文件,关上该文件,当前的章节不在累赘



1.  import os
    
2.  import configparser
    
3.  import getpathInfo# 引入咱们本人的写的获取门路的类
    

5.  path = getpathInfo.get_Path()# 调用实例化,还记得这个类返回的门路为 C:UserssonglihuiPycharmProjectsdkxinterfaceTest
    
6.  config_path = os.path.join(path, 'config.ini')# 这句话是在 path 门路下再加一级,最初变成 C:UserssonglihuiPycharmProjectsdkxinterfaceTestconfig.ini
    
7.  config = configparser.ConfigParser()# 调用内部的读取配置文件的办法
    
8.  config.read(config_path, encoding='utf-8')
    

10.  class ReadConfig():
    

12.      def get_http(self, name):
    
13.          value = config.get('HTTP', name)
    
14.          return value
    
15.      def get_email(self, name):
    
16.          value = config.get('EMAIL', name)
    
17.          return value
    
18.      def get_mysql(self, name):# 写好,留当前备用。然而因为咱们没有对数据库的操作,所以这个能够屏蔽掉
    
19.          value = config.get('DATABASE', name)
    
20.          return value
    

23.  if __name__ == '__main__':# 测试一下,咱们读取配置文件的办法是否可用
    
24.      print('HTTP 中的 baseurl 值为:', ReadConfig().get_http('baseurl'))
    
25.      print('EMAIL 中的开关 on_off 值为:', ReadConfig().get_email('on_off'))
    

执行下 readConfig.py,查看数据是否正确

所有 OK

四、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_03——读取 Excel 中的 case

配置文件写好了,接口咱们也有了,而后咱们来依据咱们的接口设计咱们简略的几条用例。首先在前两讲中咱们写了一个咱们测试的接口服务,针对这个接口服务存在三种状况的校验。正确的用户名和明码,账号密码谬误和账号密码为空

咱们依据下面的三种状况,将对这个接口的用例写在一个对应的独自文件中 testFilecaseuserCase.xlsx,userCase.xlsx 内容如下:

紧接着,咱们有了用例设计的 Excel 了,咱们要对这个 Excel 进行数据的读取操作,持续往下,咱们创立 readExcel.py 文件



1.  import os
    
2.  import getpathInfo# 本人定义的外部类,该类返回我的项目的绝对路径
    
3.  #调用读 Excel 的第三方库 xlrd
    
4.  from xlrd import open_workbook
    
5.  # 拿到该我的项目所在的绝对路径
    
6.  path = getpathInfo.get_Path()
    

8.  class readExcel():
    
9.      def get_xls(self, xls_name, sheet_name):# xls_name 填写用例的 Excel 名称 sheet_name 该 Excel 的 sheet 名称
    
10.          cls = []
    
11.          # 获取用例文件门路
    
12.          xlsPath = os.path.join(path, "testFile", 'case', xls_name)
    
13.          file = open_workbook(xlsPath)# 关上用例 Excel
    
14.          sheet = file.sheet_by_name(sheet_name)# 取得关上 Excel 的 sheet
    
15.          # 获取这个 sheet 内容行数
    
16.          nrows = sheet.nrows
    
17.          for i in range(nrows):# 依据行数做循环
    
18.              if sheet.row_values(i)[0] != u'case_name':# 如果这个 Excel 的这个 sheet 的第 i 行的第一列不等于 case_name 那么咱们把这行的数据增加到 cls[]
    
19.                  cls.append(sheet.row_values(i))
    
20.          return cls
    
21.  if __name__ == '__main__':# 咱们执行该文件测试一下是否能够正确获取 Excel 中的值
    
22.      print(readExcel().get_xls('userCase.xlsx', 'login'))
    
23.      print(readExcel().get_xls('userCase.xlsx', 'login')[0][1])
    
24.      print(readExcel().get_xls('userCase.xlsx', 'login')[1][2])
    

后果为:

完全正确~

五、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_04——requests 申请

配置文件有了,读取配置文件有了,用例有了,读取用例有了,咱们的接口服务有了,咱们是不是该写对某个接口进行 http 申请了,这时候咱们须要应用 pip install requests 来装置第三方库,在 common 下 configHttp.py,configHttp.py 的内容如下:



1.  import requests
    
2.  import json
    

5.  class RunMain():
    

7.      def send_post(self, url, data):  # 定义一个办法,传入须要的参数 url 和 data
    
8.          # 参数必须依照 url、data 程序传入
    
9.          result = requests.post(url=url, data=data).json()  # 因为这里要封装 post 办法,所以这里的 url 和 data 值不能写死
    
10.          res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)
    
11.          return res
    

13.      def send_get(self, url, data):
    
14.          result = requests.get(url=url, params=data).json()
    
15.          res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)
    
16.          return res
    

18.      def run_main(self, method, url=None, data=None):  # 定义一个 run_main 函数,通过传过来的 method 来进行不同的 get 或 post 申请
    
19.          result = None
    
20.          if method == 'post':
    
21.              result = self.send_post(url, data)
    
22.          elif method == 'get':
    
23.              result = self.send_get(url, data)
    
24.          else:
    
25.              print("method 值谬误!!!")
    
26.          return result
    

29.  if __name__ == '__main__':  # 通过写死参数,来验证咱们写的申请是否正确
    
30.      result1 = RunMain().run_main('post', 'http://127.0.0.1:8888/login', {'name': 'xiaoming','pwd':'111'})
    
31.      result2 = RunMain().run_main('get', 'http://127.0.0.1:8888/login', 'name=xiaoming&pwd=111')
    
32.      print(result1)
    
33.      print(result2)
    

执行该文件,验证后果正确性:

咱们发现和浏览器中进行申请该接口,失去的后果统一,阐明没有问题,所有 OK

六、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_05——参数动态化

在上一讲中,咱们写了针对咱们的接口服务,设计的三种测试用例,应用写死的参数(result = RunMain().run_main(‘post’, ‘http://127.0.0.1:8888/login’, ‘name=xiaoming&pwd=’))来进行 requests 申请。本讲中咱们写一个类,来用于别离获取这些参数,来第一讲的目录创立 geturlParams.py,geturlParams.py 文件中的内容如下:



1.  import readConfig as readConfig
    

3.  readconfig = readConfig.ReadConfig()
    

5.  class geturlParams():# 定义一个办法,将从配置文件中读取的进行拼接
    
6.      def get_Url(self):
    
7.          new_url = readconfig.get_http('scheme') + '://' + readconfig.get_http('baseurl') + ':8888' + '/login' + '?'
    
8.          #logger.info('new_url'+new_url)
    
9.          return new_url
    

11.  if __name__ == '__main__':# 验证拼接后的正确性
    
12.      print(geturlParams().get_Url())
    

通过将配置文件中的进行拼接,拼接后的后果:http://127.0.0.1:8888/login? 和咱们申请的统一

七、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_06——unittest 断言

以上的咱们都筹备好了,剩下的该写咱们的 unittest 断言测试 case 了,在 testCase 下创立 test01case.py 文件,文件中内容如下:



1.  import json
    
2.  import unittest
    
3.  from common.configHttp import RunMain
    
4.  import paramunittest
    
5.  import geturlParams
    
6.  import urllib.parse
    
7.  # import pythoncom
    
8.  import readExcel
    
9.  # pythoncom.CoInitialize()
    

11.  url = geturlParams.geturlParams().get_Url()# 调用咱们的 geturlParams 获取咱们拼接的 URL
    
12.  login_xls = readExcel.readExcel().get_xls('userCase.xlsx', 'login')
    

14.  @paramunittest.parametrized(*login_xls)
    
15.  class testUserLogin(unittest.TestCase):
    
16.      def setParameters(self, case_name, path, query, method):
    
17.          """
    
18.   set params
    
19.   :param case_name:
    
20.   :param path
    
21.   :param query
    
22.   :param method
    
23.   :return:
    
24.   """
    
25.          self.case_name = str(case_name)
    
26.          self.path = str(path)
    
27.          self.query = str(query)
    
28.          self.method = str(method)
    

30.      def description(self):
    
31.          """
    
32.   test report description
    
33.   :return:
    
34.   """
    
35.          self.case_name
    

37.      def setUp(self):
    
38.          """
    

40.   :return:
    
41.   """42.          print(self.case_name+" 测试开始前筹备 ")
    

44.      def test01case(self):
    
45.          self.checkResult()
    

47.      def tearDown(self):
    
48.          print("测试完结,输入 log 完结 nn")
    

50.      def checkResult(self):# 断言
    
51.          """
    
52.   check test result
    
53.   :return:
    
54.   """55.          url1 ="http://www.xxx.com/login?"
    
56.          new_url = url1 + self.query
    
57.          data1 = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(new_url).query))# 将一个残缺的 URL 中的 name=&pwd= 转换为 {'name':'xxx','pwd':'bbb'}
    
58.          info = RunMain().run_main(self.method, url, data1)# 依据 Excel 中的 method 调用 run_main 来进行 requests 申请,并拿到响应
    
59.          ss = json.loads(info)# 将响应转换为字典格局
    
60.          if self.case_name == 'login':# 如果 case_name 是 login,阐明非法,返回的 code 应该为 200
    
61.              self.assertEqual(ss['code'], 200)
    
62.          if self.case_name == 'login_error':# 同上
    
63.              self.assertEqual(ss['code'], -1)
    
64.          if self.case_name == 'login_null':# 同上
    
65.              self.assertEqual(ss['code'], 10001)
    

八、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_07——HTMLTestRunner

按我的目录构造,在 common 下创立 HTMLTestRunner.py 文件,内容如下:



1.  # -*- coding: utf-8 -*-
    
2.  """
    
3.  A TestRunner for use with the Python unit testing framework. It
    
4.  generates a HTML report to show the result at a glance.
    
5.  The simplest way to use this is to invoke its main method. E.g.
    
6.      import unittest
    
7.      import HTMLTestRunner
    
8.      ... define your tests ...
    
9.      if __name__ == '__main__':
    
10.          HTMLTestRunner.main()
    
11.  For more customization options, instantiates a HTMLTestRunner object.
    
12.  HTMLTestRunner is a counterpart to unittest's TextTestRunner. E.g.
    
13.      # output to a file
    
14.      fp = file('my_report.html', 'wb')
    
15.      runner = HTMLTestRunner.HTMLTestRunner(
    
16.                  stream=fp,
    
17.                  title='My unit test',
    
18.                  description='This demonstrates the report output by HTMLTestRunner.'
    
19.                  )
    
20.      # Use an external stylesheet.
    
21.      # See the Template_mixin class for more customizable options
    
22.      runner.STYLESHEET_TMPL = '<link rel="stylesheet"href="my_stylesheet.css"type="text/css">'
    
23.      # run the test
    
24.      runner.run(my_test_suite)
    
25.  ------------------------------------------------------------------------
    
26.  Copyright (c) 2004-2007, Wai Yip Tung
    
27.  All rights reserved.
    
28.  Redistribution and use in source and binary forms, with or without
    
29.  modification, are permitted provided that the following conditions are
    
30.  met:
    
31.  * Redistributions of source code must retain the above copyright notice,
    
32.    this list of conditions and the following disclaimer.
    
33.  * Redistributions in binary form must reproduce the above copyright
    
34.    notice, this list of conditions and the following disclaimer in the
    
35.    documentation and/or other materials provided with the distribution.
    
36.  * Neither the name Wai Yip Tung nor the names of its contributors may be
    
37.    used to endorse or promote products derived from this software without
    
38.    specific prior written permission.
    
39.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    
40.  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    
41.  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    
42.  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
    
43.  OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    
44.  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    
45.  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    
46.  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    
47.  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    
48.  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    
49.  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    
50.  """
    

52.  # URL: http://tungwaiyip.info/software/HTMLTestRunner.html
    

54.  __author__ = "Wai Yip Tung"
    
55.  __version__ = "0.9.1"
    

57.  """
    
58.  Change History
    
59.  Version 0.9.1
    
60.  * 用 Echarts 增加执行状况统计图 (灰蓝)
    
61.  Version 0.9.0
    
62.  * 改成 Python 3.x (灰蓝)
    
63.  Version 0.8.3
    
64.  * 应用 Bootstrap 稍加丑化 (灰蓝)
    
65.  * 改为中文 (灰蓝)
    
66.  Version 0.8.2
    
67.  * Show output inline instead of popup window (Viorel Lupu).
    
68.  Version in 0.8.1
    
69.  * Validated XHTML (Wolfgang Borgert).
    
70.  * Added description of test classes and test cases.
    
71.  Version in 0.8.0
    
72.  * Define Template_mixin class for customization.
    
73.  * Workaround a IE 6 bug that it does not treat <script> block as CDATA.
    
74.  Version in 0.7.1
    
75.  * Back port to Python 2.3 (Frank Horowitz).
    
76.  * Fix missing scroll bars in detail log (Podi).
    
77.  """
    

79.  # TODO: color stderr
    
80.  # TODO: simplify javascript using ,ore than 1 class in the class attribute?
    

82.  import datetime
    
83.  import sys
    
84.  import io
    
85.  import time
    
86.  import unittest
    
87.  from xml.sax import saxutils
    

90.  # ------------------------------------------------------------------------
    
91.  # The redirectors below are used to capture output during testing. Output
    
92.  # sent to sys.stdout and sys.stderr are automatically captured. However
    
93.  # in some cases sys.stdout is already cached before HTMLTestRunner is
    
94.  # invoked (e.g. calling logging.basicConfig). In order to capture those
    
95.  # output, use the redirectors for the cached stream.
    
96.  #
    
97.  # e.g.
    
98.  #   >>> logging.basicConfig(stream=HTMLTestRunner.stdout_redirector)
    
99.  #   >>>
    

101.  class OutputRedirector(object):
    
102.      """Wrapper to redirect stdout or stderr"""
    

104.      def __init__(self, fp):
    
105.          self.fp = fp
    

107.      def write(self, s):
    
108.          self.fp.write(s)
    

110.      def writelines(self, lines):
    
111.          self.fp.writelines(lines)
    

113.      def flush(self):
    
114.          self.fp.flush()
    

117.  stdout_redirector = OutputRedirector(sys.stdout)
    
118.  stderr_redirector = OutputRedirector(sys.stderr)
    

121.  # ----------------------------------------------------------------------
    
122.  # Template
    

125.  class Template_mixin(object):
    
126.      """
    
127.      Define a HTML template for report customerization and generation.
    
128.      Overall structure of an HTML report
    
129.      HTML
    
130.      +------------------------+
    
131.      |<html>                  |
    
132.      |  <head>                |
    
133.      |                        |
    
134.      |   STYLESHEET           |
    
135.      |   +----------------+   |
    
136.      |   |                |   |
    
137.      |   +----------------+   |
    
138.      |                        |
    
139.      |  </head>               |
    
140.      |                        |
    
141.      |  <body>                |
    
142.      |                        |
    
143.      |   HEADING              |
    
144.      |   +----------------+   |
    
145.      |   |                |   |
    
146.      |   +----------------+   |
    
147.      |                        |
    
148.      |   REPORT               |
    
149.      |   +----------------+   |
    
150.      |   |                |   |
    
151.      |   +----------------+   |
    
152.      |                        |
    
153.      |   ENDING               |
    
154.      |   +----------------+   |
    
155.      |   |                |   |
    
156.      |   +----------------+   |
    
157.      |                        |
    
158.      |  </body>               |
    
159.      |</html>                 |
    
160.      +------------------------+
    
161.      """
    

163.      STATUS = {
    
164.          0: u'通过',
    
165.          1: u'失败',
    
166.          2: u'谬误',
    
167.      }
    

169.      DEFAULT_TITLE = 'Unit Test Report'
    
170.      DEFAULT_DESCRIPTION = ''
    

172.      # ------------------------------------------------------------------------
    
173.      # HTML Template
    

175.      HTML_TMPL = r"""<?xml version="1.0"encoding="UTF-8"?>
    
176.  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
177.  <html xmlns="http://www.w3.org/1999/xhtml">
    
178.  <head>
    
179.      <title>%(title)s</title>
    
180.      <meta name="generator" content="%(generator)s"/>
    
181.      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    

183.      <link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
    
184.      <script src="https://cdn.bootcss.com/echarts/3.8.5/echarts.common.min.js"></script>
    
185.      <!-- <script type="text/javascript" src="js/echarts.common.min.js"></script> -->
    

187.      %(stylesheet)s
    

189.  </head>
    
190.  <body>
    
191.      <script language="javascript" type="text/javascript"><!--
    
192.      output_list = Array();
    
193.      /* level - 0:Summary; 1:Failed; 2:All */
    
194.      function showCase(level) {195.          trs = document.getElementsByTagName("tr");
    
196.          for (var i = 0; i < trs.length; i++) {197.              tr = trs[i];
    
198.              id = tr.id;
    
199.              if (id.substr(0,2) == 'ft') {200.                  if (level < 1) {
    
201.                      tr.className = 'hiddenRow';
    
202.                  }
    
203.                  else {
    
204.                      tr.className = '';
    
205.                  }
    
206.              }
    
207.              if (id.substr(0,2) == 'pt') {208.                  if (level > 1) {
    
209.                      tr.className = '';
    
210.                  }
    
211.                  else {
    
212.                      tr.className = 'hiddenRow';
    
213.                  }
    
214.              }
    
215.          }
    
216.      }
    
217.      function showClassDetail(cid, count) {218.          var id_list = Array(count);
    
219.          var toHide = 1;
    
220.          for (var i = 0; i < count; i++) {221.              tid0 = 't' + cid.substr(1) + '.' + (i+1);
    
222.              tid = 'f' + tid0;
    
223.              tr = document.getElementById(tid);
    
224.              if (!tr) {
    
225.                  tid = 'p' + tid0;
    
226.                  tr = document.getElementById(tid);
    
227.              }
    
228.              id_list[i] = tid;
    
229.              if (tr.className) {
    
230.                  toHide = 0;
    
231.              }
    
232.          }
    
233.          for (var i = 0; i < count; i++) {234.              tid = id_list[i];
    
235.              if (toHide) {236.                  document.getElementById('div_'+tid).style.display = 'none'
    
237.                  document.getElementById(tid).className = 'hiddenRow';
    
238.              }
    
239.              else {240.                  document.getElementById(tid).className = '';
    
241.              }
    
242.          }
    
243.      }
    
244.      function showTestDetail(div_id){245.          var details_div = document.getElementById(div_id)
    
246.          var displayState = details_div.style.display
    
247.          // alert(displayState)
    
248.          if (displayState != 'block') {
    
249.              displayState = 'block'
    
250.              details_div.style.display = 'block'
    
251.          }
    
252.          else {
    
253.              details_div.style.display = 'none'
    
254.          }
    
255.      }
    
256.      function html_escape(s) {257.          s = s.replace(/&/g,'&amp;');
    
258.          s = s.replace(/</g,'&lt;');
    
259.          s = s.replace(/>/g,'&gt;');
    
260.          return s;
    
261.      }
    
262.      /* obsoleted by detail in <div>
    
263.   function showOutput(id, name) {
    
264.   var w = window.open("", //url
    
265.   name,
    
266.   "resizable,scrollbars,status,width=800,height=450");
    
267.   d = w.document;
    
268.   d.write("<pre>");
    
269.   d.write(html_escape(output_list[id]));
    
270.   d.write("n");
    
271.   d.write("<a href='javascript:window.close()'>close</a>n");
    
272.   d.write("</pre>n");
    
273.   d.close();
    
274.   }
    
275.   */
    
276.      --></script>
    
277.      <div id="div_base">
    
278.          %(heading)s
    
279.          %(report)s
    
280.          %(ending)s
    
281.          %(chart_script)s
    
282.      </div>
    
283.  </body>
    
284.  </html>
    
285.  """  # variables: (title, generator, stylesheet, heading, report, ending, chart_script)
    

287.      ECHARTS_SCRIPT = """288.      <script type="text/javascript">
    
289.          // 基于筹备好的 dom,初始化 echarts 实例
    
290.          var myChart = echarts.init(document.getElementById('chart'));
    
291.          // 指定图表的配置项和数据
    
292.          var option = {
    
293.              title : {
    
294.                  text: '测试执行状况',
    
295.                  x:'center'
    
296.              },
    
297.              tooltip : {
    
298.                  trigger: 'item',
    
299.                  formatter: "{a} <br/>{b} : {c} ({d}%%)"
    
300.              },
    
301.              color: ['#95b75d', 'grey', '#b64645'],
    
302.              legend: {
    
303.                  orient: 'vertical',
    
304.                  left: 'left',
    
305.                  data: ['通过','失败','谬误']
    
306.              },
    
307.              series : [
    
308.                  {
    
309.                      name: '测试执行状况',
    
310.                      type: 'pie',
    
311.                      radius : '60%%',
    
312.                      center: ['50%%', '60%%'],
    
313.                      data:[314.                          {value:%(Pass)s, name:'通过'},
    
315.                          {value:%(fail)s, name:'失败'},
    
316.                          {value:%(error)s, name:'谬误'}
    
317.                      ],
    
318.                      itemStyle: {
    
319.                          emphasis: {
    
320.                              shadowBlur: 10,
    
321.                              shadowOffsetX: 0,
    
322.                              shadowColor: 'rgba(0, 0, 0, 0.5)'
    
323.                          }
    
324.                      }
    
325.                  }
    
326.              ]
    
327.          };
    
328.          // 应用刚指定的配置项和数据显示图表。329.          myChart.setOption(option);
    
330.      </script>
    
331.      """  # variables: (Pass, fail, error)
    

333.      # ------------------------------------------------------------------------
    
334.      # Stylesheet
    
335.      #
    
336.      # alternatively use a <link> for external style sheet, e.g.
    
337.      #   <link rel="stylesheet" href="$url" type="text/css">
    

339.      STYLESHEET_TMPL = """340.  <style type="text/css"media="screen">
    
341.      body        {font-family: Microsoft YaHei,Consolas,arial,sans-serif; font-size: 80%;}
    
342.      table       {font-size: 100%;}
    
343.      pre         {white-space: pre-wrap;word-wrap: break-word;}
    
344.      /* -- heading ---------------------------------------------------------------------- */
    
345.      h1 {
    
346.          font-size: 16pt;
    
347.          color: gray;
    
348.      }
    
349.      .heading {
    
350.          margin-top: 0ex;
    
351.          margin-bottom: 1ex;
    
352.      }
    
353.      .heading .attribute {
    
354.          margin-top: 1ex;
    
355.          margin-bottom: 0;
    
356.      }
    
357.      .heading .description {
    
358.          margin-top: 2ex;
    
359.          margin-bottom: 3ex;
    
360.      }
    
361.      /* -- css div popup ------------------------------------------------------------------------ */
    
362.      a.popup_link {363.}
    
364.      a.popup_link:hover {
    
365.          color: red;
    
366.      }
    
367.      .popup_window {
    
368.          display: none;
    
369.          position: relative;
    
370.          left: 0px;
    
371.          top: 0px;
    
372.          /*border: solid #627173 1px; */
    
373.          padding: 10px;
    
374.          /*background-color: #E6E6D6; */
    
375.          font-family: "Lucida Console", "Courier New", Courier, monospace;
    
376.          text-align: left;
    
377.          font-size: 8pt;
    
378.          /* width: 500px;*/
    
379.      }
    
380.      }
    
381.      /* -- report ------------------------------------------------------------------------ */
    
382.      #show_detail_line {
    
383.          margin-top: 3ex;
    
384.          margin-bottom: 1ex;
    
385.      }
    
386.      #result_table {
    
387.          width: 99%;
    
388.      }
    
389.      #header_row {
    
390.          font-weight: bold;
    
391.          color: #303641;
    
392.          background-color: #ebebeb;
    
393.      }
    
394.      #total_row  {font-weight: bold;}
    
395.      .passClass  {background-color: #bdedbc;}
    
396.      .failClass  {background-color: #ffefa4;}
    
397.      .errorClass {background-color: #ffc9c9;}
    
398.      .passCase   {color: #6c6;}
    
399.      .failCase   {color: #FF6600; font-weight: bold;}
    
400.      .errorCase  {color: #c00; font-weight: bold;}
    
401.      .hiddenRow  {display: none;}
    
402.      .testcase   {margin-left: 2em;}
    
403.      /* -- ending ---------------------------------------------------------------------- */
    
404.      #ending {405.}
    
406.      #div_base {
    
407.                  position:absolute;
    
408.                  top:0%;
    
409.                  left:5%;
    
410.                  right:5%;
    
411.                  width: auto;
    
412.                  height: auto;
    
413.                  margin: -15px 0 0 0;
    
414.      }
    
415.  </style>
    
416.  """
    

418.      # ------------------------------------------------------------------------
    
419.      # Heading
    
420.      #
    

422.      HEADING_TMPL = """423.      <div class='page-header'>
    
424.          <h1>%(title)s</h1>
    
425.      %(parameters)s
    
426.      </div>
    
427.      <div style="float: left;width:50%%;"><p class='description'>%(description)s</p></div>
    
428.      <div id="chart" style="width:50%%;height:400px;float:left;"></div>
    
429.  """  # variables: (title, parameters, description)
    

431.      HEADING_ATTRIBUTE_TMPL = """<p class='attribute'><strong>%(name)s:</strong> %(value)s</p>
    
432.  """  # variables: (name, value)
    

434.      # ------------------------------------------------------------------------
    
435.      # Report
    
436.      #
    

438.      REPORT_TMPL = u"""439.      <div class="btn-group btn-group-sm">
    
440.          <button class="btn btn-default" onclick='javascript:showCase(0)'> 总结 </button>
    
441.          <button class="btn btn-default" onclick='javascript:showCase(1)'> 失败 </button>
    
442.          <button class="btn btn-default" onclick='javascript:showCase(2)'> 全副 </button>
    
443.      </div>
    
444.      <p></p>
    
445.      <table id='result_table' class="table table-bordered">
    
446.          <colgroup>
    
447.              <col align='left' />
    
448.              <col align='right' />
    
449.              <col align='right' />
    
450.              <col align='right' />
    
451.              <col align='right' />
    
452.              <col align='right' />
    
453.          </colgroup>
    
454.          <tr id='header_row'>
    
455.              <td> 测试套件 / 测试用例 </td>
    
456.              <td> 总数 </td>
    
457.              <td> 通过 </td>
    
458.              <td> 失败 </td>
    
459.              <td> 谬误 </td>
    
460.              <td> 查看 </td>
    
461.          </tr>
    
462.          %(test_list)s
    
463.          <tr id='total_row'>
    
464.              <td> 总计 </td>
    
465.              <td>%(count)s</td>
    
466.              <td>%(Pass)s</td>
    
467.              <td>%(fail)s</td>
    
468.              <td>%(error)s</td>
    
469.              <td>&nbsp;</td>
    
470.          </tr>
    
471.      </table>
    
472.  """  # variables: (test_list, count, Pass, fail, error)
    

474.      REPORT_CLASS_TMPL = u"""475.      <tr class='%(style)s'>
    
476.          <td>%(desc)s</td>
    
477.          <td>%(count)s</td>
    
478.          <td>%(Pass)s</td>
    
479.          <td>%(fail)s</td>
    
480.          <td>%(error)s</td>
    
481.          <td><a href="javascript:showClassDetail('%(cid)s',%(count)s)"> 详情 </a></td>
    
482.      </tr>
    
483.  """  # variables: (style, desc, count, Pass, fail, error, cid)
    

485.      REPORT_TEST_WITH_OUTPUT_TMPL = r"""486.  <tr id='%(tid)s'class='%(Class)s'>
    
487.      <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
    
488.      <td colspan='5' align='center'>
    
489.      <!--css div popup start-->
    
490.      <a class="popup_link" onfocus='this.blur();' href="javascript:showTestDetail('div_%(tid)s')" >
    
491.          %(status)s</a>
    
492.      <div id='div_%(tid)s' class="popup_window">
    
493.          <pre>%(script)s</pre>
    
494.      </div>
    
495.      <!--css div popup end-->
    
496.      </td>
    
497.  </tr>
    
498.  """  # variables: (tid, Class, style, desc, status)
    

500.      REPORT_TEST_NO_OUTPUT_TMPL = r"""501.  <tr id='%(tid)s'class='%(Class)s'>
    
502.      <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
    
503.      <td colspan='5' align='center'>%(status)s</td>
    
504.  </tr>
    
505.  """  # variables: (tid, Class, style, desc, status)
    

507.      REPORT_TEST_OUTPUT_TMPL = r"""%(id)s: %(output)s"""  # variables: (id, output)
    

509.      # ------------------------------------------------------------------------
    
510.      # ENDING
    
511.      #
    

513.      ENDING_TMPL = """<div id='ending'>&nbsp;</div>"""
    

516.  # -------------------- The end of the Template class -------------------
    

519.  TestResult = unittest.TestResult
    

522.  class _TestResult(TestResult):
    
523.      # note: _TestResult is a pure representation of results.
    
524.      # It lacks the output and reporting ability compares to unittest._TextTestResult.
    

526.      def __init__(self, verbosity=1):
    
527.          TestResult.__init__(self)
    
528.          self.stdout0 = None
    
529.          self.stderr0 = None
    
530.          self.success_count = 0
    
531.          self.failure_count = 0
    
532.          self.error_count = 0
    
533.          self.verbosity = verbosity
    

535.          # result is a list of result in 4 tuple
    
536.          # (537.          #   result code (0: success; 1: fail; 2: error),
    
538.          #   TestCase object,
    
539.          #   Test output (byte string),
    
540.          #   stack trace,
    
541.          # )
    
542.          self.result = []
    
543.          self.subtestlist = []
    

545.      def startTest(self, test):
    
546.          TestResult.startTest(self, test)
    
547.          # just one buffer for both stdout and stderr
    
548.          self.outputBuffer = io.StringIO()
    
549.          stdout_redirector.fp = self.outputBuffer
    
550.          stderr_redirector.fp = self.outputBuffer
    
551.          self.stdout0 = sys.stdout
    
552.          self.stderr0 = sys.stderr
    
553.          sys.stdout = stdout_redirector
    
554.          sys.stderr = stderr_redirector
    

556.      def complete_output(self):
    
557.          """
    
558.          Disconnect output redirection and return buffer.
    
559.          Safe to call multiple times.
    
560.          """
    
561.          if self.stdout0:
    
562.              sys.stdout = self.stdout0
    
563.              sys.stderr = self.stderr0
    
564.              self.stdout0 = None
    
565.              self.stderr0 = None
    
566.          return self.outputBuffer.getvalue()
    

568.      def stopTest(self, test):
    
569.          # Usually one of addSuccess, addError or addFailure would have been called.
    
570.          # But there are some path in unittest that would bypass this.
    
571.          # We must disconnect stdout in stopTest(), which is guaranteed to be called.
    
572.          self.complete_output()
    

574.      def addSuccess(self, test):
    
575.          if test not in self.subtestlist:
    
576.              self.success_count += 1
    
577.              TestResult.addSuccess(self, test)
    
578.              output = self.complete_output()
    
579.              self.result.append((0, test, output, ''))
    
580.              if self.verbosity > 1:
    
581.                  sys.stderr.write('ok')
    
582.                  sys.stderr.write(str(test))
    
583.                  sys.stderr.write('n')
    
584.              else:
    
585.                  sys.stderr.write('.')
    

587.      def addError(self, test, err):
    
588.          self.error_count += 1
    
589.          TestResult.addError(self, test, err)
    
590.          _, _exc_str = self.errors[-1]
    
591.          output = self.complete_output()
    
592.          self.result.append((2, test, output, _exc_str))
    
593.          if self.verbosity > 1:
    
594.              sys.stderr.write('E')
    
595.              sys.stderr.write(str(test))
    
596.              sys.stderr.write('n')
    
597.          else:
    
598.              sys.stderr.write('E')
    

600.      def addFailure(self, test, err):
    
601.          self.failure_count += 1
    
602.          TestResult.addFailure(self, test, err)
    
603.          _, _exc_str = self.failures[-1]
    
604.          output = self.complete_output()
    
605.          self.result.append((1, test, output, _exc_str))
    
606.          if self.verbosity > 1:
    
607.              sys.stderr.write('F')
    
608.              sys.stderr.write(str(test))
    
609.              sys.stderr.write('n')
    
610.          else:
    
611.              sys.stderr.write('F')
    

613.      def addSubTest(self, test, subtest, err):
    
614.          if err is not None:
    
615.              if getattr(self, 'failfast', False):
    
616.                  self.stop()
    
617.              if issubclass(err[0], test.failureException):
    
618.                  self.failure_count += 1
    
619.                  errors = self.failures
    
620.                  errors.append((subtest, self._exc_info_to_string(err, subtest)))
    
621.                  output = self.complete_output()
    
622.                  self.result.append((1, test, output + 'nSubTestCase Failed:n' + str(subtest),
    
623.                                      self._exc_info_to_string(err, subtest)))
    
624.                  if self.verbosity > 1:
    
625.                      sys.stderr.write('F')
    
626.                      sys.stderr.write(str(subtest))
    
627.                      sys.stderr.write('n')
    
628.                  else:
    
629.                      sys.stderr.write('F')
    
630.              else:
    
631.                  self.error_count += 1
    
632.                  errors = self.errors
    
633.                  errors.append((subtest, self._exc_info_to_string(err, subtest)))
    
634.                  output = self.complete_output()
    
635.                  self.result.append(636.                      (2, test, output + 'nSubTestCase Error:n' + str(subtest), self._exc_info_to_string(err, subtest)))
    
637.                  if self.verbosity > 1:
    
638.                      sys.stderr.write('E')
    
639.                      sys.stderr.write(str(subtest))
    
640.                      sys.stderr.write('n')
    
641.                  else:
    
642.                      sys.stderr.write('E')
    
643.              self._mirrorOutput = True
    
644.          else:
    
645.              self.subtestlist.append(subtest)
    
646.              self.subtestlist.append(test)
    
647.              self.success_count += 1
    
648.              output = self.complete_output()
    
649.              self.result.append((0, test, output + 'nSubTestCase Pass:n' + str(subtest), ''))
    
650.              if self.verbosity > 1:
    
651.                  sys.stderr.write('ok')
    
652.                  sys.stderr.write(str(subtest))
    
653.                  sys.stderr.write('n')
    
654.              else:
    
655.                  sys.stderr.write('.')
    

658.  class HTMLTestRunner(Template_mixin):
    

660.      def __init__(self, stream=sys.stdout, verbosity=1, title=None, description=None):
    
661.          self.stream = stream
    
662.          self.verbosity = verbosity
    
663.          if title is None:
    
664.              self.title = self.DEFAULT_TITLE
    
665.          else:
    
666.              self.title = title
    
667.          if description is None:
    
668.              self.description = self.DEFAULT_DESCRIPTION
    
669.          else:
    
670.              self.description = description
    

672.          self.startTime = datetime.datetime.now()
    

674.      def run(self, test):
    
675.          "Run the given test case or test suite."
    
676.          result = _TestResult(self.verbosity)
    
677.          test(result)
    
678.          self.stopTime = datetime.datetime.now()
    
679.          self.generateReport(test, result)
    
680.          print('nTime Elapsed: %s' % (self.stopTime - self.startTime), file=sys.stderr)
    
681.          return result
    

683.      def sortResult(self, result_list):
    
684.          # unittest does not seems to run in any particular order.
    
685.          # Here at least we want to group them together by class.
    
686.          rmap = {}
    
687.          classes = []
    
688.          for n, t, o, e in result_list:
    
689.              cls = t.__class__
    
690.              if cls not in rmap:
    
691.                  rmap[cls] = []
    
692.                  classes.append(cls)
    
693.              rmap[cls].append((n, t, o, e))
    
694.          r = [(cls, rmap[cls]) for cls in classes]
    
695.          return r
    

697.      def getReportAttributes(self, result):
    
698.          """
    
699.          Return report attributes as a list of (name, value).
    
700.          Override this to add custom attributes.
    
701.          """
    
702.          startTime = str(self.startTime)[:19]
    
703.          duration = str(self.stopTime - self.startTime)
    
704.          status = []
    
705.          if result.success_count: status.append(u'通过 %s' % result.success_count)
    
706.          if result.failure_count: status.append(u'失败 %s' % result.failure_count)
    
707.          if result.error_count:   status.append(u'谬误 %s' % result.error_count)
    
708.          if status:
    
709.              status = ' '.join(status)
    
710.          else:
    
711.              status = 'none'
    
712.          return [713.              (u'开始工夫', startTime),
    
714.              (u'运行时长', duration),
    
715.              (u'状态', status),
    
716.          ]
    

718.      def generateReport(self, test, result):
    
719.          report_attrs = self.getReportAttributes(result)
    
720.          generator = 'HTMLTestRunner %s' % __version__
    
721.          stylesheet = self._generate_stylesheet()
    
722.          heading = self._generate_heading(report_attrs)
    
723.          report = self._generate_report(result)
    
724.          ending = self._generate_ending()
    
725.          chart = self._generate_chart(result)
    
726.          output = self.HTML_TMPL % dict(727.              title=saxutils.escape(self.title),
    
728.              generator=generator,
    
729.              stylesheet=stylesheet,
    
730.              heading=heading,
    
731.              report=report,
    
732.              ending=ending,
    
733.              chart_script=chart
    
734.          )
    
735.          self.stream.write(output.encode('utf8'))
    

737.      def _generate_stylesheet(self):
    
738.          return self.STYLESHEET_TMPL
    

740.      def _generate_heading(self, report_attrs):
    
741.          a_lines = []
    
742.          for name, value in report_attrs:
    
743.              line = self.HEADING_ATTRIBUTE_TMPL % dict(744.                  name=saxutils.escape(name),
    
745.                  value=saxutils.escape(value),
    
746.              )
    
747.              a_lines.append(line)
    
748.          heading = self.HEADING_TMPL % dict(749.              title=saxutils.escape(self.title),
    
750.              parameters=''.join(a_lines),
    
751.              description=saxutils.escape(self.description),
    
752.          )
    
753.          return heading
    

755.      def _generate_report(self, result):
    
756.          rows = []
    
757.          sortedResult = self.sortResult(result.result)
    
758.          for cid, (cls, cls_results) in enumerate(sortedResult):
    
759.              # subtotal for a class
    
760.              np = nf = ne = 0
    
761.              for n, t, o, e in cls_results:
    
762.                  if n == 0:
    
763.                      np += 1
    
764.                  elif n == 1:
    
765.                      nf += 1
    
766.                  else:
    
767.                      ne += 1
    

769.              # format class description
    
770.              if cls.__module__ == "__main__":
    
771.                  name = cls.__name__
    
772.              else:
    
773.                  name = "%s.%s" % (cls.__module__, cls.__name__)
    
774.              doc = cls.__doc__ and cls.__doc__.split("n")[0] or ""775.              desc = doc and'%s: %s' % (name, doc) or name
    

777.              row = self.REPORT_CLASS_TMPL % dict(
    
778.                  style=ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass',
    
779.                  desc=desc,
    
780.                  count=np + nf + ne,
    
781.                  Pass=np,
    
782.                  fail=nf,
    
783.                  error=ne,
    
784.                  cid='c%s' % (cid + 1),
    
785.              )
    
786.              rows.append(row)
    

788.              for tid, (n, t, o, e) in enumerate(cls_results):
    
789.                  self._generate_report_test(rows, cid, tid, n, t, o, e)
    

791.          report = self.REPORT_TMPL % dict(792.              test_list=''.join(rows),
    
793.              count=str(result.success_count + result.failure_count + result.error_count),
    
794.              Pass=str(result.success_count),
    
795.              fail=str(result.failure_count),
    
796.              error=str(result.error_count),
    
797.          )
    
798.          return report
    

800.      def _generate_chart(self, result):
    
801.          chart = self.ECHARTS_SCRIPT % dict(802.              Pass=str(result.success_count),
    
803.              fail=str(result.failure_count),
    
804.              error=str(result.error_count),
    
805.          )
    
806.          return chart
    

808.      def _generate_report_test(self, rows, cid, tid, n, t, o, e):
    
809.          # e.g. 'pt1.1', 'ft1.1', etc
    
810.          has_output = bool(o or e)
    
811.          tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid + 1, tid + 1)
    
812.          name = t.id().split('.')[-1]
    
813.          doc = t.shortDescription() or ""814.          desc = doc and ('%s: %s' % (name, doc)) or name
    
815.          tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL
    

817.          script = self.REPORT_TEST_OUTPUT_TMPL % dict(
    
818.              id=tid,
    
819.              output=saxutils.escape(o + e),
    
820.          )
    

822.          row = tmpl % dict(
    
823.              tid=tid,
    
824.              Class=(n == 0 and 'hiddenRow' or 'none'),
    
825.              style=(n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none')),
    
826.              desc=desc,
    
827.              script=script,
    
828.              status=self.STATUS[n],
    
829.          )
    
830.          rows.append(row)
    
831.          if not has_output:
    
832.              return
    

834.      def _generate_ending(self):
    
835.          return self.ENDING_TMPL
    

838.  ##############################################################################
    
839.  # Facilities for running tests from the command line
    
840.  ##############################################################################
    

842.  # Note: Reuse unittest.TestProgram to launch test. In the future we may
    
843.  # build our own launcher to support more specific command line
    
844.  # parameters like test title, CSS, etc.
    
845.  class TestProgram(unittest.TestProgram):
    
846.      """
    
847.      A variation of the unittest.TestProgram. Please refer to the base
    
848.      class for command line parameters.
    
849.      """
    

851.      def runTests(self):
    
852.          # Pick HTMLTestRunner as the default test runner.
    
853.          # base class's testRunner parameter is not useful because it means
    
854.          # we have to instantiate HTMLTestRunner before we know self.verbosity.
    
855.          if self.testRunner is None:
    
856.              self.testRunner = HTMLTestRunner(verbosity=self.verbosity)
    
857.          unittest.TestProgram.runTests(self)
    

860.  main = TestProgram
    

862.  ##############################################################################
    
863.  # Executing this module from the command line
    
864.  ##############################################################################
    

866.  if __name__ == "__main__":
    
867.      main(module=None)
    

九、Python+unittest+requests+HTMLTestRunner 残缺的接口自动化测试框架搭建_08——调用生成测试报告

先别急着创立 runAll.py 文件(所有工作做完,最初咱们运行 runAll.py 文件来执行接口自动化的测试工作并生成测试报告发送报告到相干人邮箱),然而咱们在创立此文件前,还短少点东东。按我的目录构造创立 caselist.txt 文件,内容如下:



1.  user/test01case
    
2.  #user/test02case
    
3.  #user/test03case
    
4.  #user/test04case
    
5.  #user/test05case
    
6.  #shop/test_shop_list
    
7.  #shop/test_my_shop
    
8.  #shop/test_new_shop
    

这个文件的作用是,咱们通过这个文件来管制,执行哪些模块下的哪些 unittest 用例文件。如在理论的我的项目中:user 模块下的 test01case.py,店铺 shop 模块下的我的店铺 my_shop,如果本轮无需执行哪些模块的用例的话,就在后面增加 #。咱们持续往下走,还短少一个发送邮件的文件。在 common 下创立 configEmail.py 文件,内容如下:



1.  # import os
    
2.  # import win32com.client as win32
    
3.  # import datetime
    
4.  # import readConfig
    
5.  # import getpathInfo
    
6.  # 
    
7.  # 
    
8.  # read_conf = readConfig.ReadConfig()
    
9.  # subject = read_conf.get_email('subject')# 从配置文件中读取,邮件主题
    
10.  # app = str(read_conf.get_email('app'))# 从配置文件中读取,邮件类型
    
11.  # addressee = read_conf.get_email('addressee')# 从配置文件中读取,邮件收件人
    
12.  # cc = read_conf.get_email('cc')# 从配置文件中读取,邮件抄送人
    
13.  # mail_path = os.path.join(getpathInfo.get_Path(), 'result', 'report.html')# 获取测试报告门路
    
14.  # 
    
15.  # class send_email():
    
16.  #     def outlook(self):
    
17.  #         olook = win32.Dispatch("%s.Application" % app)
    
18.  #         mail = olook.CreateItem(win32.constants.olMailItem)
    
19.  #         mail.To = addressee # 收件人
    
20.  #         mail.CC = cc # 抄送
    
21.  #         mail.Subject = str(datetime.datetime.now())[0:19]+'%s' %subject# 邮件主题
    
22.  #         mail.Attachments.Add(mail_path, 1, 1, "myFile")
    
23.  #         content = """
    
24.  #                     执行测试中……
    
25.  #                     测试已实现!!26.  #                     生成报告中……
    
27.  #                     报告已生成……
    
28.  #                     报告已邮件发送!!29.  #                     """
    
30.  #         mail.Body = content
    
31.  #         mail.Send()
    
32.  # 
    
33.  # 
    
34.  # if __name__ == '__main__':# 经营此文件来验证写的 send_email 是否正确
    
35.  #     print(subject)
    
36.  #     send_email().outlook()
    
37.  #     print("send email ok!!!!!!!!!!")
    

40.  # 两种形式,第一种是用的 win32com, 因为零碎等各方面起因,反馈 win32 问题较多,倡议改成上面的 smtplib 形式
    
41.  import os
    
42.  import smtplib
    
43.  import base64
    
44.  from email.mime.text import MIMEText
    
45.  from email.mime.multipart import MIMEMultipart
    

48.  class SendEmail(object):
    
49.      def __init__(self, username, passwd, recv, title, content,
    
50.   file=None, ssl=False,
    
51.   email_host='smtp.163.com', port=25, ssl_port=465):
    
52.          self.username = username  # 用户名
    
53.          self.passwd = passwd  # 明码
    
54.          self.recv = recv  # 收件人,多个要传 list ['a@qq.com','b@qq.com]
    
55.          self.title = title  # 邮件题目
    
56.          self.content = content  # 邮件注释
    
57.          self.file = file  # 附件门路,如果不在当前目录下,要写绝对路径
    
58.          self.email_host = email_host  # smtp 服务器地址
    
59.          self.port = port  # 一般端口
    
60.          self.ssl = ssl  # 是否平安链接
    
61.          self.ssl_port = ssl_port  # 平安链接端口
    

63.      def send_email(self):
    
64.          msg = MIMEMultipart()
    
65.          # 发送内容的对象
    
66.          if self.file:  # 解决附件的
    
67.              file_name = os.path.split(self.file)[-1]  # 只取文件名,不取门路
    
68.              try:
    
69.                  f = open(self.file, 'rb').read()
    
70.              except Exception as e:
    
71.                  raise Exception('附件打不开!!!!')
    
72.              else:
    
73.                  att = MIMEText(f, "base64", "utf-8")
    
74.                  att["Content-Type"] = 'application/octet-stream'
    
75.                  # base64.b64encode(file_name.encode()).decode()
    
76.                  new_file_name = '=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
    
77.                  # 这里是解决文件名为中文名的,必须这么写
    
78.                  att["Content-Disposition"] = 'attachment; filename="%s"' % (new_file_name)
    
79.                  msg.attach(att)
    
80.          msg.attach(MIMEText(self.content))  # 邮件注释的内容
    
81.          msg['Subject'] = self.title  # 邮件主题
    
82.          msg['From'] = self.username  # 发送者账号
    
83.          msg['To'] = ','.join(self.recv)  # 接收者账号列表
    
84.          if self.ssl:
    
85.              self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port)
    
86.          else:
    
87.              self.smtp = smtplib.SMTP(self.email_host, port=self.port)
    
88.          # 发送邮件服务器的对象
    
89.          self.smtp.login(self.username, self.passwd)
    
90.          try:
    
91.              self.smtp.sendmail(self.username, self.recv, msg.as_string())
    
92.              pass
    
93.          except Exception as e:
    
94.              print('出错了。。', e)
    
95.          else:
    
96.              print('发送胜利!')
    
97.          self.smtp.quit()
    

100.  if __name__ == '__main__':
    

102.      m = SendEmail(
    
103.          username='@163.com',
    
104.          passwd='',
    
105.          recv=[''],
    
106.          title='',
    
107.          content='测试发送邮件',
    
108.          file=r'E:test_recordv2.3.3 测试截图调整款式.png',
    
109.          ssl=True,
    
110.      )
    
111.      m.send_email()
    

运行 configEmail.py 验证邮件发送是否正确

邮件已发送胜利,咱们进入到邮箱中进行查看,所有 OK~~ 不过这我要阐明一下,我写的 send_email 是调用的 outlook,如果您的电脑本地是应用的其余邮件服务器的话,这块的代码须要批改为您想应用的邮箱调用代码

如果遇到发送的多个收件人,然而只有第一个收件人能够收到邮件,或者收件人为空能够参考 http://www.361way.com/smtplib-multiple-addresses/5503.html

持续往下走,这下咱们该创立咱们的 runAll.py 文件了

1.  import os
    
2.  import common.HTMLTestRunner as HTMLTestRunner
    
3.  import getpathInfo
    
4.  import unittest
    
5.  import readConfig
    
6.  from common.configEmail import SendEmail
    
7.  from apscheduler.schedulers.blocking import BlockingScheduler
    
8.  import pythoncom
    
9.  # import common.Log
    

11.  send_mail = SendEmail(
    
12.          username='@163.com',
    
13.          passwd='',
    
14.          recv=[''],
    
15.          title='',
    
16.          content='测试发送邮件',
    
17.          file=r'E:test_recordv2.3.3 测试截图调整款式.png',
    
18.          ssl=True,
    
19.      )
    
20.  path = getpathInfo.get_Path()
    
21.  report_path = os.path.join(path, 'result')
    
22.  on_off = readConfig.ReadConfig().get_email('on_off')
    
23.  # log = common.Log.logger
    

25.  class AllTest:# 定义一个类 AllTest
    
26.      def __init__(self):# 初始化一些参数和数据
    
27.          global resultPath
    
28.          resultPath = os.path.join(report_path, "report.html")#result/report.html
    
29.          self.caseListFile = os.path.join(path, "caselist.txt")# 配置执行哪些测试文件的配置文件门路
    
30.          self.caseFile = os.path.join(path, "testCase")# 真正的测试断言文件门路
    
31.          self.caseList = []
    

33.      def set_case_list(self):
    
34.          """
    
35.   读取 caselist.txt 文件中的用例名称,并增加到 caselist 元素组
    
36.   :return:
    
37.   """
    
38.          fb = open(self.caseListFile)
    
39.          for value in fb.readlines():
    
40.              data = str(value)
    
41.              if data != ''and not data.startswith("#"):# 如果 data 非空且不以 #结尾
    
42.                  self.caseList.append(data.replace("n", ""))# 读取每行数据会将换行转换为 n,去掉每行数据中的 n
    
43.          fb.close()
    

45.      def set_case_suite(self):
    
46.          """
    

48.   :return:
    
49.   """
    
50.          self.set_case_list()# 通过 set_case_list() 拿到 caselist 元素组
    
51.          test_suite = unittest.TestSuite()
    
52.          suite_module = []
    
53.          for case in self.caseList:# 从 caselist 元素组中循环取出 case
    
54.              case_name = case.split("/")[-1]# 通过 split 函数来将 aaa/bbb 宰割字符串,- 1 取前面,0 取后面
    
55.              print(case_name+".py")# 打印出取出来的名称
    
56.              #批量加载用例,第一个参数为用例寄存门路,第一个参数为门路文件名
    
57.              discover = unittest.defaultTestLoader.discover(self.caseFile, pattern=case_name + '.py', top_level_dir=None)
    
58.              suite_module.append(discover)# 将 discover 存入 suite_module 元素组
    
59.              print('suite_module:'+str(suite_module))
    
60.          if len(suite_module) > 0:# 判断 suite_module 元素组是否存在元素
    
61.              for suite in suite_module:# 如果存在,循环取出元素组内容,命名为 suite
    
62.                  for test_name in suite:# 从 discover 中取出 test_name,应用 addTest 增加到测试集
    
63.                      test_suite.addTest(test_name)
    
64.          else:
    
65.              print('else:')
    
66.              return None
    
67.          return test_suite# 返回测试集
    

69.      def run(self):
    
70.          """
    
71.   run test
    
72.   :return:
    
73.   """
    
74.          try:
    
75.              suit = self.set_case_suite()# 调用 set_case_suite 获取 test_suite
    
76.              print('try')
    
77.              print(str(suit))
    
78.              if suit is not None:# 判断 test_suite 是否为空
    
79.                  print('if-suit')
    
80.                  fp = open(resultPath, 'wb')# 关上 result/20181108/report.html 测试报告文件,如果不存在就创立
    
81.                  #调用 HTMLTestRunner
    
82.                  runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Test Report', description='Test Description')
    
83.                  runner.run(suit)
    
84.              else:
    
85.                  print("Have no case to test.")
    
86.          except Exception as ex:
    
87.              print(str(ex))
    
88.              #log.info(str(ex))
    

90.          finally:
    
91.              print("*********TEST END*********")
    
92.              #log.info("*********TEST END*********")
    
93.              fp.close()
    
94.          #判断邮件发送的开关
    
95.          if on_off == 'on':
    
96.              send_mail.send_email()
    
97.          else:
    
98.              print("邮件发送开关配置敞开,请关上开关后可失常主动发送测试报告")
    
99.  # pythoncom.CoInitialize()
    
100.  # scheduler = BlockingScheduler()
    
101.  # scheduler.add_job(AllTest().run, 'cron', day_of_week='1-5', hour=14, minute=59)
    
102.  # scheduler.start()
    

104.  if __name__ == '__main__':
    
105.      AllTest().run() 

执行 runAll.py,进到邮箱中查看发送的测试后果报告,关上查看

而后持续,咱们框架到这里就算根本搭建好了,然而短少日志的输入,在一些要害的参数调用的中央咱们来输入一些日志。从而更不便的来保护和查找问题。

按目录构造持续在 common 下创立 Log.py,内容如下:



1.  import os
    
2.  import logging
    
3.  from logging.handlers import TimedRotatingFileHandler
    
4.  import getpathInfo
    

6.  path = getpathInfo.get_Path()
    
7.  log_path = os.path.join(path, 'result')  # 寄存 log 文件的门路
    

10.  class Logger(object):
    
11.      def __init__(self, logger_name='logs…'):
    
12.          self.logger = logging.getLogger(logger_name)
    
13.          logging.root.setLevel(logging.NOTSET)
    
14.          self.log_file_name = 'logs'  # 日志文件的名称
    
15.          self.backup_count = 5  # 最多寄存日志的数量
    
16.          # 日志输入级别
    
17.          self.console_output_level = 'WARNING'
    
18.          self.file_output_level = 'DEBUG'
    
19.          # 日志输入格局
    
20.          self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    

22.      def get_logger(self):
    
23.          """在 logger 中增加日志句柄并返回,如果 logger 已有句柄,则间接返回"""
    
24.          if not self.logger.handlers:  # 防止反复日志
    
25.              console_handler = logging.StreamHandler()
    
26.              console_handler.setFormatter(self.formatter)
    
27.              console_handler.setLevel(self.console_output_level)
    
28.              self.logger.addHandler(console_handler)
    

30.              # 每天从新创立一个日志文件,最多保留 backup_count 份
    
31.              file_handler = TimedRotatingFileHandler(filename=os.path.join(log_path, self.log_file_name), when='D',
    
32.                                                      interval=1, backupCount=self.backup_count, delay=True,
    
33.                                                      encoding='utf-8')
    
34.              file_handler.setFormatter(self.formatter)
    
35.              file_handler.setLevel(self.file_output_level)
    
36.              self.logger.addHandler(file_handler)
    
37.          return self.logger
    

40.  logger = Logger().get_logger()
    

而后咱们在须要咱们输入日志的中央增加日志:

咱们批改 runAll.py 文件,在顶部减少 import common.Log,而后减少标红框的代码

让咱们再来运行一下 runAll.py 文件,发现在 result 下多了一个 logs 文件,咱们关上看一下有没有咱们打印的日志
[url]https://www.51design.com/work…[/url]
[url]https://www.51design.com/work…[/url]

OK,至此咱们的接口自动化测试的框架就搭建完了,后续咱们能够将此框架进行进一步优化革新,应用咱们实在我的项目的接口,联合继续集成定时工作等,让这个我的项目每天定时的来跑啦~~~

欢送增加我的微信,互相学习探讨~1305618688,qq 交换群:849102042

2020 年 9 月 23 追加

一、、最近有太多人反馈,执行通过后 report.html 文件中内容为空,这个基本上少数起因是因为用例执行异样报错,导致没有胜利执行用例,所以没有生成数据。大家能够运行 testCase 下的 test01Case.py 等用例文件,看是不是运行报错了。如果运行胜利,再去执行 runAll 试一下

正文完
 0