1. 程式人生 > >python - requests從excel中獲取測試用例資料

python - requests從excel中獲取測試用例資料

 

 

HttpRequests.py

 1 #-*- coding:utf-8 -*-
 2 
 3 
 4 import requests
 5 class HttpRequests():
 6     def http_requests(self,url,params,http_mothed,cookies=None):
 7         if http_mothed=='get':
 8             res=requests.get(url,params,cookies=cookies)
 9             return
res 10 else: 11 res=requests.post(url,params,cookies=cookies) 12 return res

 

test_HttpRequests.py

 1 #-*- coding:utf-8 -*-
 2 
 3 #存放測試用例
 4 import unittest
 5 from study_181130_request.HttpRequests import HttpRequests
 6 
 7 
 8 COOKIES=None
 9 
10 class TestHttpRequests(unittest.TestCase):
11 12 13 def setUp(self): 14 # self.url='http://47.107.168.87:8080/futureloan/mvc/api/member/login' 15 pass 16 17 def __init__(self,url,params,http_method,excepted,methodName):#初始化傳參;用初始化函式一定要記得去看看父類裡面有沒有初始化函式,如果有,需要超繼承 18 19 self.params=params#請求的資料 20 self.http_method=http_method#
請求方法 21 self.url=url 22 self.excepted=excepted 23 super(TestHttpRequests,self).__init__(methodName)#超繼承 24 25 26 def test_api(self):#登入成功 :手機號正確、密碼正確;用例裡面不可以傳引數 27 global COOKIES#宣告全域性變數 28 res=HttpRequests().http_requests(self.url,self.params,self.http_method,COOKIES) 29 try: 30 self.assertEqual(self.excepted,res.json()['msg']) 31 except AssertionError as e: 32 print('斷言結果是:{}'.format(e)) 33 raise e 34 35 if res.cookies: 36 COOKIES=res.cookies#當res.cookies非空時,修改COOKIES的值

 

test_runner.py

#-*- coding:utf-8 -*-


import unittest
import HTMLTestRunnerNew
from study_181130_request.test_HttpRequests import TestHttpRequests
from study_181130_request.read_excel import TestExcel

test_data=TestExcel().get_TestExcel()

suit=unittest.TestSuite()##裝用例的地方
for item in test_data:
    suit.addTest(TestHttpRequests(item['url'],eval(item['params']),item['http_method'],item['excepted'],'test_api'))#建立例項的方法來新增用

#執行用例
with open('test_api.html','bw+') as file:
    Runner=HTMLTestRunnerNew.HTMLTestRunner(stream=file,verbosity=2,
                                            title='HTTP請求作業-單元測試報告',description='測試一下HTTP請求',tester='huimin'
                                            )
    Runner.run(suit)

 

read_excel.py

#-*- coding:utf-8 -*-

from openpyxl import load_workbook


class TestExcel():

    def get_TestExcel(self):
        workbook = load_workbook('http_requests.xlsx')#開啟表
        sheet = workbook['Sheet1']#定位表單

        test_data = []#把所有行的資料放到列表中

        for i in range(2,sheet.max_row+1):
            sub_data = {}#把每行的資料放到字典中
            for j in range(1,sheet.max_column+1):

                sub_data[sheet.cell(1,j).value] = sheet.cell(i,j).value

            test_data.append(sub_data)#拼接每行單元格的資料

        return test_data

 

測試報告: