前言

1.环境准备:

  • python3.6
  • requests
  • xlrd
  • openpyxl
  • HTMLTestRunner_api

2.目前实现的功能:

  • 封装requests请求方法
  • 在excel填写接口请求参数
  • 运行完后,重新生成一个excel报告,结果写入excel
  • 用unittest+ddt数据驱动模式执行
  • HTMLTestRunner生成可视化的html报告
  • 对于没有关联的单个接口请求是可以批量执行的,需要登录的话写到setUpclass里的session里保持cookies
  • token关联的不能实现
  • logging日志文件暂时未加入

3.目前已知的缺陷:

  • 无法实现参数关联:上个请求的结果是下个请求的参数,如token
  • 接口请求参数名有重复的,目前未处理,如key1=value1&key1=value2,两个key都一样,这种需要用元组存储,目前暂时未判断
  • 生成的excel样式未处理,后期慢慢优化样式
  • python新手可能遇到模块导入报错问题
  • 局限性太多,所以已经弃用!!谨慎入坑,换pytest框架了

项目结构

excel测试数据

xlrd读excel数据

1.先从excel里面读取测试数据,返回字典格式

  1. # coding:utf-8
  2. # 作者:上海-悠悠
  3. # QQ群:226296743
  4. import xlrd
  5. class ExcelUtil():
  6. def __init__(self, excelPath, sheetName="Sheet1"):
  7. self.data = xlrd.open_workbook(excelPath)
  8. self.table = self.data.sheet_by_name(sheetName)
  9. # 获取第一行作为key值
  10. self.keys = self.table.row_values(0)
  11. # 获取总行数
  12. self.rowNum = self.table.nrows
  13. # 获取总列数
  14. self.colNum = self.table.ncols
  15. def dict_data(self):
  16. if self.rowNum <= 1:
  17. print("总行数小于1")
  18. else:
  19. r = []
  20. j = 1
  21. for i in list(range(self.rowNum-1)):
  22. s = {}
  23. # 从第二行取对应values值
  24. s['rowNum'] = i+2
  25. values = self.table.row_values(j)
  26. for x in list(range(self.colNum)):
  27. s[self.keys[x]] = values[x]
  28. r.append(s)
  29. j += 1
  30. return r
  31. if __name__ == "__main__":
  32. filepath = "debug_api.xlsx"
  33. sheetName = "Sheet1"
  34. data = ExcelUtil(filepath, sheetName)
  35. print(data.dict_data())

openpyxl写入数据

1.再封装一个写入excel数据的方法

  1. # coding:utf-8
  2. from openpyxl import load_workbook
  3. import openpyxl
  4. # 作者:上海-悠悠
  5. # QQ群:226296743
  6. def copy_excel(excelpath1, excelpath2):
  7. '''复制excek,把excelpath1数据复制到excelpath2'''
  8. wb2 = openpyxl.Workbook()
  9. wb2.save(excelpath2)
  10. # 读取数据
  11. wb1 = openpyxl.load_workbook(excelpath1)
  12. wb2 = openpyxl.load_workbook(excelpath2)
  13. sheets1 = wb1.sheetnames
  14. sheets2 = wb2.sheetnames
  15. sheet1 = wb1[sheets1[0]]
  16. sheet2 = wb2[sheets2[0]]
  17. max_row = sheet1.max_row # 最大行数
  18. max_column = sheet1.max_column # 最大列数
  19. for m in list(range(1,max_row+1)):
  20. for n in list(range(97,97+max_column)): # chr(97)='a'
  21. n = chr(n) # ASCII字符
  22. i ='%s%d'% (n, m) # 单元格编号
  23. cell1 = sheet1[i].value # 获取data单元格数据
  24. sheet2[i].value = cell1 # 赋值到test单元格
  25. wb2.save(excelpath2) # 保存数据
  26. wb1.close() # 关闭excel
  27. wb2.close()
  28. class Write_excel(object):
  29. '''修改excel数据'''
  30. def __init__(self, filename):
  31. self.filename = filename
  32. self.wb = load_workbook(self.filename)
  33. self.ws = self.wb.active # 激活sheet
  34. def write(self, row_n, col_n, value):
  35. '''写入数据,如(2,3,"hello"),第二行第三列写入数据"hello"'''
  36. self.ws.cell(row_n, col_n).value = value
  37. self.wb.save(self.filename)
  38. if __name__ == "__main__":
  39. copy_excel("debug_api.xlsx", "testreport.xlsx")
  40. wt = Write_excel("testreport.xlsx")
  41. wt.write(4, 5, "HELLEOP")
  42. wt.write(4, 6, "HELLEOP")

