首页 > 解决方案 > 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 功能?

标签: pythonpython-3.xunit-testingpython-unittest

解决方案


在一位好导师的帮助下,我发现我的方法全错了。这是我最终的单元测试:

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,我们将 requests.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'} 是我的 requests.post 调用返回的内容,因此该位逻辑之后的返回值是 'foo',因此 MyTestCase 中的 assert_equal 通过。


推荐阅读