Today in the use of global variables to solve the global problem of data dependencies, we notice a huge hole. Executive order unittest framework, the order unittest script is loaded by default: Load ASCII codes according to the order, the order of numbers and letters are: 0-9, AZ, az. Therefore, in the beginning of the test method A will be preferentially executed, after a beginning to be performed.
I do not know in front of this rule, resulting in being given as follows:
AttributeError: 'NoneType' object has no attribute 'group'
For this reason error is generated, the second use case I need to use the login cookie, use the results of the second example was performed first, leading to pass the cookie is empty. Last Solution: adjust the operating sequence, a change of use-case name, so landing the first implementation use cases.
The second embodiment with the first run of FIG facie, cookie so printed is empty:
There can be seen at FIG. Code:
We define a global variable, COOKIE = None, then login cookies were a replacement operation. I.e. COOKIE = login_res.cookies. Then the next time a use case, get my fine pages of information, the cookies = COOKIE http request is transmitted to the inside. Thus solving the problem depends on a request to return a value to the request.
All code is as follows:
import unittest from API_AUTO.tools.http_request import HttpRequest import re COOKIE = None class TestHttp(unittest.TestCase): def setUp(self): pass # abcdefghijklmnopqrstuvwxyz def test_Normal_login(self): '''正常登录''' global COOKIE url = 'https://www.ketangpai.com/UserApi/login' data = { "email": "[email protected]", "password": "A156829", "remember": 0 } 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", } login_res = HttpRequest().http_request('post', url, data, headers) if login_res.cookies: COOKIE = login_res.cookies print(COOKIE) try: self.assertEqual(1, login_res.json()['status'], '登录失败') except AssertionError as e: print('登录错误{}'.format(e)) raise e def test_mooc(self): '''我的精品页面''' global COOKIE # print(COOKIE) 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", } print(COOKIE) res1 = HttpRequest().http_request('get', url=url1, headers=headers1, cookies=COOKIE) 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()