这里介绍一种方式,实现通用的接口自动化测试用例脚本,自动读取excel接口文档进行接口测试
utils.py源代码:
import xlrd
def parse_intf(file,sheet_index):
with xlrd.open_workbook(file) as f:
table = f.sheet_by_index(sheet_index)
for row in range(0,table.nrows):
if (table.row_values(row)[0]).strip().upper()=='URL':
url = (table.row_values(row)[1]).strip()
elif (table.row_values(row)[0]).strip()=='方法':
method=(table.row_values(row)[1]).strip()
elif (table.row_values(row)[0]).strip()=='传入参数':
params={}
params_str=(table.row_values(row)[1]).strip().split(',')
for param_str in params_str:
key,value=param_str.strip().split('=')
params[key.strip()]=value.strip()
elif (table.row_values(row)[0]).strip()=='返回值':
rv=eval((table.row_values(row)[1]).strip())
elif (table.row_values(row)[0]).strip()=='状态码':
lst=(table.row_values(row)[1]).strip().split(':')
status=int(lst[0].strip()), lst[1].strip()
return url,method,params,rv,status
def send_request(s,method,url,params):
if method.upper()=='GET':
return s.request(method, url, params=params)
elif method.upper()=='POST':
return s.request(method, url, json=params)
test_interface.py源代码
import unittest
import requests
import utils
file='学生信息查询接口.xlsx'
sheet_index=0
class TestGetStu(unittest.TestCase):
def setUp(self):
self.url,self.method,self.params,self.rv,self.status=utils.parse_intf(file,sheet_index)
self.s=requests.Session()
def test_get_stu(self):
r=utils.send_request(self.s,self.method,self.url,self.params)
self.assertEqual(dict(r.json()),self.rv)
self.assertEqual((r.status_code,r.reason),self.status)
def tearDown(self):
self.s.close()
if __name__ == '__main__':
unittest.main()
举例用的学生信息查询接口.xlsx文件内容:
名称 | 查询学生信息 | |
URL | http://127.0.0.1:8080/stu_cou/get_stu/ | |
方法 | GET | |
传入参数 | id=3011205 | id是学生的学号 |
返回值 | {'id':3011205,'name':'Tom', 'birthday':'1982-01-01','province':'Xinjiang'} | |
状态码 | 200: OK |
上面的测试用例脚本test_interface.py具有通用性,同样可以读取其它excel接口文档,进行接口测试。