python_接口自动化测试框架
Posted 程序员老波
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python_接口自动化测试框架相关的知识,希望对你有一定的参考价值。
本文总结分享介绍接口测试框架开发,环境使用python3+selenium3+unittest+ddt+requests测试框架及ddt数据驱动,采用Excel管理测试用例等集成测试数据功能,以及使用htmlTestRunner来生成测试报告,目前有开源的poman、Jmeter等接口测试工具,为什么还要开发接口测试框架呢?因接口测试工具也有存在几点不足。
- 测试数据不可控制。比如接口返回数据不可控,就无法自动断言接口返回的数据,不能断定是接口程序引起,还是测试数据变化引起的错误,所以需要做一些初始化测试数据。接口工具没有具备初始化测试数据功能,无法做到真正的接口测试自动化。
- 无法测试加密接口。实际项目中,多数接口不是可以随便调用,一般情况无法摸拟和生成加密算法。如时间戳和MDB加密算法,一般接口工具无法摸拟。
- 扩展能力不足。开源的接口测试工具无法实现扩展功能。比如,我们想生成不同格式的测试报告,想将测试报告发送到指定邮箱,又想让接口测试集成到CI中,做持续集成定时任务。
测试框架处理流程
测试框架处理过程如下:
- 首先初始化清空数据库表的数据,向数据库插入测试数据;
- 调用被测试系统提供的接口,先数据驱动读取excel用例一行数据;
- 发送请求数据,根据传参数据,向数据库查询得到对应的数据;
- 将查询的结果组装成JSON格式的数据,同时根据返回的数据值与Excel的值对比判断,并写入结果至指定Excel测试用例表格;
- 通过单元测试框架断言接口返回的数据,并生成测试报告,最后把生成最新的测试报告HTML文件发送指定的邮箱。
测试框架结构目录介绍
目录结构介绍如下:
- config/: 文件路径配置
- database/: 测试用例模板文件及数据库和发送邮箱配置文件
- db_fixture/: 初始化接口测试数据
- lib/: 程序核心模块。包含有excel解析读写、发送邮箱、发送请求、生成最新测试报告文件
- package/: 存放第三方库包。如HTMLTestRunner,用于生成HTML格式测试报告
- report/: 生成接口自动化测试报告
- testcase/: 用于编写接口自动化测试用例
- run_demo.py: 执行所有接口测试用例的主程序
- GitHub项目地址: GitHub - yingoja/DemoAPI: 基于python的接口自动化测试框架
数据库封装
1 [tester] 2 name = Jason 3 4 [mysqlconf] 5 host = 127.0.0.1 6 port = 3306 7 user = root 8 password = 123456 9 db_name = guest 10 11 [user] 12 # 发送邮箱服务器 13 HOST_SERVER = smtp.163.com 14 # 邮件发件人 15 FROM = 111@163.com 16 # 邮件收件人 17 TO = 222@126.com 18 # 发送邮箱用户名/密码 19 user = aaa 20 password = aaa 21 # 邮件主题 22 SUBJECT = 发布会系统接口自动化测试报告
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import os,sys 6 sys.path.append(os.path.dirname(os.path.dirname(__file__))) 7 from config import setting 8 from pymysql import connect,cursors 9 from pymysql.err import OperationalError 10 import configparser as cparser 11 12 # --------- 读取config.ini配置文件 --------------- 13 cf = cparser.ConfigParser() 14 cf.read(setting.TEST_CONFIG,encoding='UTF-8') 15 host = cf.get("mysqlconf","host") 16 port = cf.get("mysqlconf","port") 17 user = cf.get("mysqlconf","user") 18 password = cf.get("mysqlconf","password") 19 db = cf.get("mysqlconf","db_name") 20 21 class DB: 22 """ 23 MySQL基本操作 24 """ 25 def __init__(self): 26 try: 27 # 连接数据库 28 self.conn = connect(host = host, 29 user = user, 30 password = password, 31 db = db, 32 charset = 'utf8mb4', 33 cursorclass = cursors.DictCursor 34 ) 35 except OperationalError as e: 36 print("Mysql Error %d: %s" % (e.args[0],e.args[1])) 37 38 # 清除表数据 39 def clear(self,table_name): 40 real_sql = "delete from " + table_name + ";" 41 with self.conn.cursor() as cursor: 42 # 取消表的外键约束 43 cursor.execute("SET FOREIGN_KEY_CHECKS=0;") 44 cursor.execute(real_sql) 45 self.conn.commit() 46 47 # 插入表数据 48 def insert(self, table_name, table_data): 49 for key in table_data: 50 table_data[key] = "'"+str(table_data[key])+"'" 51 key = ','.join(table_data.keys()) 52 value = ','.join(table_data.values()) 53 real_sql = "INSERT INTO " + table_name + " (" + key + ") VALUES (" + value + ")" 54 55 with self.conn.cursor() as cursor: 56 cursor.execute(real_sql) 57 self.conn.commit() 58 59 # 关闭数据库 60 def close(self): 61 self.conn.close() 62 63 # 初始化数据 64 def init_data(self, datas): 65 for table, data in datas.items(): 66 self.clear(table) 67 for d in data: 68 self.insert(table, d) 69 self.close()
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import sys, time, os 6 sys.path.append(os.path.dirname(os.path.dirname(__file__))) 7 from db_fixture.mysql_db import DB 8 9 # 定义过去时间 10 past_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()-100000)) 11 # 定义将来时间 12 future_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()+10000)) 13 14 # 创建测试数据 15 datas = 16 # 发布会表数据 17 'sign_event':[ 18 'id':1,'name':'红米Pro发布会','`limit`':2000,'status':1,'address':'北京会展中心','start_time':future_time, 19 'id':2,'name':'苹果iphon6发布会','`limit`':1000,'status':1,'address':'宝安体育馆','start_time':future_time, 20 'id':3,'name':'华为荣耀8发布会','`limit`':2000,'status':0,'address':'深圳福田会展中心','start_time':future_time, 21 'id':4,'name':'苹果iphon8发布会','`limit`':2000,'status':1,'address':'深圳湾体育中心','start_time':past_time, 22 'id':5,'name':'小米5发布会','`limit`':2000,'status':1,'address':'北京国家会议中心','start_time':future_time, 23 ], 24 # 嘉宾表数据 25 'sign_guest':[ 26 'id':1,'realname':'Tom','phone':13511886601,'email':'alen@mail.com','sign':0,'event_id':1, 27 'id':2,'realname':'Jason','phone':13511886602,'email':'sign@mail.com','sign':1,'event_id':1, 28 'id':3,'realname':'Jams','phone':13511886603,'email':'tom@mail.com','sign':0,'event_id':5, 29 ], 30 31 32 # 测试数据插入表 33 def init_data(): 34 DB().init_data(datas)
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import os,sys 6 BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 7 sys.path.append(BASE_DIR) 8 9 # 配置文件 10 TEST_CONFIG = os.path.join(BASE_DIR,"database","config.ini") 11 # 测试用例模板文件 12 SOURCE_FILE = os.path.join(BASE_DIR,"database","DemoAPITestCase.xlsx") 13 # excel测试用例结果文件 14 TARGET_FILE = os.path.join(BASE_DIR,"report","excelReport","DemoAPITestCase.xlsx") 15 # 测试用例报告 16 TEST_REPORT = os.path.join(BASE_DIR,"report") 17 # 测试用例程序文件 18 TEST_CASE = os.path.join(BASE_DIR,"testcase")
程序核心模块
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import os 6 7 def new_report(testreport): 8 """ 9 生成最新的测试报告文件 10 :param testreport: 11 :return:返回文件 12 """ 13 lists = os.listdir(testreport) 14 lists.sort(key=lambda fn: os.path.getmtime(testreport + "\\\\" + fn)) 15 file_new = os.path.join(testreport,lists[-1]) 16 return file_new
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import xlrd 6 7 class ReadExcel(): 8 """读取excel文件数据""" 9 def __init__(self,fileName, SheetName="Sheet1"): 10 self.data = xlrd.open_workbook(fileName) 11 self.table = self.data.sheet_by_name(SheetName) 12 13 # 获取总行数、总列数 14 self.nrows = self.table.nrows 15 self.ncols = self.table.ncols 16 def read_data(self): 17 if self.nrows > 1: 18 # 获取第一行的内容,列表格式 19 keys = self.table.row_values(0) 20 listApiData = [] 21 # 获取每一行的内容,列表格式 22 for col in range(1, self.nrows): 23 values = self.table.row_values(col) 24 # keys,values组合转换为字典 25 api_dict = dict(zip(keys, values)) 26 listApiData.append(api_dict) 27 return listApiData 28 else: 29 print("表格是空数据!") 30 return None
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import os,sys,json 6 sys.path.append(os.path.dirname(os.path.dirname(__file__))) 7 8 9 class SendRequests(): 10 """发送请求数据""" 11 def sendRequests(self,s,apiData): 12 try: 13 #从读取的表格中获取响应的参数作为传递 14 method = apiData["method"] 15 url = apiData["url"] 16 if apiData["params"] == "": 17 par = None 18 else: 19 par = eval(apiData["params"]) 20 if apiData["headers"] == "": 21 h = None 22 else: 23 h = eval(apiData["headers"]) 24 if apiData["body"] == "": 25 body_data = None 26 else: 27 body_data = eval(apiData["body"]) 28 type = apiData["type"] 29 v = False 30 if type == "data": 31 body = body_data 32 elif type == "json": 33 body = json.dumps(body_data) 34 else: 35 body = body_data 36 37 #发送请求 38 re = s.request(method=method,url=url,headers=h,params=par,data=body,verify=v) 39 return re 40 except Exception as e: 41 print(e)
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import os,sys 6 sys.path.append(os.path.dirname(os.path.dirname(__file__))) 7 from config import setting 8 import smtplib 9 from lib.newReport import new_report 10 import configparser 11 from email.mime.text import MIMEText 12 from email.mime.multipart import MIMEMultipart 13 14 15 def send_mail(file_new): 16 """ 17 定义发送邮件 18 :param file_new: 19 :return: 成功:打印发送邮箱成功;失败:返回失败信息 20 """ 21 f = open(file_new,'rb') 22 mail_body = f.read() 23 f.close() 24 #发送附件 25 con = configparser.ConfigParser() 26 con.read(setting.TEST_CONFIG,encoding='utf-8') 27 report = new_report(setting.TEST_REPORT) 28 sendfile = open(report,'rb').read() 29 # --------- 读取config.ini配置文件 --------------- 30 HOST = con.get("user","HOST_SERVER") 31 SENDER = con.get("user","FROM") 32 RECEIVER = con.get("user","TO") 33 USER = con.get("user","user") 34 PWD = con.get("user","password") 35 SUBJECT = con.get("user","SUBJECT") 36 37 att = MIMEText(sendfile,'base64','utf-8') 38 att["Content-Type"] = 'application/octet-stream' 39 att.add_header("Content-Disposition", "attachment", filename=("gbk", "", report)) 40 41 msg = MIMEMultipart('related') 42 msg.attach(att) 43 msgtext = MIMEText(mail_body,'html','utf-8') 44 msg.attach(msgtext) 45 msg['Subject'] = SUBJECT 46 msg['from'] = SENDER 47 msg['to'] = RECEIVER 48 49 try: 50 server = smtplib.SMTP() 51 server.connect(HOST) 52 server.starttls() 53 server.login(USER,PWD) 54 server.sendmail(SENDER,RECEIVER,msg.as_string()) 55 server.quit() 56 print("邮件发送成功!") 57 except Exception as e: 58 print("失败: " + str(e))
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import os,sys 6 sys.path.append(os.path.dirname(os.path.dirname(__file__))) 7 import shutil 8 from config import setting 9 from openpyxl import load_workbook 10 from openpyxl.styles import Font,Alignment 11 from openpyxl.styles.colors import RED,GREEN,DARKYELLOW 12 import configparser as cparser 13 14 # --------- 读取config.ini配置文件 --------------- 15 cf = cparser.ConfigParser() 16 cf.read(setting.TEST_CONFIG,encoding='UTF-8') 17 name = cf.get("tester","name") 18 19 class WriteExcel(): 20 """文件写入数据""" 21 def __init__(self,fileName): 22 self.filename = fileName 23 if not os.path.exists(self.filename): 24 # 文件不存在,则拷贝模板文件至指定报告目录下 25 shutil.copyfile(setting.SOURCE_FILE,setting.TARGET_FILE) 26 self.wb = load_workbook(self.filename) 27 self.ws = self.wb.active 28 29 def write_data(self,row_n,value): 30 """ 31 写入测试结果 32 :param row_n:数据所在行数 33 :param value: 测试结果值 34 :return: 无 35 """ 36 font_GREEN = Font(name='宋体', color=GREEN, bold=True) 37 font_RED = Font(name='宋体', color=RED, bold=True) 38 font1 = Font(name='宋体', color=DARKYELLOW, bold=True) 39 align = Alignment(horizontal='center', vertical='center') 40 # 获数所在行数 41 L_n = "L" + str(row_n) 42 M_n = "M" + str(row_n) 43 if value == "PASS": 44 self.ws.cell(row_n, 12, value) 45 self.ws[L_n].font = font_GREEN 46 if value == "FAIL": 47 self.ws.cell(row_n, 12, value) 48 self.ws[L_n].font = font_RED 49 self.ws.cell(row_n, 13, name) 50 self.ws[L_n].alignment = align 51 self.ws[M_n].font = font1 52 self.ws[M_n].alignment = align 53 self.wb.save(self.filename)
接口测试用例编写
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 import os,sys 6 sys.path.append(os.path.dirname(os.path.dirname(__file__))) 7 import unittest,requests,ddt 8 from config import setting 9 from lib.readexcel import ReadExcel 10 from lib.sendrequests import SendRequests 11 from lib.writeexcel import WriteExcel 12 13 testData = ReadExcel(setting.SOURCE_FILE, "Sheet1").read_data() 14 15 @ddt.ddt 16 class Demo_API(unittest.TestCase): 17 """发布会系统""" 18 def setUp(self): 19 self.s = requests.session() 20 21 def tearDown(self): 22 pass 23 24 @ddt.data(*testData) 25 def test_api(self,data): 26 # 获取ID字段数值,截取结尾数字并去掉开头0 27 rowNum = int(data['ID'].split("_")[2]) 28 # 发送请求 29 re = SendRequests().sendRequests(self.s,data) 30 # 获取服务端返回的值 31 self.result = re.json() 32 # 获取excel表格数据的状态码和消息 33 readData_code = int(data["status_code"]) 34 readData_msg = data["msg"] 35 if readData_code == self.result['status'] and readData_msg == self.result['message']: 36 OK_data = "PASS" 37 WriteExcel(setting.TARGET_FILE).write_data(rowNum + 1,OK_data) 38 if readData_code != self.result['status'] or readData_msg != self.result['message']: 39 NOT_data = "FAIL" 40 WriteExcel(setting.TARGET_FILE).write_data(rowNum + 1,NOT_data) 41 self.assertEqual(self.result['status'], readData_code, "返回实际结果是->:%s" % self.result['status']) 42 self.assertEqual(self.result['message'], readData_msg, "返回实际结果是->:%s" % self.result['message']) 43 44 if __name__=='__main__': 45 unittest.main()
集成测试报告
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = 'YinJia' 4 5 6 import os,sys 7 sys.path.append(os.path.dirname(__file__)) 8 from config import setting 9 import unittest,time 10 from HTMLTestRunner import HTMLTestRunner 11 from lib.sendmail import send_mail 12 from lib.newReport import new_report 13 from db_fixture import test_data 14 from package.HTMLTestRunner import HTMLTestRunner 15 16 def add_case(test_path=setting.TEST_CASE): 17 """加载所有的测试用例""" 18 discover = unittest.defaultTestLoader.discover(test_path, pattern='*API.py') 19 return discover 20 21 def run_case(all_case,result_path=setting.TEST_REPORT): 22 """执行所有的测试用例""" 23 24 # 初始化接口测试数据 25 test_data.init_data() 26 27 now = time.strftime("%Y-%m-%d %H_%M_%S") 28 filename = result_path + '/' + now + 'result.html' 29 fp = open(filename,'wb') 30 runner = HTMLTestRunner(stream=fp,title='发布会系统接口自动化测试报告', 31 description='环境:windows 7 浏览器:chrome', 32 tester='Jason') 33 runner.run(all_case) 34 fp.close() 35 report = new_report(setting.TEST_REPORT) #调用模块生成最新的报告 36 send_mail(report) #调用发送邮件模块 37 38 if __name__ =="__main__": 39 cases = add_case() 40 run_case(cases)
测试结果展示
- HTML测试结果报告:
- Excel测试用例结果
- 邮件收到的测试报告
Python+requests+exce接口自动化测试框架
一、接口自动化测试框架
二、工程目录
三、Excel测试用例设计
四、基础数据base
封装post/get:runmethod.py
#!/usr/bin/env python3 # -*-coding:utf-8-*- # __author__: hunter import requests import json class RunMain: def send_get(self, url, data): res = requests.get(url=url, params=data).json() # return res return json.dumps(res, indent=2, sort_keys=False, ensure_ascii=False) def send_post(self, url, data): res = requests.post(url=url, data=json.dumps(data)).json() # return res return json.dumps(res, indent=2, sort_keys=False, ensure_ascii=False) def run_main(self, url, method, data=None): if method == \'POST\': res = self.send_post(url, data) else: res = self.send_get(url, data) return res
HTMLTestrunner:测试报告
""" A TestRunner for use with the Python unit testing framework. It generates a HTML report to show the result at a glance. The simplest way to use this is to invoke its main method. E.g. import unittest import HTMLTestRunner ... define your tests ... if __name__ == \'__main__\': HTMLTestRunner.main() For more customization options, instantiates a HTMLTestRunner object. HTMLTestRunner is a counterpart to unittest\'s TextTestRunner. E.g. # output to a file fp = file(\'my_report.html\', \'wb\') runner = HTMLTestRunner.HTMLTestRunner( stream=fp, title=\'My unit test\', description=\'This demonstrates the report output by HTMLTestRunner.\' ) # Use an external stylesheet. # See the Template_mixin class for more customizable options runner.STYLESHEET_TMPL = \'<link rel="stylesheet" href="my_stylesheet.css" type="text/css">\' # run the test runner.run(my_test_suite) ------------------------------------------------------------------------ Copyright (c) 2004-2007, Wai Yip Tung All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name Wai Yip Tung nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # URL: http://tungwaiyip.info/software/HTMLTestRunner.html __author__ = "Wai Yip Tung" __version__ = "0.8.2" """ Change History Version 0.8.2 * Show output inline instead of popup window (Viorel Lupu). Version in 0.8.1 * Validated XHTML (Wolfgang Borgert). * Added description of test classes and test cases. Version in 0.8.0 * Define Template_mixin class for customization. * Workaround a IE 6 bug that it does not treat <script> block as CDATA. Version in 0.7.1 * Back port to Python 2.3 (Frank Horowitz). * Fix missing scroll bars in detail log (Podi). """ # TODO: color stderr # TODO: simplify javascript using ,ore than 1 class in the class attribute? import datetime import io import sys import time import unittest from xml.sax import saxutils # ------------------------------------------------------------------------ # The redirectors below are used to capture output during testing. Output # sent to sys.stdout and sys.stderr are automatically captured. However # in some cases sys.stdout is already cached before HTMLTestRunner is # invoked (e.g. calling logging.basicConfig). In order to capture those # output, use the redirectors for the cached stream. # # e.g. # >>> logging.basicConfig(stream=HTMLTestRunner.stdout_redirector) # >>> class OutputRedirector(object): """ Wrapper to redirect stdout or stderr """ def __init__(self, fp): self.fp = fp def write(self, s): self.fp.write(s) def writelines(self, lines): self.fp.writelines(lines) def flush(self): self.fp.flush() stdout_redirector = OutputRedirector(sys.stdout) stderr_redirector = OutputRedirector(sys.stderr) # ---------------------------------------------------------------------- # Template class Template_mixin(object): """ Define a HTML template for report customerization and generation. Overall structure of an HTML report HTML +------------------------+ |<html> | | <head> | | | | STYLESHEET | | +----------------+ | | | | | | +----------------+ | | | | </head> | | | | <body> | | | | HEADING | | +----------------+ | | | | | | +----------------+ | | | | REPORT | | +----------------+ | | | | | | +----------------+ | | | | ENDING | | +----------------+ | | | | | | +----------------+ | | | | </body> | |</html> | +------------------------+ """ STATUS = { 0: \'pass\', 1: \'fail\', 2: \'error\', } DEFAULT_TITLE = \'Unit Test Report\' DEFAULT_DESCRIPTION = \'\' # ------------------------------------------------------------------------ # HTML Template HTML_TMPL = r"""<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>%(title)s</title> <meta name="generator" content="%(generator)s"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> %(stylesheet)s </head> <body> <script language="javascript" type="text/javascript"><!-- output_list = Array(); /* level - 0:Summary; 1:Failed; 2:All */ function showCase(level) { trs = document.getElementsByTagName("tr"); for (var i = 0; i < trs.length; i++) { tr = trs[i]; id = tr.id; if (id.substr(0,2) == \'ft\') { if (level < 1) { tr.className = \'hiddenRow\'; } else { tr.className = \'\'; } } if (id.substr(0,2) == \'pt\') { if (level > 1) { tr.className = \'\'; } else { tr.className = \'hiddenRow\'; } } } } function showClassDetail(cid, count) { var id_list = Array(count); var toHide = 1; for (var i = 0; i < count; i++) { tid0 = \'t\' + cid.substr(1) + \'.\' + (i+1); tid = \'f\' + tid0; tr = document.getElementById(tid); if (!tr) { tid = \'p\' + tid0; tr = document.getElementById(tid); } id_list[i] = tid; if (tr.className) { toHide = 0; } } for (var i = 0; i < count; i++) { tid = id_list[i]; if (toHide) { document.getElementById(\'div_\'+tid).style.display = \'none\' document.getElementById(tid).className = \'hiddenRow\'; } else { document.getElementById(tid).className = \'\'; } } } function showTestDetail(div_id){ var details_div = document.getElementById(div_id) var displayState = details_div.style.display // alert(displayState) if (displayState != \'block\' ) { displayState = \'block\' details_div.style.display = \'block\' } else { details_div.style.display = \'none\' } } function html_escape(s) { s = s.replace(/&/g,\'&\'); s = s.replace(/</g,\'<\'); s = s.replace(/>/g,\'>\'); return s; } /* obsoleted by detail in <div> function showOutput(id, name) { var w = window.open("", //url name, "resizable,scrollbars,status,width=800,height=450"); d = w.document; d.write("<pre>"); d.write(html_escape(output_list[id])); d.write("\\n"); d.write("<a href=\'javascript:window.close()\'>close</a>\\n"); d.write("</pre>\\n"); d.close(); } */ --></script> %(heading)s %(report)s %(ending)s </body> </html> """ # variables: (title, generator, stylesheet, heading, report, ending) # ------------------------------------------------------------------------ # Stylesheet # # alternatively use a <link> for external style sheet, e.g. # <link rel="stylesheet" href="$url" type="text/css"> STYLESHEET_TMPL = """ <style type="text/css" media="screen"> body { font-family: verdana, arial, helvetica, sans-serif; font-size: 80%; } table { font-size: 100%; } pre { } /* -- heading ---------------------------------------------------------------------- */ h1 { font-size: 16pt; color: gray; } .heading { margin-top: 0ex; margin-bottom: 1ex; } .heading .attribute { margin-top: 1ex; margin-bottom: 0; } .heading .description { margin-top: 4ex; margin-bottom: 6ex; } /* -- css div popup ------------------------------------------------------------------------ */ a.popup_link { } a.popup_link:hover { color: red; } .popup_window { display: none; position: relative; left: 0px; top: 0px; /*border: solid #627173 1px; */ padding: 10px; background-color: #E6E6D6; font-family: "Lucida Console", "Courier New", Courier, monospace; text-align: left; font-size: 8pt; width: 500px; } } /* -- report ------------------------------------------------------------------------ */ #show_detail_line { margin-top: 3ex; margin-bottom: 1ex; } #result_table { width: 80%; border-collapse: collapse; border: 1px solid #777; } #header_row { font-weight: bold; color: white; background-color: #777; } #result_table td { border: 1px solid #777; padding: 2px; } #total_row { font-weight: bold; } .passClass { background-color: #6c6; } .failClass { background-color: #c60; } .errorClass { background-color: #c00; } .passCase { color: #6c6; } .failCase { color: #c60; font-weight: bold; } .errorCase { color: #c00; font-weight: bold; } .hiddenRow { display: none; } .testcase { margin-left: 2em; } /* -- ending ---------------------------------------------------------------------- */ #ending { } </style> """ # ------------------------------------------------------------------------ # Heading # HEADING_TMPL = """<div class=\'heading\'> <h1>%(title)s</h1> %(parameters)s <p class=\'description\'>%(description)s</p> </div> """ # variables: (title, parameters, description) HEADING_ATTRIBUTE_TMPL = """<p class=\'attribute\'><strong>%(name)s:</strong> %(value)s</p> """ # variables: (name, value) # ------------------------------------------------------------------------ # Report # REPORT_TMPL = """ <p id=\'show_detail_line\'>Show <a href=\'javascript:showCase(0)\'>Summary</a> <a href=\'javascript:showCase(1)\'>Failed</a> <a href=\'javascript:showCase(2)\'>All</a> </p> <table id=\'result_table\'> <colgroup> <col align=\'left\' /> <col align=\'right\' /> <col align=\'right\' /> <col align=\'right\' /> <col align=\'right\' /> <col align=\'right\' /> </colgroup> <tr id=\'header_row\'> <td>Test Group/Test case</td> <td>Count</td> <td>Pass</td> <td>Fail</td> <td>Error</td> <td>View</td> </tr> %(test_list)s <tr id=\'total_row\'> <td>Total</td> <td>%(count)s</td> <td>%(Pass)s</td> <td>%(fail)s</td> <td>%(error)s</td> <td> </td> </tr> </table> """ # variables: (test_list, count, Pass, fail, error) REPORT_CLASS_TMPL = r""" <tr class=\'%(style)s\'> <td>%(desc)s</td> <td>%(count)s</td> <td>%(Pass)s</td> <td>%(fail)s</td> <td>%(error)s</td> <td><a href="javascript:showClassDetail(\'%(cid)s\',%(count)s)">Detail</a></td> </tr> """ # variables: (style, desc, count, Pass, fail, error, cid) REPORT_TEST_WITH_OUTPUT_TMPL = r""" <tr id=\'%(tid)s\' class=\'%(Class)s\'> <td class=\'%(style)s\'><div class=\'testcase\'>%(desc)s</div></td> <td colspan=\'5\' align=\'center\'> <!--css div popup start--> <a class="popup_link" onfocus=\'this.blur();\' href="javascript:showTestDetail(\'div_%(tid)s\')" > %(status)s</a> <div id=\'div_%(tid)s\' class="popup_window"> <div style=\'text-align: right; color:red;cursor:pointer\'> <a onfocus=\'this.blur();\' onclick="document.getElementById(\'div_%(tid)s\').style.display = \'none\' " > [x]</a> </div> <pre> %(script)s </pre> </div> <!--css div popup end--> </td> </tr> """ # variables: (tid, Class, style, desc, status) REPORT_TEST_NO_OUTPUT_TMPL = r""" <tr id=\'%(tid)s\' class=\'%(Class)s\'> <td class=\'%(style)s\'><div class=\'testcase\'>%(desc)s</div></td> <td colspan=\'5\' align=\'center\'>%(status)s</td> </tr> """ # variables: (tid, Class, style, desc, status) REPORT_TEST_OUTPUT_TMPL = r""" %(id)s: %(output)s """ # variables: (id, output) # ------------------------------------------------------------------------ # ENDING # ENDING_TMPL = """<div id=\'ending\'> </div>""" # -------------------- The end of the Template class ------------------- TestResult = unittest.TestResult class _TestResult(TestResult): # note: _TestResult is a pure representation of results. # It lacks the output and reporting ability compares to unittest._TextTestResult. def __init__(self, verbosity=1): TestResult.__init__(self) self.stdout0 = None self.stderr0 = None self.success_count = 0 self.failure_count = 0 self.error_count = 0 self.verbosity = verbosity # result is a list of result in 4 tuple # ( # result code (0: success; 1: fail; 2: error), # TestCase object, # Test output (byte string), # stack trace, # ) self.result = [] def startTest(self, test): TestResult.startTest(self, test) # just one buffer for both stdout and stderr self.outputBuffer = io.BytesIO() stdout_redirector.fp = self.outputBuffer stderr_redirector.fp = self.outputBuffer self.stdout0 = sys.stdout self.stderr0 = sys.stderr sys.stdout = stdout_redirector sys.stderr = stderr_redirector def complete_output(self): """ Disconnect output redirection and return buffer. Safe to call multiple times. """ if self.stdout0: sys.stdout = self.stdout0 sys.stderr = self.stderr0 self.stdout0 = None self.stderr0 = None return self.outputBuffer.getvalue() def stopTest(self, test): # Usually one of addSuccess, addError or addFailure would have been called. # But there are some path in unittest that would bypass this. # We must disconnect stdout in stopTest(), which is guaranteed to be called. self.complete_output() def addSuccess(self, test): self.success_count += 1 TestResult.addSuccess(self, test) output = self.complete_output() self.result.append((0, test, output, \'\')) if self.verbosity > 1: sys.stderr.write(\'ok \') sys.stderr.write(str(test)) sys.stderr.write(\'\\n\') else: sys.stderr.write(\'.\') def addError(self, test, err): self.error_count += 1 TestResult.addError(self, test, err) _, _exc_str = self.errors[-1] output = self.complete_output() self.result.append((2, test, output, _exc_str)) if self.verbosity > 1: sys.stderr.write(\'E \') sys.stderr.write(str(test)) sys.stderr.write(\'\\n\') else: sys.stderr.write(\'E\') def addFailure(self, test, err): self.failure_count += 1 TestResult.addFailure(self, test, err) _, _exc_str = self.failures[-1] output = self.complete_output() self.result.append((1, test, output, _exc_str)) if self.verbosity > 1: sys.stderr.write(\'F \') sys.stderr.write(str(test)) sys.stderr.write(\'\\n\') else: sys.stderr.write(\'F\') class HTMLTestRunner(Template_mixin): """ """ def __init__(self, stream=sys.stdout, verbosity=1, title=None, description=None): self.stream = stream self.verbosity = verbosity if title is None: self.title = self.DEFAULT_TITLE else: self.title = title if description is None: self.description = self.DEFAULT_DESCRIPTION else: self.description = description self.startTime = datetime.datetime.now() def run(self, test): "Run the given test case or test suite." result = _TestResult(self.verbosity) test(result) self.stopTime = datetime.datetime.now() self.generateReport(test, result) print(sys.stderr, \'\\nTime Elapsed: %s\' % (self.stopTime-self.startTime)) return result def sortResult(self, result_list): # unittest does not seems to run in any particular order. # Here at least we want to group them together by class. rmap = {} classes = [] for n,t,o,e in result_list: cls = t.__class__ if not cls in rmap: rmap[cls] = [] classes.append(cls) rmap[cls].append((n,t,o,e)) r = [(cls, rmap[cls]) for cls in classes] return r def getReportAttributes(self, result): """ Return report attributes as a list of (name, value). Override this to add custom attributes. """ startTime = str(self.startTime)[:19] duration = str(self.stopTime - self.startTime) status = [] if result.success_count: status.append(\'Pass %s\' % result.success_count) if result.failure_count: status.append(\'Failure %s\' % result.failure_count) if result.error_count: status.append(\'Error %s\' % result.error_count ) if status: status = \' \'.join(status) else: status = \'none\' return [ (\'Start Time\', startTime), (\'Duration\', duration), (\'Status\', status), ] def generateReport(self, test, result): report_attrs = self.getReportAttributes(result) generator = \'HTMLTestRunner %s\' % __version__ stylesheet = self._generate_stylesheet() heading = self._generate_heading(report_attrs) report = self._generate_report(result) ending = self._generate_ending() output = self.HTML_TMPL % dict( title = saxutils.escape(self.title), generator = generator, stylesheet = stylesheet, heading = heading, report = report, ending = ending, ) self.stream.write(output.encode(\'utf8\')) def _generate_stylesheet(self): return self.STYLESHEET_TMPL def _generate_heading(self, report_attrs): a_lines = [] for name, value in report_attrs: line = self.HEADING_ATTRIBUTE_TMPL % dict( name = saxutils.escape(name), value = saxutils.escape(value), ) a_lines.append(line) heading = self.HEADING_TMPL % dict( title = saxutils.escape(self.title), parameters = \'\'.join(a_lines), description = saxutils.escape(self.description), ) return heading def _generate_report(self, result): rows = [] sortedResult = self.sortResult(result.result) for cid, (cls, cls_results) in enumerate(sortedResult): # subtotal for a class np = nf = ne = 0 for n,t,o,e in cls_results: if n == 0: np += 1 elif n == 1: nf += 1 else: ne += 1 # format class description if cls.__module__ == "__main__": name = cls.__name__ else: name = "%s.%s" % (cls.__module__, cls.__name__) doc = cls.__doc__ and cls.__doc__.split("\\n")[0] or "" desc = doc and \'%s: %s\' % (name, doc) or name row = self.REPORT_CLASS_TMPL % dict( style = ne > 0 and \'errorClass\' or nf > 0 and \'failClass\' or \'passClass\', desc = desc, count = np+nf+ne, Pass = np, fail = nf, error = ne, cid = \'c%s\' % (cid+1), ) rows.append(row) for tid, (n,t,o,e) in enumerate(cls_results): self._generate_report_test(rows, cid, tid, n, t, o, e) report = self.REPORT_TMPL % dict( test_list = \'\'.join(rows), count = str(result.success_count+result.failure_count+result.error_count), Pass = str(result.success_count), fail = str(result.failure_count), error = str(result.error_count), ) return report def _generate_report_test(self, rows, cid, tid, n, t, o, e): # e.g. \'pt1.1\', \'ft1.1\', etc has_output = bool(o or e) tid = (n == 0 and \'p\' or \'f\') + \'t%s.%s\' % (cid+1,tid+1) name = t.id().split(\'.\')[-1] doc = t.shortDescription() or "" desc = doc and (\'%s: %s\' % (name, doc)) or name tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL # o and e should be byte string because they are collected from stdout and stderr? if isinstance(o,str): # TODO: some problem with \'string_escape\': it escape \\n and mess up formating # uo = unicode(o.encode(\'string_escape\')) uo = o.decode(\'latin-1\') else: uo = o if isinstance(e,str): # TODO: some problem with \'string_escape\': it escape \\n and mess up formating # ue = unicode(e.encode(\'string_escape\')) ue = e else: ue = e script = self.REPORT_TEST_OUTPUT_TMPL % dict( id = tid, output = saxutils.escape(str(uo)+ue), ) row = tmpl % dict( tid = tid, Class = (n == 0 and \'hiddenRow\' or \'none\'), style = n == 2 and \'errorCase\' or (n == 1 and \'failCase\' or \'none\'), desc = desc, script = script, status = self.STATUS[n], ) rows.append(row) if not has_output: return def _generate_ending(self): return self.ENDING_TMPL ############################################################################## # Facilities for running tests from the command line ############################################################################## # Note: Reuse unittest.TestProgram to launch test. In the future we may # build our own launcher to support more specific command line # parameters like test title, CSS, etc. class TestProgram(unittest.TestProgram): """ A variation of the unittest.TestProgram. Please refer to the base class for command line parameters. """ def runTests(self): # Pick HTMLTestRunner as the default test runner. # base class\'s testRunner parameter is not useful because it means # we have to instantiate HTMLTestRunner before we know self.verbosity. if self.testRunner is None: self.testRunner = HTMLTestRunner(verbosity=self.verbosity) unittest.TestProgram.runTests(self) main = TestProgram ############################################################################## # Executing this module from the command line ############################################################################## if __name__ == "__main__": main(module=None)
五、data操作Excel的读写、日志
handle_excel.py:封装Excel的读写
#!/usr/bin/env python3 # -*-coding:utf-8-*- # __author__: hunter import xlrd from xlutils.copy import copy class HandleExcel: """封装操作Excel的方法""" def __init__(self, file=\'D:/hunter_/interfaceTest/hunter_interface/case/demo2.xlsx\', sheet_id=0): self.file = file self.sheet_id = sheet_id self.data = self.get_data() # 为了创建一个实例时就获得Excel的sheet对象,可以在构造器中调用get_data() # 因为类在实例化时就会自动调用构造器,这样创建一个实例时就会自动获得sheet对象了 # 获取某一页sheet对象 def get_data(self): data = xlrd.open_workbook(self.file) sheet = data.sheet_by_index(self.sheet_id) return sheet # 获取Excel数据行数 def get_rows(self): rows = self.data.nrows return rows # 获取某个单元格写入数据 def get_value(self, row, col): value = self.data.cell_value(row, col) return value # 向某个单元格写入数据 def write_value(self, row, col, value): data = xlrd.open_workbook(self.file) # 打开文件 data_copy = copy(data) # 复制源文件 sheet = data_copy.get_sheet(0) # 取得复制文件的sheet对象 sheet.write(row, col, value) # 在某一单元格写入value以上是关于python_接口自动化测试框架的主要内容,如果未能解决你的问题,请参考以下文章python接口自动化测试 - unittest框架基本使用
《selenium2 python 自动化测试实战》(21)——unittest单元测试框架解析