1. 程式人生 > >Python+Requests+Unittest+Excel 介面自動化測試框架之Request模組01

Python+Requests+Unittest+Excel 介面自動化測試框架之Request模組01

1.Requests模組  a.Request模組是Python中可以實現模擬Http協議的模組  b.安裝方式很多,可以用pip install requests

2.舉例 import requests class Http_Request:     #定義一個請求函式,傳入url,method,param引數     def http_request(self,url,method,param):         #對method進行判斷並斷言,method.upper()對method進行大寫處理判斷值         if method.upper()=='GET':             try:             #如果是GET,則呼叫requests的get方法,傳入url,param                 res=requests.get(url,param)             except Exception as e:                 print('get請求出錯了,錯誤是{0}'.format(e))         elif method.upper()=='POST':             try:            #如果是post,則呼叫requests的post方法,傳入url,param                 res=requests.post(url,json=param)             except Exception as e :                 print('Post請求出錯了,錯誤是{0}'.format(e))         else:         #method的值不是get和post             print('輸入的method不能被識別')

        #返回請求的結果         return res

#if __name__=='__main__':後面的程式碼只會在執行該檔案時執行,被呼叫的時候不會執行,相當於自己的測試資料

if __name__=='__main__':     url='http://127.0.0.1:7000/api/XXXXX'  #請求的URL     testdata={"RoleBaseInfo":{"ASIName":"","RoleName":"Role1","Remark":"Role1"},"PrivilegeList":[]}  #請求引數 Json或是字串格式

    res=Http_Request().http_request(url,'post',testdata)     print(res.json())   #列印返回的結果,json格式

    print(res.text)   #列印返回結果 text格式