当前位置:   article > 正文

Python+unittest+requests+Jenkins 接口自动化测试框架搭建 完整的框架搭建过程 实战_confighttp.send_post

confighttp.send_post

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

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

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——测试接口服务

一个简单的接口测试小例子

  1. import json
  2. from pip._vendor import requests
  3. headers={
  4. "token": "token",
  5. "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_2_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.18(0x1800122c) NetType/WIFI Language/zh_CN",
  6. "Accept-Encoding": "gzip",
  7. "Accept-Language": "zh-CN,zh;q=0.9",
  8. "Content-Type": "application/json",
  9. "Content-Length": "129",
  10. }
  11. def login():
  12. url = "xxxxxx/app/user/login"
  13. data={
  14. "pwd": "xxxx",
  15. "name": "xxxxxx"
  16. }
  17. luckyUrl = requests.post(url=url, data=json.dumps(data), headers=headers)
  18. result=luckyUrl.json()
  19. print(luckyUrl.text)
  20. # print(luckyUrl.status_code)
  21. # print(result['status'])
  22. if result['status']==0:
  23. print ("登录成功")
  24. else:
  25. print("登录失败")
  26. if __name__ == '__main__':
  27. login()

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

这个配置文件按照作者抄写的,但是后续发送邮件直接写死,没有用到里面的配置,后续再研究

  1. [DATABASE]
  2. host =
  3. username =
  4. password =
  5. port =
  6. database =
  7. [HTTP]
  8. # 接口的url
  9. scheme = https
  10. baseurl = url
  11. port = 443
  12. timeout = 1.0
  13. [EMAIL]
  14. on_off = off
  15. #在邮件中on_off是设置的一个开关,=on打开,发送邮件,=其他不发送邮件
  16. mail_host = smtp.qq.com
  17. mail_user = xxxxxx@qq.com
  18. mail_pass = xxxxx
  19. mail_port = 25
  20. sender = xxxxx@qq.com
  21. receiver = xxxxx@qq.com
  22. subject = python
  23. content = "All interface test has been complited\nplease read the report file about the detile of result in the attachment."
  24. testuser = qiugongyuan

在HTTP中,协议http,baseURL,端口,超时时间。

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

在我们编写readConfig.py文件前,我们先写一个获取项目某路径下某文件绝对路径的一个方法。按第一讲的目录结构创建好getpathInfo.py,打开该文件

  1. import os
  2. def get_Path():
  3. path = os.path.split(os.path.realpath(__file__))[0]
  4. return path
  5. if __name__ == '__main__': # 执行该文件,测试下是否OK
  6. print('测试路径是否OK,路径为:', get_Path())

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

继续往下走,同理,按第一讲目录创建好readConfig.py文件,打开该文件,以后的章节不在累赘

  1. import os
  2. import configparser
  3. import getpathInfo # 引入我们自己的写的获取路径的类
  4. path = getpathInfo.get_Path() # 调用实例化
  5. config_path = os.path.join(path,
  6. 'config.ini') # 这句话是在path路径下再加一级
  7. config = configparser.ConfigParser() # 调用外部的读取配置文件的方法
  8. config.read(config_path, encoding='utf-8')
  9. class ReadConfig():
  10. def get_http(self, name):
  11. value = config.get('HTTP', name)
  12. return value
  13. def get_email(self, name):
  14. value = config.get('EMAIL', name)
  15. return value
  16. def get_mysql(self, name): # 写好,留以后备用。但是因为我们没有对数据库的操作,所以这个可以屏蔽掉
  17. value = config.get('DATABASE', name)
  18. return value
  19. if __name__ == '__main__': # 测试一下,我们读取配置文件的方法是否可用
  20. print('HTTP中的baseurl值为:', ReadConfig().get_http('baseurl'))
  21. print('EMAIL中的开关on_off值为:', ReadConfig().get_email('on_off'))

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

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

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

我们根据上面的三种情况,将对这个接口的用例写在一个对应的单独文件中,testcase.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()
  7. class readExcel():
  8. def get_xls(self, xls_name, sheet_name): # xls_name填写用例的Excel名称 sheet_name该Excel的sheet名称
  9. cls = []
  10. # 获取用例文件路径
  11. xlsPath = os.path.join(path, xls_name)
  12. file = open_workbook(xlsPath) # 打开用例Excel
  13. sheet = file.sheet_by_name(sheet_name) # 获得打开Excel的sheet
  14. # 获取这个sheet内容行数
  15. nrows = sheet.nrows
  16. for i in range(nrows): # 根据行数做循环
  17. if sheet.row_values(i)[0] != u'test_case': # 如果这个Excel的这个sheet的第i行的第一列不等于case_name那么我们把这行的数据添加到cls[]
  18. cls.append(sheet.row_values(i))
  19. return cls
  20. if __name__ == '__main__': # 我们执行该文件测试一下是否可以正确获取Excel中的值
  21. print(readExcel().get_xls('testcase.xlsx', 'login'))
  22. print(readExcel().get_xls('testcase.xlsx', 'login')[0][1])
  23. print(readExcel().get_xls('testcase.xlsx', 'login')[1][2])
  24. print(readExcel().get_xls('testcase.xlsx', 'login')[2][3])

 运行一下