封装request请求方法

1.把从excel读处理的数据作为请求参数,封装requests请求方法,传入请求参数,并返回结果

2.为了不污染测试的数据,出报告的时候先将测试的excel复制都应该新的excel

3.把测试返回的结果,在新的excel里面写入数据

  1. # coding:utf-8
  2. import json
  3. import requests
  4. from excelddtdriver.common.readexcel import ExcelUtil
  5. from excelddtdriver.common.writeexcel import copy_excel, Write_excel
  6. # 作者:上海-悠悠
  7. # QQ群:226296743
  8. def send_requests(s, testdata):
  9. '''封装requests请求'''
  10. method = testdata["method"]
  11. url = testdata["url"]
  12. # url后面的params参数
  13. try:
  14. params = eval(testdata["params"])
  15. except:
  16. params = None
  17. # 请求头部headers
  18. try:
  19. headers = eval(testdata["headers"])
  20. print("请求头部:%s" % headers)
  21. except:
  22. headers = None
  23. # post请求body类型
  24. type = testdata["type"]
  25. test_nub = testdata['id']
  26. print("*******正在执行用例:----- %s ----**********" % test_nub)
  27. print("请求方式:%s, 请求url:%s" % (method, url))
  28. print("请求params:%s" % params)
  29. # post请求body内容
  30. try:
  31. bodydata = eval(testdata["body"])
  32. except:
  33. bodydata = {}
  34. # 判断传data数据还是json
  35. if type == "data":
  36. body = bodydata
  37. elif type == "json":
  38. body = json.dumps(bodydata)
  39. else:
  40. body = bodydata
  41. if method == "post": print("post请求body类型为:%s ,body内容为:%s" % (type, body))
  42. verify = False
  43. res = {} # 接受返回数据
  44. try:
  45. r = s.request(method=method,
  46. url=url,
  47. params=params,
  48. headers=headers,
  49. data=body,
  50. verify=verify
  51. )
  52. print("页面返回信息:%s" % r.content.decode("utf-8"))
  53. res['id'] = testdata['id']
  54. res['rowNum'] = testdata['rowNum']
  55. res["statuscode"] = str(r.status_code) # 状态码转成str
  56. res["text"] = r.content.decode("utf-8")
  57. res["times"] = str(r.elapsed.total_seconds()) # 接口请求时间转str
  58. if res["statuscode"] != "200":
  59. res["error"] = res["text"]
  60. else:
  61. res["error"] = ""
  62. res["msg"] = ""
  63. if testdata["checkpoint"] in res["text"]:
  64. res["result"] = "pass"
  65. print("用例测试结果: %s---->%s" % (test_nub, res["result"]))
  66. else:
  67. res["result"] = "fail"
  68. return res
  69. except Exception as msg:
  70. res["msg"] = str(msg)
  71. return res
  72. def wirte_result(result, filename="result.xlsx"):
  73. # 返回结果的行数row_nub
  74. row_nub = result['rowNum']
  75. # 写入statuscode
  76. wt = Write_excel(filename)
  77. wt.write(row_nub, 8, result['statuscode']) # 写入返回状态码statuscode,第8列
  78. wt.write(row_nub, 9, result['times']) # 耗时
  79. wt.write(row_nub, 10, result['error']) # 状态码非200时的返回信息
  80. wt.write(row_nub, 12, result['result']) # 测试结果 pass 还是fail
  81. wt.write(row_nub, 13, result['msg']) # 抛异常
  82. if __name__ == "__main__":
  83. data = ExcelUtil("debug_api.xlsx").dict_data()
  84. print(data[0])
  85. s = requests.session()
  86. res = send_requests(s, data[0])
  87. copy_excel("debug_api.xlsx", "result.xlsx")
  88. wirte_result(res, filename="result.xlsx")

