This is the function I am trying to test.
def service_request(url, session=configure_session()):
response = session.get(url)
document = json.loads(response.text)
return document
Yes it is basic right now (hardly worth testing you might argue), but if I can get the mocking working I will be able to add more logic to it and test the new additions as I go. I have tried various things to mock two other functions called within this test. One is the configure_session
function and the other is the get
method from the requests
library.
The configure_session
function builds the requests.Session
object configured with certificates required to make a request to the service. This method also optionally verifies the SSL connection with the CA bundle. The config
file, imported at the top of the file (not shown) retrieves environment variables and is working as expected.
def configure_session():
session = requests.Session()
session.cert = (config.client_cert, config.client_key)
if config.ssl_verify:
session.verify = config.ca_bundle
else:
session.verify = False
user_agent = f'{config.user_agent_version}'
session.headers.update({'User-Agent': user_agent,
'Accept': 'application/json'})
return session
This is the latest code I have tried. The load_fixture
method is a test utility method and is working as expected.
def test_request():
response_fixture = load_fixture('example_response.json')
mock_session = MagicMock()
mock_get = MagicMock()
mock_session.get.return_value = mock_get
mock_get.text.return_value = response_fixture
test_url = "https://url-for-test/with/the/path/here"
expected_headers = {
'Accept': 'application/json',
'User-Agent': 'test_user_agent_from_env_vars'
}
service_request(test_url, mock_session)
mock_session.get.assert_called_with(
test_url,
headers=expected_headers
)
assert response == response_fixture
The current error is TypeError: the JSON object must be str, bytes or bytearray, not 'MagicMock'
.
Aucun commentaire:
Enregistrer un commentaire