平时工做中开发在作自测或先后端联调测试时会使用一些工具来进行,如postman,jmeter等。
但工具都是有自身局限的,今天小编就以数据驱动的框架思惟来手工编码进行接口自动化测试(基于python requests模块)。python
设计思路:
一、 先设计好要测试数据,包括请求体里的 url,method,headers,params,body_data 等数据。数据库
二、 测试数据放哪里?放文件,放excel,仍是放数据库里,能够根据不一样的业务需求来进行设计,我这里以excel表格为例进行说明。json
三、怎么对测试数据进行读取和写入,达到测试接口的目标,要么只是须要有预期结果和测试结果,须要进行编写代码来完成。后端
测试数据设计以下:session
host: 访问的ip地址或域名
url: 接口的url地址
method: http接口的访问方法,get仍是post,或是put等
headers: 接口的header信息框架
params: 接口的参数信息
data_tpye: 接口body的数据类型,是data仍是json
body_data: 接口的body数据
assert: 断言
test result: 测试结果ide
核心代码以下:工具
一、读取excel文件,获取行数和table。post
#!/usr/bin/env python
#-- coding: utf-8 -测试
import xlrd
def ReadExcel(fileName,SheetName="Sheet1"):
data = xlrd.open_workbook(fileName)
table = data.sheet_by_name(SheetName)
nrows = table.nrows
return nrows,table
二、 封装 http 请求,根据http请求的返回值与断言进行对比,向excel表中test result字段回写测试结果
#!/usr/bin/env python
#-- coding: utf-8 -
import requests
import json
import os.path
import xlrd
from xlutils.copy import copy
from comm.ReadExcel import ReadExcel
def SendRequests():
s = requests.session()
report_path = os.path.abspath(os.path.join(os.getcwd(), ".."))
fileName = report_path + '\testdata' + '\testdata.xls'
for i in range(1, ReadExcel(fileName)[0]): host = ReadExcel(fileName)[1].row_values(i)[2] url = ReadExcel(fileName)[1].row_values(i)[3] method = ReadExcel(fileName)[1].row_values(i)[4] headers = ReadExcel(fileName)[1].row_values(i)[5] params = ReadExcel(fileName)[1].row_values(i)[6] data_type = ReadExcel(fileName)[1].row_values(i)[7] body_data = ReadExcel(fileName)[1].row_values(i)[8] ex_assert = ReadExcel(fileName)[1].row_values(i)[9] testresult = ReadExcel(fileName)[1].row_values(i)[10] p_ex_assert = eval(ex_assert) try: if headers == "": h_headers = None else: h_headers = eval(headers) if params == "": p_params = None else: p_params = params if body_data == "": b_body_data = None else: b_body_data = eval(body_data) if data_type == "": data_type = None elif data_type == "json" : body = json.dumps(b_body_data) elif data_type == "data": body = b_body_data else: body = b_body_data re = s.request(method=method, url=host + url, headers=h_headers,params=p_params,data=body,verify=False) if p_ex_assert['success'] == str(re.json()['success']): workbook = xlrd.open_workbook(fileName) new_workbook = copy(workbook) new_worksheet = new_workbook.get_sheet(0) new_worksheet.write(i, 10, 'pass') new_workbook.save(fileName) print("pass") else: workbook = xlrd.open_workbook(fileName) new_workbook = copy(workbook) new_worksheet = new_workbook.get_sheet(0) new_worksheet.write(i, 10, 'fail') new_workbook.save(fileName) print("fail") except Exception as e: print(e)
三、运行脚本
if name == "main":
SendRequests()