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()