H5W3
当前位置:H5W3 > python > 正文

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

完整的框架源码下载 https://gitee.com/submi_to/in…,欢迎添加我的微信,相互学习探讨~1305618688,qq交流群:849102042

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

 首先配置好开发环境,下载安装Python并下载安装pycharm,在pycharm中创建项目功能目录。如果不会的可以百度Google一下,该内容网上的讲解还是比较多比较全的!

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

大家可以先简单了解下该项目的目录结构介绍,后面会针对每个文件有详细注解和代码。

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】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

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

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

三、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 = [email protected]
15.  cc = [email protected]

在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())

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

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

继续往下走,同理,按第一讲目录创建好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,查看数据是否正确

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

一切OK

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

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

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

我们根据上面的三种情况,将对这个接口的用例写在一个对应的单独文件中testFilecaseuserCase.xlsx ,userCase.xlsx内容如下:

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

紧接着,我们有了用例设计的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】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

完全正确~

五、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)

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

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

我们发现和浏览器中进行请求该接口,得到的结果一致,说明没有问题,一切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】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

七、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="https://segmentfault.com/a/1190000038865850/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></script>
185.      <!-- <script type="text/javascript"></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="https://segmentfault.com/a/1190000038865850/$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><p class='description'>%(description)s</p></div>
428.      <div id="chart"></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 ['[email protected]','[email protected]]
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验证邮件发送是否正确

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

邮件已发送成功,我们进入到邮箱中进行查看,一切OK~~不过这我要说明一下,我写的send_email是调用的outlook,如果您的电脑本地是使用的其他邮件服务器的话,这块的代码需要修改为您想使用的邮箱调用代码

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

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

继续往下走,这下我们该创建我们的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,进到邮箱中查看发送的测试结果报告,打开查看

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

然后继续,我们框架到这里就算基本搭建好了,但是缺少日志的输出,在一些关键的参数调用的地方我们来输出一些日志。从而更方便的来维护和查找问题。

按目录结构继续在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,然后增加标红框的代码

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

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

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

OK,至此我们的接口自动化测试的框架就搭建完了,后续我们可以将此框架进行进一步优化改造,使用我们真实项目的接口,结合持续集成定时任务等,让这个项目每天定时的来跑啦~~~

欢迎添加我的微信,相互学习探讨~1305618688,qq交流群:849102042

2020年9月23追加

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

本文地址:H5W3 » 【Python】Python+unittest+requests 接口自动化测试框架搭建 完整的框架搭建过程 实战

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址