Python模拟对承载令牌的请求?

2024-09-28 01:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图弄清楚如何在python中模拟我对承载令牌的请求。 我有一门课:

class grab_apitokens(object):

    def __init__(self, consumer_key, first_api_url, second_api_user, second_api_password, second_api_url):
        self.consumer_key = consumer_key
        self.second_api_user = second_api_user
        self.second_api_password = second_api_password
        self.first_api_url = first_api_url
        self.second_api_url = second_api_url

    def logintofirstsite(self):  
        b64val = base64.b64encode(self.consumer_key.encode()).decode()
        headers = {"Authorization": "Basic %s" % b64val}
        data = {'grant_type': 'client_credentials', 'validity_period': '3600'}
        try:
            response = requests.post(self.first_api_url, headers=headers, data=data)
            decodedresponse = json.loads(response.content.decode())
            access_token = decodedresponse['access_token']
            return access_token
        except:
            return None
            
    def logintosecondsite(self):
        header = {"accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"}
        logindata = {'grant_type': 'password',
                     'username': "" + self.second_api_user + "", 'password': "" + self.second_api_password + ""
                     }
        try:
            returnedfromsite = requests.post(self.second_api_url + '/api/V1/token', 
headers=header, data=logindata)
            return returnedfromsite.json()['access_token']
        except:
            return None

我不明白的是如何模拟该请求调用,以及它在Python中的样子

我的测试当前看起来像:

class MyTestCase(unittest.TestCase):



    def setUp(self) -> None:       # PROBLEM BEGINS HERE
        self.grab_apitokens = grab_apitokens(actual_key, actual_site1, actual_user, actual_pass, actual_2nd_site)

    @patch('grab_apitokens.requests.get')
    def test_login(self, mock_get):
        mock_get.return_value.ok = True
        response = self.grab_apitokens.logintosite()
        assert_is_not_none(response)
        # self.assertEqual(True, False)



if __name__ == '__main__':
    unittest.main()

如何模拟requests.post功能


Tags: keyselftokenapiurlreturnconsumerdef
1条回答
网友
1楼 · 发布于 2024-09-28 01:23:03

在一位好导师的帮助下,我发现我的方法完全错了。下面是我在单元测试中得出的结论:

class MyTestCase(unittest.TestCase):


    def setUp(self) -> None:
        self.grab_apitokens = grab_apitokens("complete","gibberish","it really doesnt","matter","what is","in","here")

    @patch('grab_apitokens.requests.posts')
    def test_login(self, mock_get):
        mock_json = {'token': 'foo'}
        mock_get.return_value = Mock(ok=True)
        mock_get.return_value.json.return_value = mock_json
        mock_get.return_value.content = b'{"token": "foo"}'
        response = self.grab_apitokens.logintofirstsite()
        assert_equal(response, "foo")



if __name__ == '__main_

为了理解它的作用,我需要知道我们真正模拟的不是logintofirstsite()方法,我们模拟的是requests.post在该方法中做出的响应。使用mock_get,我们将injectrequests.posts设置为:{'token':'foo'}。那么以后的一切呢

response = requests.post(self.first_api_url, headers=headers, data=data)

在logintofirstsite()中,我真正要测试的是。即:

            decodedresponse = json.loads(response.content.decode())
            access_token = decodedresponse['token']
            return access_token

requests.post调用之前的设置一点也不重要。由于with{'token':'foo'}是my requests.post调用返回的内容,因此该逻辑位之后的返回值是'foo',因此MyTestCase中的assert_equal返回

相关问题 更多 >

    热门问题