1.封裝http接口請求
已經實現了一個簡單的接口請求,接下來就要考慮封裝這個請求,在後面的用例中,只需要傳遞參數(URL ,Params,cookie,heade,method 等)每次去調用這個請求類,
然後根據接口的請求類型來調用相應的處理,如果是get方式就調用get方法,如果是post方式就調用post方法,經過這樣的設計後,測試方法中的代碼結構會更加清晰有層次,也更容易維護。
代碼實現:
# 導入requests包
import requests
class HttpRequest:
def http_request(self, url, params, http_method):
res = ''
if http_method.upper()=='POST':
try:
res=requests.post(url,params)
print("正在進行post請求")
except Exception as e:
print("post請求出現了異常:{0}".format(e))
elif http_method.upper()=='GET':
try:
res=requests.post(url,params)
print("正在進行get請求")
except Exception as e:
print("get請求出現了異常:{0}".format(e))
return res
if __name__ == '__main__':
url = 'http://27.154.55.14:8180/api/fcb2bcrm/webRegister'
datas = {'LoginAccount': '[email protected]', 'Password': '123456', 'Type': 'Pro'}
res=HttpRequest().http_request(url, datas, 'post')
print(res.json())
執行結果:
4.TestCase調用封裝好的http請求,並添加異常處理。
在運行用例的時候,發現無論斷言成功與否,測試報告都是全部通過,後面發現是在處理異常的時候,沒有將異常拋出。
以下是test_register.py 修改後的代碼:
# 導入
import unittest
import requests
from Common.http_request import HttpRequest
class TestRegister (unittest.TestCase): # 類必須以Test開頭,繼承TestCase
url = 'http://27.154.55.14:8180/api/fcb2bcrm/webRegister'
def setUp(self):
print("======開始執行測試用例======")
def tearDown(self):
print("======測試用例執行完畢======")
# 測試用例 - 正常註冊
def test_register_normal(self): # 每一條測試用例以test_開頭
# 發送請求
params = {'LoginAccount': '[email protected]', 'Password': '123456', 'Type': 'Pro'}
# res = requests.post(self.url,params)
res = HttpRequest().http_request(self.url,params,'post')
# 斷言:根據實際測試場景,可以查詢數據庫是否有新註冊的用戶、對比接口的返回信息、對比狀態碼等等
try:
self.assertEqual(200, res.status_code)
print('成功測試用戶:{}'.format(params['LoginAccount']))
except AssertionError as e:
print('Failed')
raise e # 注意一定要拋出異常
# 測試用例 - 重複註冊
def test_register_existing(self):
# 發送請求
params = {'LoginAccount': '[email protected]', 'Password': '123456', 'Type': 'Pro'}
# res = requests.post(self.url,params)
res = HttpRequest().http_request(self.url, params, 'post')
# 斷言
try:
self.assertIn("The email has been registered", res.json()['Message'])
print("執行結果:pass:", res.json()['Message'])
except AssertionError as e:
print('執行結果:Failed')
raise e
# 測試用例 - 無效的郵箱格式去註冊
def test_register_invalid_email(self):
# 發送請求
params = {'LoginAccount': 'testapi@emai', 'Password': '123456', 'Type': 'Pro'}
# res = requests.post(self.url,params)
res = HttpRequest().http_request(self.url, params, 'post')
# 斷言
try:
self.assertIn("valid email", res.json()['Message'])
print("執行結果:pass:", res.json()['Message'])
except AssertionError as e:
print('執行結果:Failed')
raise e