五、Python+unittest+requests+HTMLTestRunner完整的接口自动化测试框架搭建_04——requests请求

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

  1. import requests
  2. import json
  3. headers = {
  4. "token":"token",
  5. "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_2_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.18(0x1800122c) NetType/WIFI Language/zh_CN",
  6. "Accept-Encoding": "gzip",
  7. "Accept-Language": "zh-CN,zh;q=0.9",
  8. "Content-Type": "application/json",
  9. "Content-Length": "129",
  10. }
  11. class RunMain():
  12. def send_post(self, url, data): # 定义一个方法,传入需要的参数url和data
  13. # 参数必须按照url、data顺序传入
  14. result = requests.post(url=url, data=json.dumps(data), headers=headers) # 因为这里要封装post方法,所以这里的url和data值不能写死
  15. # result = requests.post(url=url, data=data, headers=headers)#后续读取excel,需要用到这个格式传参data
  16. res = result.json()
  17. return res
  18. def send_get(self, url, data):
  19. result = requests.get(url=url, data=data, headers=headers)
  20. res = result.json()
  21. return res
  22. def run_main(self, method, url=None, data=None): # 定义一个run_main函数,通过传过来的method来进行不同的get或post请求
  23. result = None
  24. if method == 'post':
  25. result = self.send_post(url, data)
  26. elif method == 'get':
  27. result = self.send_get(url, data)
  28. else:
  29. print("method值错误!!!,method:%s" % (str(method)))
  30. return result
  31. if __name__ == '__main__': # 通过写死参数,来验证我们写的请求是否正确
  32. result1 = RunMain().run_main('post','xxxxxx/app/user/login',
  33. {"pwd": "888888", "name": "xxxx"})
  34. print(result1)

 运行一下:

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

写一个类,动态获取URL

  1. import readConfig as readConfig
  2. readconfig = readConfig.ReadConfig()
  3. class geturlParams(): # 定义一个方法,将从配置文件中读取的进行拼接
  4. def get_Url(self):
  5. new_url = readconfig.get_http('scheme') + '://' + readconfig.get_http('baseurl') + '/app/user/login'
  6. return new_url
  7. if __name__ == '__main__': # 验证拼接后的正确性
  8. print(geturlParams().get_Url())

后续跑了一下,发现url在这里写死了,没有参数化,后续test01case.py文件读取excel里的url进行完整url拼接,更改一下:

  1. import readConfig as readConfig
  2. readconfig = readConfig.ReadConfig()
  3. class geturlParams(): # 定义一个方法,将从配置文件中读取的进行拼接
  4. def get_Url(self):
  5. new_url = readconfig.get_http('scheme') + '://' + readconfig.get_http('baseurl')
  6. return new_url
  7. if __name__ == '__main__': # 验证拼接后的正确性
  8. print(geturlParams().get_Url())

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

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

  1. import unittest
  2. from common import configHttp
  3. import paramunittest
  4. import geturlParams
  5. import readExcel
  6. login_xls = readExcel.readExcel().get_xls('testcase.xlsx', 'login')
  7. @paramunittest.parametrized(*login_xls)
  8. class testUserLogin(unittest.TestCase):
  9. def setParameters(self, case_name, path, data, method):
  10. self.case_name = str(case_name)
  11. self.path = str(path)
  12. self.data = str(data)
  13. self.method = str(method)
  14. def description(self):
  15. self.case_name
  16. def setUp(self):
  17. print("测试项目:" + self.case_name)
  18. print("测试路径:" + self.path)
  19. def test01case(self):
  20. self.checkResult()
  21. def tearDown(self):
  22. print("测试结束,输出log完结\n\n")
  23. def checkResult(self):
  24. url = geturlParams.geturlParams.get_Url(self)
  25. info = configHttp.RunMain().run_main(self.method, url=url, data=self.data)
  26. print(info)
  27. if self.case_name == 'login': # 如果case_name是login
  28. self.assertEqual(info['status'], 0)
  29. if self.case_name == 'login_error': # 如果case_name是login_error
  30. self.assertEqual(info['msg'], '密码有误')
  31. if self.case_name == 'login_null': # 如果case_name是login_null
  32. self.assertEqual(info['msg'], 'Pwd不能为空,Name不能为空')

 这个时候,就需要将configHttp里的send_post()方法里的result更改为

result = requests.post(url=url, data=data, headers=headers)#后续读取excel,需要用到这个格式传参data

运行一下:

优化一:这里没有将url参数化,后续优化了一下,通过get_url方法+拼接excel里的url,获取完整的url:

 优化二:如果需要校验返回结果里的Json里面的结果,尝试用了一下jsonpath,参考链接:

在接口自动化测试中,如何利用Pytest + JSONPath 进行接口响应断言_刘春明的博客-CSDN博客

