I have a simple class that looks like this (it is used to consult a private Giltab for "ini" style configuration): remote_config.py
import requests
class RemoteConfig():
def __init__(self, config_endpoint, token):
self.config_endpoint = config_endpoint
self.token = token
def get_remote_settings(self):
headers= {'PRIVATE_TOKEN' : self.token}
params. = {'ref': 'master'}
response = requests.get(self.config_endopoint, params=params, headers=headers)
settings_from_remote = response.content.decode("utf-8")
return settings_from_remote
I need to write a unittest for this code. How can I do this without actually callling the http endpoint?
So far I am trying this: test_remote_config.py
import requests
import unittest
from private.remote_config import RemoteConfig # project code
class TestRemoteConfiguration(unittest.Testcase):
@patch(RemoteConfig.get_remote_settings)
def test_remote_config():
pass
If I stop here and run the test code, I am getting this error: TypeError: Need a valid target to patch, You supplied <function RemoteConfig.get_remote_settings>
How can I code the correct @patch
to get this test started?
To test this code without calling the actual http endpoint, mock the call of requests.get().
import unittest
from unittest import mock
from remote_config import RemoteConfig # project code
class TestRemoteConfiguration(unittest.TestCase):
def test_get_remote_settings(self):
url, token = "url", "token"
# create a RemoteConfig object
remote_config = RemoteConfig(url, token)
# mock the requests.get function
with mock.patch("requests.get") as get_request:
# set the return value of the mock to a fake response
get_request.return_value.content = b"{'foo': 'bar'}"
# call the get_remote_settings method
settings = remote_config.get_remote_settings()
# assert that the settings are equal to the expected settings
self.assertEqual(settings, "{'foo': 'bar'}")
# assert that the requests.get function was called with the correct parameters
get_request.assert_called_with(
url, params={"ref": "master"}, headers={"PRIVATE_TOKEN": token}
)
if __name__ == "__main__":
unittest.main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.