Reputation: 1343
I am trying to mock the get function from requests.session
and somehow it does not end up happening.
I have the following code:
#main.py
import requests
def function_with_get():
c = requests.session()
c.get('https://awesome_url.com')
# do some other stuff
return c
def second_function_with_get(client):
c.get('https://awesome_url.com')
# do some other stuff
#test.py
from unittest import mock
from django.test import TestCase
class Testing(TestCase):
@mock.patch('main.requests.session.get)
@mock.patch('main.requests.session)
def test_which_fails_because_of_get(mock_sess, mock_get):
client = function_with_get()
second_function_with_get(client)
assertEqual(mock_requests_session_get.call_count, 2)
The test throws an assertion error that mock_get
is called 0 times (0 != 2
)
How should the get
function of requests.session()
be mocked?
Upvotes: 0
Views: 3214
Reputation: 1304
It seems that you are already mocking the requests session - since it is a MagicMock
, you don't need to additionally mock the get method itself - checking for calls on the session will be enough.
So, your test.py could look like this:
#test.py
from unittest import mock
from unittest import TestCase
from main import function_with_get, second_function_with_get
class Testing(TestCase):
@mock.patch('main.requests.session')
def test_which_fails_because_of_get(self, mock_sess):
client = function_with_get()
second_function_with_get(client)
self.assertEqual(mock_sess.return_value.get.call_count, 2)
You could also try to create your own SessionMock
class with the get
method mocked, but it would require also proper setting (or resetting) it for each test. Personally, I usually find using MagicMock and its return_value
chain easier.
Upvotes: 1