八、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. """
  51. # URL: http://tungwaiyip.info/software/HTMLTestRunner.html
  52. __author__ = "Wai Yip Tung"
  53. __version__ = "0.9.1"
  54. """
  55. Change History
  56. Version 0.9.1
  57. * 用Echarts添加执行情况统计图 (灰蓝)
  58. Version 0.9.0
  59. * 改成Python 3.x (灰蓝)
  60. Version 0.8.3
  61. * 使用 Bootstrap稍加美化 (灰蓝)
  62. * 改为中文 (灰蓝)
  63. Version 0.8.2
  64. * Show output inline instead of popup window (Viorel Lupu).
  65. Version in 0.8.1
  66. * Validated XHTML (Wolfgang Borgert).
  67. * Added description of test classes and test cases.
  68. Version in 0.8.0
  69. * Define Template_mixin class for customization.
  70. * Workaround a IE 6 bug that it does not treat <script> block as CDATA.
  71. Version in 0.7.1
  72. * Back port to Python 2.3 (Frank Horowitz).
  73. * Fix missing scroll bars in detail log (Podi).
  74. """
  75. # TODO: color stderr
  76. # TODO: simplify javascript using ,ore than 1 class in the class attribute?
  77. import datetime
  78. import sys
  79. import io
  80. import time
  81. import unittest
  82. from xml.sax import saxutils
  83. # ------------------------------------------------------------------------
  84. # The redirectors below are used to capture output during testing. Output
  85. # sent to sys.stdout and sys.stderr are automatically captured. However
  86. # in some cases sys.stdout is already cached before HTMLTestRunner is
  87. # invoked (e.g. calling logging.basicConfig). In order to capture those
  88. # output, use the redirectors for the cached stream.
  89. #
  90. # e.g.
  91. # >>> logging.basicConfig(stream=HTMLTestRunner.stdout_redirector)
  92. # >>>
  93. class OutputRedirector(object):
  94. """ Wrapper to redirect stdout or stderr """
  95. def __init__(self, fp):
  96. self.fp = fp
  97. def write(self, s):
  98. self.fp.write(s)
  99. def writelines(self, lines):
  100. self.fp.writelines(lines)
  101. def flush(self):
  102. self.fp.flush()
  103. stdout_redirector = OutputRedirector(sys.stdout)
  104. stderr_redirector = OutputRedirector(sys.stderr)
  105. # ----------------------------------------------------------------------
  106. # Template
  107. class Template_mixin(object):
  108. """
  109. Define a HTML template for report customerization and generation.
  110. Overall structure of an HTML report
  111. HTML
  112. +------------------------+
  113. |<html> |
  114. | <head> |
  115. | |
  116. | STYLESHEET |
  117. | +----------------+ |
  118. | | | |
  119. | +----------------+ |
  120. | |
  121. | </head> |
  122. | |
  123. | <body> |
  124. | |
  125. | HEADING |
  126. | +----------------+ |
  127. | | | |
  128. | +----------------+ |
  129. | |
  130. | REPORT |
  131. | +----------------+ |
  132. | | | |
  133. | +----------------+ |
  134. | |
  135. | ENDING |
  136. | +----------------+ |
  137. | | | |
  138. | +----------------+ |
  139. | |
  140. | </body> |
  141. |</html> |
  142. +------------------------+
  143. """
  144. STATUS = {
  145. 0: u'通过',
  146. 1: u'失败',
  147. 2: u'错误',
  148. }
  149. DEFAULT_TITLE = 'Unit Test Report'
  150. DEFAULT_DESCRIPTION = ''
  151. # ------------------------------------------------------------------------
  152. # HTML Template
  153. HTML_TMPL = r"""<?xml version="1.0" encoding="UTF-8"?>
  154. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  155. <html xmlns="http://www.w3.org/1999/xhtml">
  156. <head>
  157. <title>%(title)s</title>
  158. <meta name="generator" content="%(generator)s"/>
  159. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  160. <link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
  161. <script src="https://cdn.bootcss.com/echarts/3.8.5/echarts.common.min.js"></script>
  162. <!-- <script type="text/javascript" src="js/echarts.common.min.js"></script> -->
  163. %(stylesheet)s
  164. </head>
  165. <body>
  166. <script language="javascript" type="text/javascript"><!--
  167. output_list = Array();
  168. /* level - 0:Summary; 1:Failed; 2:All */
  169. function showCase(level) {
  170. trs = document.getElementsByTagName("tr");
  171. for (var i = 0; i < trs.length; i++) {
  172. tr = trs[i];
  173. id = tr.id;
  174. if (id.substr(0,2) == 'ft') {
  175. if (level < 1) {
  176. tr.className = 'hiddenRow';
  177. }
  178. else {
  179. tr.className = '';
  180. }
  181. }
  182. if (id.substr(0,2) == 'pt') {
  183. if (level > 1) {
  184. tr.className = '';
  185. }
  186. else {
  187. tr.className = 'hiddenRow';
  188. }
  189. }
  190. }
  191. }
  192. function showClassDetail(cid, count) {
  193. var id_list = Array(count);
  194. var toHide = 1;
  195. for (var i = 0; i < count; i++) {
  196. tid0 = 't' + cid.substr(1) + '.' + (i+1);
  197. tid = 'f' + tid0;
  198. tr = document.getElementById(tid);
  199. if (!tr) {
  200. tid = 'p' + tid0;
  201. tr = document.getElementById(tid);
  202. }
  203. id_list[i] = tid;
  204. if (tr.className) {
  205. toHide = 0;
  206. }
  207. }
  208. for (var i = 0; i < count; i++) {
  209. tid = id_list[i];
  210. if (toHide) {
  211. document.getElementById('div_'+tid).style.display = 'none'
  212. document.getElementById(tid).className = 'hiddenRow';
  213. }
  214. else {
  215. document.getElementById(tid).className = '';
  216. }
  217. }
  218. }
  219. function showTestDetail(div_id){
  220. var details_div = document.getElementById(div_id)
  221. var displayState = details_div.style.display
  222. // alert(displayState)
  223. if (displayState != 'block' ) {
  224. displayState = 'block'
  225. details_div.style.display = 'block'
  226. }
  227. else {
  228. details_div.style.display = 'none'
  229. }
  230. }
  231. function html_escape(s) {
  232. s = s.replace(/&/g,'&amp;');
  233. s = s.replace(/</g,'&lt;');
  234. s = s.replace(/>/g,'&gt;');
  235. return s;
  236. }
  237. /* obsoleted by detail in <div>
  238. function showOutput(id, name) {
  239. var w = window.open("", //url
  240. name,
  241. "resizable,scrollbars,status,width=800,height=450");
  242. d = w.document;
  243. d.write("<pre>");
  244. d.write(html_escape(output_list[id]));
  245. d.write("\n");
  246. d.write("<a href='javascript:window.close()'>close</a>\n");
  247. d.write("</pre>\n");
  248. d.close();
  249. }
  250. */
  251. --></script>
  252. <div id="div_base">
  253. %(heading)s
  254. %(report)s
  255. %(ending)s
  256. %(chart_script)s
  257. </div>
  258. </body>
  259. </html>
  260. """ # variables: (title, generator, stylesheet, heading, report, ending, chart_script)
  261. ECHARTS_SCRIPT = """
  262. <script type="text/javascript">
  263. // 基于准备好的dom,初始化echarts实例
  264. var myChart = echarts.init(document.getElementById('chart'));
  265. // 指定图表的配置项和数据
  266. var option = {
  267. title : {
  268. text: '测试执行情况',
  269. x:'center'
  270. },
  271. tooltip : {
  272. trigger: 'item',
  273. formatter: "{a} <br/>{b} : {c} ({d}%%)"
  274. },
  275. color: ['#95b75d', 'grey', '#b64645'],
  276. legend: {
  277. orient: 'vertical',
  278. left: 'left',
  279. data: ['通过','失败','错误']
  280. },
  281. series : [
  282. {
  283. name: '测试执行情况',
  284. type: 'pie',
  285. radius : '60%%',
  286. center: ['50%%', '60%%'],
  287. data:[
  288. {value:%(Pass)s, name:'通过'},
  289. {value:%(fail)s, name:'失败'},
  290. {value:%(error)s, name:'错误'}
  291. ],
  292. itemStyle: {
  293. emphasis: {
  294. shadowBlur: 10,
  295. shadowOffsetX: 0,
  296. shadowColor: 'rgba(0, 0, 0, 0.5)'
  297. }
  298. }
  299. }
  300. ]
  301. };
  302. // 使用刚指定的配置项和数据显示图表。
  303. myChart.setOption(option);
  304. </script>
  305. """ # variables: (Pass, fail, error)
  306. # ------------------------------------------------------------------------
  307. # Stylesheet
  308. #
  309. # alternatively use a <link> for external style sheet, e.g.
  310. # <link rel="stylesheet" href="$url" type="text/css">
  311. STYLESHEET_TMPL = """
  312. <style type="text/css" media="screen">
  313. body { font-family: Microsoft YaHei,Consolas,arial,sans-serif; font-size: 80%; }
  314. table { font-size: 100%; }
  315. pre { white-space: pre-wrap;word-wrap: break-word; }
  316. /* -- heading ---------------------------------------------------------------------- */
  317. h1 {
  318. font-size: 16pt;
  319. color: gray;
  320. }
  321. .heading {
  322. margin-top: 0ex;
  323. margin-bottom: 1ex;
  324. }
  325. .heading .attribute {
  326. margin-top: 1ex;
  327. margin-bottom: 0;
  328. }
  329. .heading .description {
  330. margin-top: 2ex;
  331. margin-bottom: 3ex;
  332. }
  333. /* -- css div popup ------------------------------------------------------------------------ */
  334. a.popup_link {
  335. }
  336. a.popup_link:hover {
  337. color: red;
  338. }
  339. .popup_window {
  340. display: none;
  341. position: relative;
  342. left: 0px;
  343. top: 0px;
  344. /*border: solid #627173 1px; */
  345. padding: 10px;
  346. /*background-color: #E6E6D6; */
  347. font-family: "Lucida Console", "Courier New", Courier, monospace;
  348. text-align: left;
  349. font-size: 8pt;
  350. /* width: 500px;*/
  351. }
  352. }
  353. /* -- report ------------------------------------------------------------------------ */
  354. #show_detail_line {
  355. margin-top: 3ex;
  356. margin-bottom: 1ex;
  357. }
  358. #result_table {
  359. width: 99%;
  360. }
  361. #header_row {
  362. font-weight: bold;
  363. color: #303641;
  364. background-color: #ebebeb;
  365. }
  366. #total_row { font-weight: bold; }
  367. .passClass { background-color: #bdedbc; }
  368. .failClass { background-color: #ffefa4; }
  369. .errorClass { background-color: #ffc9c9; }
  370. .passCase { color: #6c6; }
  371. .failCase { color: #FF6600; font-weight: bold; }
  372. .errorCase { color: #c00; font-weight: bold; }
  373. .hiddenRow { display: none; }
  374. .testcase { margin-left: 2em; }
  375. /* -- ending ---------------------------------------------------------------------- */
  376. #ending {
  377. }
  378. #div_base {
  379. position:absolute;
  380. top:0%;
  381. left:5%;
  382. right:5%;
  383. width: auto;
  384. height: auto;
  385. margin: -15px 0 0 0;
  386. }
  387. </style>
  388. """
  389. # ------------------------------------------------------------------------
  390. # Heading
  391. #
  392. HEADING_TMPL = """
  393. <div class='page-header'>
  394. <h1>%(title)s</h1>
  395. %(parameters)s
  396. </div>
  397. <div style="float: left;width:50%%;"><p class='description'>%(description)s</p></div>
  398. <div id="chart" style="width:50%%;height:400px;float:left;"></div>
  399. """ # variables: (title, parameters, description)
  400. HEADING_ATTRIBUTE_TMPL = """<p class='attribute'><strong>%(name)s:</strong> %(value)s</p>
  401. """ # variables: (name, value)
  402. # ------------------------------------------------------------------------
  403. # Report
  404. #
  405. REPORT_TMPL = u"""
  406. <div class="btn-group btn-group-sm">
  407. <button class="btn btn-default" onclick='javascript:showCase(0)'>总结</button>
  408. <button class="btn btn-default" onclick='javascript:showCase(1)'>失败</button>
  409. <button class="btn btn-default" onclick='javascript:showCase(2)'>全部</button>
  410. </div>
  411. <p></p>
  412. <table id='result_table' class="table table-bordered">
  413. <colgroup>
  414. <col align='left' />
  415. <col align='right' />
  416. <col align='right' />
  417. <col align='right' />
  418. <col align='right' />
  419. <col align='right' />
  420. </colgroup>
  421. <tr id='header_row'>
  422. <td>测试套件/测试用例</td>
  423. <td>总数</td>
  424. <td>通过</td>
  425. <td>失败</td>
  426. <td>错误</td>
  427. <td>查看</td>
  428. </tr>
  429. %(test_list)s
  430. <tr id='total_row'>
  431. <td>总计</td>
  432. <td>%(count)s</td>
  433. <td>%(Pass)s</td>
  434. <td>%(fail)s</td>
  435. <td>%(error)s</td>
  436. <td>&nbsp;</td>
  437. </tr>
  438. </table>
  439. """ # variables: (test_list, count, Pass, fail, error)
  440. REPORT_CLASS_TMPL = u"""
  441. <tr class='%(style)s'>
  442. <td>%(desc)s</td>
  443. <td>%(count)s</td>
  444. <td>%(Pass)s</td>
  445. <td>%(fail)s</td>
  446. <td>%(error)s</td>
  447. <td><a href="javascript:showClassDetail('%(cid)s',%(count)s)">详情</a></td>
  448. </tr>
  449. """ # variables: (style, desc, count, Pass, fail, error, cid)
  450. REPORT_TEST_WITH_OUTPUT_TMPL = r"""
  451. <tr id='%(tid)s' class='%(Class)s'>
  452. <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
  453. <td colspan='5' align='center'>
  454. <!--css div popup start-->
  455. <a class="popup_link" onfocus='this.blur();' href="javascript:showTestDetail('div_%(tid)s')" >
  456. %(status)s</a>
  457. <div id='div_%(tid)s' class="popup_window">
  458. <pre>%(script)s</pre>
  459. </div>
  460. <!--css div popup end-->
  461. </td>
  462. </tr>
  463. """ # variables: (tid, Class, style, desc, status)
  464. REPORT_TEST_NO_OUTPUT_TMPL = r"""
  465. <tr id='%(tid)s' class='%(Class)s'>
  466. <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
  467. <td colspan='5' align='center'>%(status)s</td>
  468. </tr>
  469. """ # variables: (tid, Class, style, desc, status)
  470. REPORT_TEST_OUTPUT_TMPL = r"""%(id)s: %(output)s""" # variables: (id, output)
  471. # ------------------------------------------------------------------------
  472. # ENDING
  473. #
  474. ENDING_TMPL = """<div id='ending'>&nbsp;</div>"""
  475. # -------------------- The end of the Template class -------------------
  476. TestResult = unittest.TestResult
  477. class _TestResult(TestResult):
  478. # note: _TestResult is a pure representation of results.
  479. # It lacks the output and reporting ability compares to unittest._TextTestResult.
  480. def __init__(self, verbosity=1):
  481. TestResult.__init__(self)
  482. self.stdout0 = None
  483. self.stderr0 = None
  484. self.success_count = 0
  485. self.failure_count = 0
  486. self.error_count = 0
  487. self.verbosity = verbosity
  488. # result is a list of result in 4 tuple
  489. # (
  490. # result code (0: success; 1: fail; 2: error),
  491. # TestCase object,
  492. # Test output (byte string),
  493. # stack trace,
  494. # )
  495. self.result = []
  496. self.subtestlist = []
  497. def startTest(self, test):
  498. TestResult.startTest(self, test)
  499. # just one buffer for both stdout and stderr
  500. self.outputBuffer = io.StringIO()
  501. stdout_redirector.fp = self.outputBuffer
  502. stderr_redirector.fp = self.outputBuffer
  503. self.stdout0 = sys.stdout
  504. self.stderr0 = sys.stderr
  505. sys.stdout = stdout_redirector
  506. sys.stderr = stderr_redirector
  507. def complete_output(self):
  508. """
  509. Disconnect output redirection and return buffer.
  510. Safe to call multiple times.
  511. """
  512. if self.stdout0:
  513. sys.stdout = self.stdout0
  514. sys.stderr = self.stderr0
  515. self.stdout0 = None
  516. self.stderr0 = None
  517. return self.outputBuffer.getvalue()
  518. def stopTest(self, test):
  519. # Usually one of addSuccess, addError or addFailure would have been called.
  520. # But there are some path in unittest that would bypass this.
  521. # We must disconnect stdout in stopTest(), which is guaranteed to be called.
  522. self.complete_output()
  523. def addSuccess(self, test):
  524. if test not in self.subtestlist:
  525. self.success_count += 1
  526. TestResult.addSuccess(self, test)
  527. output = self.complete_output()
  528. self.result.append((0, test, output, ''))
  529. if self.verbosity > 1:
  530. sys.stderr.write('ok ')
  531. sys.stderr.write(str(test))
  532. sys.stderr.write('\n')
  533. else:
  534. sys.stderr.write('.')
  535. def addError(self, test, err):
  536. self.error_count += 1
  537. TestResult.addError(self, test, err)
  538. _, _exc_str = self.errors[-1]
  539. output = self.complete_output()
  540. self.result.append((2, test, output, _exc_str))
  541. if self.verbosity > 1:
  542. sys.stderr.write('E ')
  543. sys.stderr.write(str(test))
  544. sys.stderr.write('\n')
  545. else:
  546. sys.stderr.write('E')
  547. def addFailure(self, test, err):
  548. self.failure_count += 1
  549. TestResult.addFailure(self, test, err)
  550. _, _exc_str = self.failures[-1]
  551. output = self.complete_output()
  552. self.result.append((1, test, output, _exc_str))
  553. if self.verbosity > 1:
  554. sys.stderr.write('F ')
  555. sys.stderr.write(str(test))
  556. sys.stderr.write('\n')
  557. else:
  558. sys.stderr.write('F')
  559. def addSubTest(self, test, subtest, err):
  560. if err is not None:
  561. if getattr(self, 'failfast', False):
  562. self.stop()
  563. if issubclass(err[0], test.failureException):
  564. self.failure_count += 1
  565. errors = self.failures
  566. errors.append((subtest, self._exc_info_to_string(err, subtest)))
  567. output = self.complete_output()
  568. self.result.append((1, test, output + '\nSubTestCase Failed:\n' + str(subtest),
  569. self._exc_info_to_string(err, subtest)))
  570. if self.verbosity > 1:
  571. sys.stderr.write('F ')
  572. sys.stderr.write(str(subtest))
  573. sys.stderr.write('\n')
  574. else:
  575. sys.stderr.write('F')
  576. else:
  577. self.error_count += 1
  578. errors = self.errors
  579. errors.append((subtest, self._exc_info_to_string(err, subtest)))
  580. output = self.complete_output()
  581. self.result.append(
  582. (2, test, output + '\nSubTestCase Error:\n' + str(subtest), self._exc_info_to_string(err, subtest)))
  583. if self.verbosity > 1:
  584. sys.stderr.write('E ')
  585. sys.stderr.write(str(subtest))
  586. sys.stderr.write('\n')
  587. else:
  588. sys.stderr.write('E')
  589. self._mirrorOutput = True
  590. else:
  591. self.subtestlist.append(subtest)
  592. self.subtestlist.append(test)
  593. self.success_count += 1
  594. output = self.complete_output()
  595. self.result.append((0, test, output + '\nSubTestCase Pass:\n' + str(subtest), ''))
  596. if self.verbosity > 1:
  597. sys.stderr.write('ok ')
  598. sys.stderr.write(str(subtest))
  599. sys.stderr.write('\n')
  600. else:
  601. sys.stderr.write('.')
  602. class HTMLTestRunner(Template_mixin):
  603. def __init__(self, stream=sys.stdout, verbosity=1, title=None, description=None):
  604. self.stream = stream
  605. self.verbosity = verbosity
  606. if title is None:
  607. self.title = self.DEFAULT_TITLE
  608. else:
  609. self.title = title
  610. if description is None:
  611. self.description = self.DEFAULT_DESCRIPTION
  612. else:
  613. self.description = description
  614. self.startTime = datetime.datetime.now()
  615. def run(self, test):
  616. "Run the given test case or test suite."
  617. result = _TestResult(self.verbosity)
  618. test(result)
  619. self.stopTime = datetime.datetime.now()
  620. self.generateReport(test, result)
  621. print('\nTime Elapsed: %s' % (self.stopTime - self.startTime), file=sys.stderr)
  622. return result
  623. def sortResult(self, result_list):
  624. # unittest does not seems to run in any particular order.
  625. # Here at least we want to group them together by class.
  626. rmap = {}
  627. classes = []
  628. for n, t, o, e in result_list:
  629. cls = t.__class__
  630. if cls not in rmap:
  631. rmap[cls] = []
  632. classes.append(cls)
  633. rmap[cls].append((n, t, o, e))
  634. r = [(cls, rmap[cls]) for cls in classes]
  635. return r
  636. def getReportAttributes(self, result):
  637. """
  638. Return report attributes as a list of (name, value).
  639. Override this to add custom attributes.
  640. """
  641. startTime = str(self.startTime)[:19]
  642. duration = str(self.stopTime - self.startTime)
  643. status = []
  644. if result.success_count: status.append(u'通过 %s' % result.success_count)
  645. if result.failure_count: status.append(u'失败 %s' % result.failure_count)
  646. if result.error_count: status.append(u'错误 %s' % result.error_count)
  647. if status:
  648. status = ' '.join(status)
  649. else:
  650. status = 'none'
  651. return [
  652. (u'开始时间', startTime),
  653. (u'运行时长', duration),
  654. (u'状态', status),
  655. ]
  656. def generateReport(self, test, result):
  657. report_attrs = self.getReportAttributes(result)
  658. generator = 'HTMLTestRunner %s' % __version__
  659. stylesheet = self._generate_stylesheet()
  660. heading = self._generate_heading(report_attrs)
  661. report = self._generate_report(result)
  662. ending = self._generate_ending()
  663. chart = self._generate_chart(result)
  664. output = self.HTML_TMPL % dict(
  665. title=saxutils.escape(self.title),
  666. generator=generator,
  667. stylesheet=stylesheet,
  668. heading=heading,
  669. report=report,
  670. ending=ending,
  671. chart_script=chart
  672. )
  673. self.stream.write(output.encode('utf8'))
  674. def _generate_stylesheet(self):
  675. return self.STYLESHEET_TMPL
  676. def _generate_heading(self, report_attrs):
  677. a_lines = []
  678. for name, value in report_attrs:
  679. line = self.HEADING_ATTRIBUTE_TMPL % dict(
  680. name=saxutils.escape(name),
  681. value=saxutils.escape(value),
  682. )
  683. a_lines.append(line)
  684. heading = self.HEADING_TMPL % dict(
  685. title=saxutils.escape(self.title),
  686. parameters=''.join(a_lines),
  687. description=saxutils.escape(self.description),
  688. )
  689. return heading
  690. def _generate_report(self, result):
  691. rows = []
  692. sortedResult = self.sortResult(result.result)
  693. for cid, (cls, cls_results) in enumerate(sortedResult):
  694. # subtotal for a class
  695. np = nf = ne = 0
  696. for n, t, o, e in cls_results:
  697. if n == 0:
  698. np += 1
  699. elif n == 1:
  700. nf += 1
  701. else:
  702. ne += 1
  703. # format class description
  704. if cls.__module__ == "__main__":
  705. name = cls.__name__
  706. else:
  707. name = "%s.%s" % (cls.__module__, cls.__name__)
  708. doc = cls.__doc__ and cls.__doc__.split("\n")[0] or ""
  709. desc = doc and '%s: %s' % (name, doc) or name
  710. row = self.REPORT_CLASS_TMPL % dict(
  711. style=ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass',
  712. desc=desc,
  713. count=np + nf + ne,
  714. Pass=np,
  715. fail=nf,
  716. error=ne,
  717. cid='c%s' % (cid + 1),
  718. )
  719. rows.append(row)
  720. for tid, (n, t, o, e) in enumerate(cls_results):
  721. self._generate_report_test(rows, cid, tid, n, t, o, e)
  722. report = self.REPORT_TMPL % dict(
  723. test_list=''.join(rows),
  724. count=str(result.success_count + result.failure_count + result.error_count),
  725. Pass=str(result.success_count),
  726. fail=str(result.failure_count),
  727. error=str(result.error_count),
  728. )
  729. return report
  730. def _generate_chart(self, result):
  731. chart = self.ECHARTS_SCRIPT % dict(
  732. Pass=str(result.success_count),
  733. fail=str(result.failure_count),
  734. error=str(result.error_count),
  735. )
  736. return chart
  737. def _generate_report_test(self, rows, cid, tid, n, t, o, e):
  738. # e.g. 'pt1.1', 'ft1.1', etc
  739. has_output = bool(o or e)
  740. tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid + 1, tid + 1)
  741. name = t.id().split('.')[-1]
  742. doc = t.shortDescription() or ""
  743. desc = doc and ('%s: %s' % (name, doc)) or name
  744. tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL
  745. script = self.REPORT_TEST_OUTPUT_TMPL % dict(
  746. id=tid,
  747. output=saxutils.escape(o + e),
  748. )
  749. row = tmpl % dict(
  750. tid=tid,
  751. Class=(n == 0 and 'hiddenRow' or 'none'),
  752. style=(n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none')),
  753. desc=desc,
  754. script=script,
  755. status=self.STATUS[n],
  756. )
  757. rows.append(row)
  758. if not has_output:
  759. return
  760. def _generate_ending(self):
  761. return self.ENDING_TMPL
  762. ##############################################################################
  763. # Facilities for running tests from the command line
  764. ##############################################################################
  765. # Note: Reuse unittest.TestProgram to launch test. In the future we may
  766. # build our own launcher to support more specific command line
  767. # parameters like test title, CSS, etc.
  768. class TestProgram(unittest.TestProgram):
  769. """
  770. A variation of the unittest.TestProgram. Please refer to the base
  771. class for command line parameters.
  772. """
  773. def runTests(self):
  774. # Pick HTMLTestRunner as the default test runner.
  775. # base class's testRunner parameter is not useful because it means
  776. # we have to instantiate HTMLTestRunner before we know self.verbosity.
  777. if self.testRunner is None:
  778. self.testRunner = HTMLTestRunner(verbosity=self.verbosity)
  779. unittest.TestProgram.runTests(self)
  780. main = TestProgram
  781. ##############################################################################
  782. # Executing this module from the command line
  783. ##############################################################################
  784. if __name__ == "__main__":
  785. main(module=None)

将作者的HTMLTestRunner.py拷贝出来

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

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

这个文件的作用是,我们通过这个文件来控制,执行哪些模块下的哪些unittest用例文件。如在实际的项目中:user模块下的test01case.py如果本轮无需执行哪些模块的用例的话,就在前面添加#。还缺少一个发送邮件的文件。在common下创建configEmail.py文件,内容如下:

  1. import smtplib
  2. from email.mime.text import MIMEText
  3. class SendEmail(object):
  4. def send_email(self):
  5. msg_from = 'zzzz@qq.com' # 发送方邮箱
  6. passwd = 'xxxxxx' # 填入发送方邮箱的授权码
  7. msg_to = 'xxxxx@qq.com' # 收件人邮箱
  8. subject = "python邮件测试" # 主题
  9. f = open("F:\\jiekouceshikj\\result\\report.html", 'rb')
  10. content = f.read()
  11. f.close()
  12. message=content.decode('utf-8')
  13. msg = MIMEText(message)
  14. msg['Subject'] = subject
  15. msg['From'] = msg_from
  16. msg['To'] = msg_to
  17. try:
  18. s = smtplib.SMTP_SSL("smtp.qq.com", 465)
  19. s.login(msg_from, passwd)
  20. s.sendmail(msg_from, msg_to, msg.as_string())
  21. print("发送成功")
  22. except s.SMTPException as e:
  23. print("发送失败")
  24. finally:
  25. s.quit()
  26. if __name__ == '__main__':
  27. SendEmail().send_email()

 没有用作者文中的发送邮件,没有调通,先用这个,这个只能把html里面的内容直接放在邮件里,后续再研究怎么直接添加htm作为附件来发送邮件

研究了一下怎样将html作为附件来发送邮件

  1. import smtplib
  2. from email.mime.multipart import MIMEMultipart
  3. from email.mime.text import MIMEText
  4. class SendEmail(object):
  5. def send_email(self):
  6. msg_from = 'xxxxxx@qq.com' # 发送方邮箱
  7. passwd = 'xxxxx' # 填入发送方邮箱的授权码
  8. msg_to = 'xxxxx@qq.com' # 收件人邮箱
  9. subject = "python邮件测试" # 主题
  10. f = open("F:\\jiekouceshikj\\result\\report.html", 'rb')
  11. content = f.read()
  12. mail_mul = MIMEMultipart() # 构建一个邮件对象
  13. mail_text = MIMEText("各位好,附件是本次的测试报告,请查阅!谢谢", "plain", "utf-8") # 构建邮件正文
  14. mail_mul.attach(mail_text) # 把构建好的邮件正文附加到邮件中
  15. # 设置附件
  16. msg = MIMEText(content, 'html', 'utf-8')
  17. msg['Content-type'] = 'application/octet-stream'
  18. msg['Content-disposition'] = "attachment; filename ='test.html'"
  19. mail_mul.attach(msg) # 将附加按添加到邮件中
  20. msg['Subject'] = subject
  21. msg['From'] = msg_from
  22. msg['To'] = msg_to
  23. try:
  24. s = smtplib.SMTP_SSL("smtp.qq.com", 465)
  25. s.login(msg_from, passwd)
  26. s.sendmail(msg_from, msg_to, msg.as_string())
  27. print("发送成功")
  28. except s.SMTPException as e:
  29. print("发送失败")
  30. finally:
  31. s.quit()
  32. if __name__ == '__main__':
  33. SendEmail().send_email()

继续往下走,这下我们该创建我们的runAll.py文件了

 
  1.  
    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. import common.log
    8. send_mail = SendEmail()
    9. path = getpathInfo.get_Path()
    10. report_path = os.path.join(path, 'result')
    11. on_off = readConfig.ReadConfig().get_email('on_off')
    12. log=common.log.logger
    13. class AllTest: # 定义一个类AllTest
    14. def __init__(self): # 初始化一些参数和数据
    15. global resultPath
    16. resultPath = os.path.join(report_path, "report.html") # result/report.html
    17. self.caseListFile = os.path.join(path, "caselist.txt") # 配置执行哪些测试文件的配置文件路径
    18. self.caseFile = os.path.join(path, "testcase") # 真正的测试断言文件路径
    19. self.caseList = []
    20. log.info('resultPath',resultPath)#将resultPath的值输入到日志,方便定位查看问题
    21. # log.info('caseListFile',self.caseListFile)
    22. # log.info('caselist',self.caseList)
    23. def set_case_list(self):
    24. fb = open(self.caseListFile)
    25. for value in fb.readlines():
    26. data = str(value)
    27. if data != '' and not data.startswith("#"): # 如果data非空且不以#开头
    28. self.caseList.append(data.replace("\n", "")) # 读取每行数据会将换行转换为\n,去掉每行数据中的\n
    29. fb.close()
    30. def set_case_suite(self):
    31. self.set_case_list() # 通过set_case_list()拿到caselist元素组
    32. test_suite = unittest.TestSuite()
    33. suite_module = []
    34. for case in self.caseList: # 从caselist元素组中循环取出case
    35. case_name = case.split("/")[-1] # 通过split函数来将aaa/bbb分割字符串,-1取后面,0取前面
    36. print(case_name + ".py") # 打印出取出来的名称
    37. # 批量加载用例,第一个参数为用例存放路径,第一个参数为路径文件名
    38. discover = unittest.defaultTestLoader.discover(self.caseFile, pattern=case_name + '.py', top_level_dir=None)
    39. suite_module.append(discover) # 将discover存入suite_module元素组
    40. print('suite_module:' + str(suite_module))
    41. if len(suite_module) > 0: # 判断suite_module元素组是否存在元素
    42. for suite in suite_module: # 如果存在,循环取出元素组内容,命名为suite
    43. for test_name in suite: # 从discover中取出test_name,使用addTest添加到测试集
    44. test_suite.addTest(test_name)
    45. else:
    46. print('else:')
    47. return None
    48. return test_suite # 返回测试集
    49. def run(self):
    50. try:
    51. suit = self.set_case_suite() # 调用set_case_suite获取test_suite
    52. print('try')
    53. print(str(suit))
    54. if suit is not None: # 判断test_suite是否为空
    55. print('if-suit')
    56. fp = open(resultPath, 'wb') # 打开result/report.html测试报告文件,如果不存在就创建
    57. # 调用HTMLTestRunner
    58. runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Test Report', description='Test Description')
    59. runner.run(suit)
    60. else:
    61. print("Have no case to test.")
    62. except Exception as ex:
    63. print(str(ex))
    64. finally:
    65. print("*********TEST END*********")
    66. fp.close()
    67. # 判断邮件发送的开关
    68. if on_off == 'on':
    69. send_mail.send_email()
    70. else:
    71. print("邮件发送开关配置关闭,请打开开关后可正常自动发送测试报告")
    72. if __name__ == '__main__':
    73. AllTest().run()

    九、Python+unittest+requests+HTMLTestRunner完整的接口自动化测试框架搭建_08——生成log文件    

我们修改runAll.py文件,在顶部增加import common.Log,然后增加标红框的代码

让我们再来运行一下runAll.py文件,发现在result下多了一个logs文件,我们打开看一下有没有我们打印的日志

十、Python+unittest+requests+HTMLTestRunner完整的接口自动化测试框架搭建_09——Jenkins构建定时任务自动执行测试

Jenkins的搭建就不赘述,网上很多,现在说一下项目配置

先cd到项目目录下

然后用python的环境执行一下脚本

因为脚本里面有发送邮件的配置,这里Jenkins就不需要配置邮件了。 

感谢作者的文档,照着抄写然后结合实际项目更改了一下,运行起来了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/249864
推荐阅读
相关标签
  

闽ICP备14008679号