测试用例unittest+ddt

1.测试用例用unittest框架组建,并用ddt数据驱动模式,批量执行用例

  1. # coding:utf-8
  2. import unittest
  3. import ddt
  4. import os
  5. import requests
  6. from excelddtdriver.common import base_api
  7. from excelddtdriver.common import readexcel
  8. from excelddtdriver.common import writeexcel
  9. # 作者:上海-悠悠
  10. # QQ群:226296743
  11. # 获取demo_api.xlsx路径
  12. curpath = os.path.dirname(os.path.realpath(__file__))
  13. testxlsx = os.path.join(curpath, "demo_api.xlsx")
  14. # 复制demo_api.xlsx文件到report下
  15. report_path = os.path.join(os.path.dirname(curpath), "report")
  16. reportxlsx = os.path.join(report_path, "result.xlsx")
  17. testdata = readexcel.ExcelUtil(testxlsx).dict_data()
  18. @ddt.ddt
  19. class Test_api(unittest.TestCase):
  20. @classmethod
  21. def setUpClass(cls):
  22. cls.s = requests.session()
  23. # 如果有登录的话,就在这里先登录了
  24. writeexcel.copy_excel(testxlsx, reportxlsx) # 复制xlsx
  25. @ddt.data(*testdata)
  26. def test_api(self, data):
  27. # 先复制excel数据到report
  28. res = base_api.send_requests(self.s, data)
  29. base_api.wirte_result(res, filename=reportxlsx)
  30. # 检查点 checkpoint
  31. check = data["checkpoint"]
  32. print("检查点->:%s"%check)
  33. # 返回结果
  34. res_text = res["text"]
  35. print("返回实际结果->:%s"%res_text)
  36. # 断言
  37. self.assertTrue(check in res_text)
  38. if __name__ == "__main__":
  39. unittest.main()

生成报告

1.用HTMLTestRunner生成html报告,我这里改了下名称,改成了HTMLTestRunner_api.py

  1. # coding=utf-8
  2. import unittest
  3. import time
  4. from excelddtdriver.common import HTMLTestRunner_api
  5. import os
  6. # 作者:上海-悠悠
  7. # QQ群:226296743
  8. curpath = os.path.dirname(os.path.realpath(__file__))
  9. report_path = os.path.join(curpath, "report")
  10. if not os.path.exists(report_path): os.mkdir(report_path)
  11. case_path = os.path.join(curpath, "case")
  12. def add_case(casepath=case_path, rule="test*.py"):
  13. '''加载所有的测试用例'''
  14. # 定义discover方法的参数
  15. discover = unittest.defaultTestLoader.discover(casepath,
  16. pattern=rule,)
  17. return discover
  18. def run_case(all_case, reportpath=report_path):
  19. '''执行所有的用例, 并把结果写入测试报告'''
  20. htmlreport = reportpath+r"\result.html"
  21. print("测试报告生成地址:%s"% htmlreport)
  22. fp = open(htmlreport, "wb")
  23. runner = HTMLTestRunner_api.HTMLTestRunner(stream=fp,
  24. verbosity=2,
  25. title="测试报告",
  26. description="用例执行情况")
  27. # 调用add_case函数返回值
  28. runner.run(all_case)
  29. fp.close()
  30. if __name__ == "__main__":
  31. cases = add_case()
  32. run_case(cases)

2.生成的excel报告

3.生成的html报告

---------------------------------python接口自动化已出书-------------------------

买了此书的小伙伴可以在书的最后一篇下载到源码

全书购买地址 https://yuedu.baidu.com/ebook/585ab168302b3169a45177232f60ddccda38e695



---------------------------------python接口自动化完整版-------------------------

全书购买地址 https://yuedu.baidu.com/ebook/585ab168302b3169a45177232f60ddccda38e695

作者:上海-悠悠 QQ交流群:588402570

也可以关注下我的个人公众号:yoyoketang

