一、問題原因
使用unittest框架進行接口自動化測試:
多個接口聯調測試時,會出現這樣的情況,前面的接口返回值,需要后面接口的參數進行測試。
比如
1、登錄之后修改用戶信息,修改用戶信息接口,需要登錄接口的session,傳到post請求中。
2、通過提交密保問題及答案,修改密碼時,修改密碼接口,需要提交密保問題及接口的token值作為參數傳遞到用戶信息中。修改密碼這個接口的一個參數,就是交密保問題及接口的返回值token。
出現這兩種情況應該怎樣處理傳遞這個參數呢?
二、問題解決
(1)方法一:如果在面向對象方法中:
可以將前一個接口數據作為一個返回值傳遞出來,再用變量接收這個返回值,進行傳遞
response = requests.post(url,data = user_info1).text print(response) #獲取響應的token值,利用loads方法轉換為dict(),對這個dict用key取值 response_dict = json.loads(response) forget_token = response_dict['data'] return forget_token
(2)方法二:如果是在獨立接口測試中。
可以將前一個接口,放在初始化方法setup()中,用self.xxx接收這個值,這樣這個參數就作為類屬性,后面用例接收這個self.xxx,AAA = self.xxx即可
def setUp(self): url = "http://localhost:8080//forget_axxxr.do" uerinfo = {'username': '小肥','question':'你今天吃了沒','answer':'沒胃口吃'} response = requests.post(url,data = uerinfo).text #這個請求對象,調用post方法傳入參數 print(response) response_dict = json.loads(response) self.get_token = response_dict['data'] def test_case2(self): url1 = "http://localhost:8080//forgetxxxx.do" Forget_token = self.get_token uerinfo1 = {'username': 小肥','passwordNew':'666666','forgetToken':Forget_token} response1 = requests.post(url1,data = uerinfo1).text #這個請求對象,調用post方法傳入參數 print(response1)
(3)方法三:如果是多個接口聯調, 不同用例是獨立的。
需要設置一個全局變量,這樣所有的case就可以共享這個變量
在類的最前面定義這個變量
#定義token的全局變量 global Token 12 接收這個變量token #接收這個token值 globals ()['Token'] = response_dict['data']