pip install requests
pip install xlrd
pip install json
pip install unittesthtml
import requests #導入requests模塊 class Base(): def method_post(self,url,params = None,data = None,headers = None,files = None): return requests.post(url = url,params = params,data = data,headers = headers,files = files) def method_get(self,url,params = None,data = None,headers = None,files = None): return requests.get(url = url,params = params,data = data,headers = headers,files = files) def method_put(self,url,params = None,data = None,headers = None,files = None): return requests.put(url = url,params = params,data = data,headers = headers,files = files) def method_delete(self,url,params = None,data = None,headers = None,files = None): return requests.delete(url = url,params = params,data = data,headers = headers,files = files)
由於每個請求都會有params參數或是data參數,可是不可能兩個都存在,因此這裏用了None,依次類推python
def requests_type(self,method,url,params = None,data = None,headers = None,files = None): if method =='post' or method =='POST': return self.method_post(url = url,params = params,data = data,headers = headers,files = files) elif method =='get' or method =='GET': return self.method_get(url = url,params = params,data = data,headers = headers,files = files) elif method =='put' or method =='PUT': return requests.put(url = url,params = params,data = data,headers = headers,files = files) elif method =='delete' or method =='DELETE': return requests.delete(url = url,params = params,data = data,headers = headers,files = files)
也能夠對須要拿到cookie的接口進行封裝方法保存:面試
def Get_Login_cookie(self,data): res = self.method_post(url = "請求網址",data = data) return {"userId":str(res.json()['result']['userId']),"sessionId":res.json()['result']['sessionId']}
以後咱們要將base頁驗證的這些代碼作清除,不然的話永遠都是調的這些接口json
這裏我添加了一個data包,用於存放xlrd表,以及html報告存放路徑、log日誌存放路徑api
log_path = r'D:\PycharmProjects\自動化接口\自動化接口測試\report\logs' report_html = r'D:\PycharmProjects\自動化接口\自動化接口測試\report\html' read_xlrd = r'D:\PycharmProjects\自動化接口\自動化接口測試\data' class Common(): #封裝日誌方法 def get_logs(self,path = log_path): import logging,time logs = logging.getLogger() logs.setLevel(logging.DEBUG) path = path+'/' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.log' write_file = logging.FileHandler(path,'a+',encoding='utf-8') write_file.setLevel(logging.DEBUG) set_logs = logging.Formatter('%(asctime)s - %(filename)s - %(funcName)s - %(levelname)s - %(message)s') write_file.setFormatter(set_logs) pycharm_text = logging.StreamHandler() pycharm_text.setFormatter(set_logs) logs.addHandler(write_file) logs.addHandler(pycharm_text) return logs
# 讀取Excel表方法,方便後續讀取接口用例數據 def ReadExcelTypeDict(self,file_name,path = read_xlrd): path = path+'/' + file_name import xlrd work_book = xlrd.open_workbook(path) # 打開Excel表 sheets = work_book.sheet_names() # 獲取全部的sheets頁 DatasList = [] for sheet in sheets: sheets = work_book.sheet_by_name(sheet) nrows = sheets.nrows for i in range(0,nrows): values = sheets.row_values(i) DatasList.append(values) title_list = DatasList[0] content_list = DatasList[1:] new_list = [] for content in content_list: dic = {} for i in range(len(content)): dic[title_list[i]] = content[i] new_list.append(dic) return new_list #最終返回爲字典形式 有鍵和值
爲何要轉換格式呢?
這裏就涉及到了怎麼設計一個自動化接口用例瀏覽器
用例的參數值要用json格式寫入,不要有空格
預期結果的出參也要用json格式寫入
不要有' '值都要用" "包起來cookie
# 封裝一個HTML報告方法 def GetHtmlResult(self,suite,title,path = report_html): import HTMLTestReportCN,time path = path + '/' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.html' with open(path,'wb+') as f: run = HTMLTestReportCN.HTMLTestRunner(stream=f,description='用戶相關接口測試報告',tester='小白',title = title) run.run(suite)
其他還有須要補充的能夠繼續添加,我這裏三個基本夠用session
import unittest import ddt import 自動化接口測試.common.commons as common from 自動化接口測試.base.Base_Page import Base
import unittest import ddt import 自動化接口測試.common.commons as common from 自動化接口測試.base.Base_Page import Base r = common.Common().ReadExcelTypeDict('cezxhi .xlsx') # 拿到具體的Excel表數據 @ddt.ddt #導入ddt模塊 class TestLogin(unittest.TestCase): @classmethod def setUpClass(cls) -> None: # setupclass類方法 所有用例開始前執行一次 cls.logs = common.Common().get_logs() # 導入日誌方法 cls.logs.debug('開始寫入接口自動化測試用例') @classmethod def tearDownClass(cls) -> None: cls.logs.debug('自動化接口用例結束') def setUp(self) -> None: self.logs.debug('開始本條接口用例') def tearDown(self) -> None: self.logs.debug('結束本條用例') @ddt.data(*r) # 引入ddt模塊,讀取拿到的數據 def test_logins(self,pars): # 用例方法名開頭必須已test pars參數爲接收的表數據值 import json #導入json模塊 dic = json.loads(pars['body參數值']) # 將Excel數據中的參數值轉變爲json格式 url = pars['接口地址'] # 拿到請求url yuqi = pars['預期結果'] # 拿到預期結果 fs = pars['請求方式'] # 拿到請求方式 result = Base().requests_type(method = fs,url = url,data = dic) # 填充base頁的請求api self.assertEqual(result.text,yuqi) # 進行斷言 看用例是否經過
if __name__ == '__main__': load = unittest.TestLoader().loadTestsFromTestCase(TestLogin) #使用loader加載方式 來找尋全部已test開頭的用例 suite = unittest.TestSuite([load,]) common.Common().GetHtmlResult(suite,'登陸測試用例')
若是對軟件測試、接口測試、自動化測試、面試經驗交流。感興趣能夠加軟件測試交流:1085991341,還會有同行一塊兒技術交流。app
最後咱們run一下框架
控制檯是這樣的
爲何會有400呢?由於有一些接口是異常的,好比url錯誤的,少傳入參數、空參,因此會出錯,常理之中
在pycharm中是這樣的
而後咱們copy下他的路徑到瀏覽器中查看
根據我追蹤的信息,第一條失敗是由於sessionId是能夠變的,每一次的值都是不同,在這裏也但願你們可以找到BUG,並妥善處理好每個問題。
以上內容但願對你有幫助,有被幫助到的朋友歡迎點贊,評論。