python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(已弃用)的更多相关文章

  1. python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(二)

    可以参考 python+requests接口自动化完整项目设计源码(一)https://www.cnblogs.com/111testing/p/9612671.html 原文地址https://ww ...

  2. python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告

    1.环境准备: python3.6 requests xlrd openpyxl HTMLTestRunner_api 2.目前实现的功能: 封装requests请求方法 在excel填写接口请求参数 ...

  3. Python+Selenium+Unittest+Ddt+HTMLReport分布式数据驱动自动化测试框架结构

    1.Business:公共业务模块,如登录模块,可以把登录模块进行封装供调用 ------login_business.py from Page_Object.Common_Page.login_pa ...

  4. Python+Pytest+Allure+Git+Jenkins接口自动化框架

    Python+Pytest+Allure+Git+Jenkins接口自动化框架 一.接口基础 接口测试是对系统和组件之间的接口进行测试,主要是效验数据的交换,传递和控制管理过程,以及相互逻辑依赖关系. ...

  5. Python——Requests库的开发者接口

    本文介绍 Python Requests 库的开发者接口,主要内容包括: 目录 一.主要接口 1. requests.request() 2. requests.head().get().post() ...

  6. python+ddt+unittest+excel+request实现接口自动化

    接口自动化测试流程:需求分析-用例设计--脚本开发--测试执行--结果分析1.获取接口文档,根据文档获取请求方式,传输协议,请求参数,响应参数,判断测试是否通过设计用例2.脚本开发:使用request ...

  7. python+requests+excel 接口自动化框架

    一.项目框架如图: 1.common :这个包都是一些公共的方法,如:手机号加解密,get/post接口请求的方法封装,接口鉴权,发邮件,读写excel文件方法等等 2.result:存放每次运行的l ...

  8. Python接口自动化测试框架: pytest+allure+jsonpath+requests+excel实现的接口自动化测试框架(学习成果)

    废话 最近在自己学习接口自动化测试,这里也算是完成一个小的成果,欢迎大家交流指出不合适的地方,源码在文末 问题 整体代码结构优化未实现,导致最终测试时间变长,其他工具单接口测试只需要39ms,该框架中 ...

  9. Python+requests+excel接口测试

    2018-06-14   17:00:13 环境准备: - Python 3.7 - requests库 - xlrd 1.创建Excel文件 2.读取Excel文件 import xlrd clas ...

随机推荐

  1. 最稳定万能vip视频解析接口 支持HTTPS

    最稳定万能vip视频解析接口 支持HTTPS https://cdn.yangju.vip/k/?url=后面加上播放的地址即可 https://cdn.yangju.vip/k/?url= http ...

  2. RequestUtil 获取网址页面信息

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.i ...

  3. [LeetCode] 341. Flatten Nested List Iterator 压平嵌套链表迭代器

    Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...

  4. [LeetCode] 452. Minimum Number of Arrows to Burst Balloons 最少箭数爆气球

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  5. [LeetCode] 602. Friend Requests II: Who Has Most Friend? 朋友请求 II: 谁有最多的朋友?

    In social network like Facebook or Twitter, people send friend requests and accept others' requests ...

  6. Harbor的安装和基本使用

    Harbor是一个开源的云原生registry工程.Harbor对开源的Docker Distribution扩进行了扩展,支持registries之间镜像的复制功能,而且还提供了一些高级的安全方面的 ...

  7. android基础---->SharedPreferences的使用

    SharedPreferences 还支持多种不同的数据类型存储,如果存储的数据类型是整型,那么读取出来的数据也是整型的,存储的数据是一个字符串,读取出来的数据仍然是字符串.这样你应该就能明显地感觉到 ...

  8. SecureCRT字体、界面优化

    SecureCRT字体.界面优化 本文是secureCRT的第三篇博文,也是目前secureCRT优化的最终篇.首次使用该软件时候.应该会设置字体和编码,接下来,将演示如何设置. 1. 字体.编码设置 ...

  9. LeetCode 75. 颜色分类(Sort Colors) 30

    75. 颜色分类 75. Sort Colors 题目描述 给定一个包含红色.白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色.白色.蓝色顺序排列. 此题中, ...

  10. (三)linux 学习 --操作文件和目录

    The Linux Command Line 读书笔记 - 部分内容来自 http://billie66.github.io/TLCL/book/chap05.html 文章目录 通配符 字符范围 ` ...