在進行接口自動化測試時,有好多接口都基於登陸接口的響應值來關聯進行操作的,在次之前試了很多方法,都沒有成功,其實很簡單用session來做。
1、在登陸接口創建一個全局session
1 # -*- coding: utf-8 -*- 2 import requests 3 '''在登陸模塊創建一個全局session,在其他接口操作時帶入登陸時的session,保持session的一致性''' 4 s = requests.Session()#定義一個全局session 5 class testlogin(): 6 login_url = "http://api-xxxxxx/api/Account/Login" 7 username = "xxxxx" 8 password = xxxxx 9 def test_login(self): 10 data ={ 11 "UserName" : self.username, 12 "Password" : self.password 13 } 14 r = s.post(self.login_url,data) 15 print(r.cookies) 16 return s
2、在其他接口調用登陸的session,用這個session.post()去訪問其他接口
1 from test_case.loggin import testlogin 2 import unittest 3 4 '''這里導入之前的登陸模塊,調用登陸模塊的session,然后去執行其他接口''' 5 s = testlogin().test_login() 6 7 class testtransfer(unittest.TestCase): 8 def setUp(self): 9 self.transfer_url = "http://xxxxxxx/Transfer/DoTransferToGame" 10 def test_transfer(self): 11 url = self.transfer_url 12 data ={"Amount":xx, 13 "GamePlatform":"xxxx" 14 } 15 r = s.post(url,data) 16 17 print(r.text) 18 if __name__ == "__main__": 19 unittest.main()