這裏介紹一種方式,實現通用的接口自動化測試用例腳本,自動讀取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接口文檔,進行接口測試。