setUp是用例運行的前置條件,每次在運行用例的時候,都會優先運行setUp函數,我們可以運用setUp的這一特性,來解決數據依賴問題。
如下圖:

將登錄的請求放到了setUp函數里面,每次運行前都會發起登錄請求。然后再將需要用到的cookie當做參數傳遞到了下一個請求中。從而解決了數據依賴問題。

參考代碼如下:
from API_AUTO.tools.http_request import HttpRequest
import unittest
import re
class TestJenkins(unittest.TestCase):
def setUp(self):
'''登錄請求'''
self.url = 'https://www.ketangpai.com/UserApi/login'
self.data = {
"email": "1489088761@qq.com",
"password": "A1789788",
"remember": 0
}
self.headers = {
"User-Agent": " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded",
}
self.login_res = HttpRequest().http_request('post', self.url, self.data, self.headers, verify=False)
def test_mooc(self):
'''我的精品頁面'''
print(self.login_res.text)
url1 = 'https://www.ketangpai.com/Mooc/Mooc/index.html'
headers1 = {
"Referer": "https: // www.ketangpai.com / Main / index.html",
"User-Agent": " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
}
res1 = HttpRequest().http_request('get', url=url1, headers=headers1, cookies=self.login_res.cookies,
verify=False)
try:
pattern = '<img class=.*?\salt=(".*?").*?>'
regular = re.search(pattern, res1.text, re.S)
self.assertEqual('夏茂傑', eval(regular.group(1)), '進入我的界面失敗')
except Exception as e:
print('錯誤是{}'.format(e))
raise e
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
