osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

mocking for get method in requests


On 18.1.2019 19:16, Shakti Kumar wrote:
> Hello people,
> I noticed something weird (weird as per my current knowledge, though I know
> its subjective) today.

Hi Kumar,


> mock_req.get('').return_value = 'Hello'

Here you are calling mock_req -MagicMocks get-method with parameter '' 
and assigning 'Hello' to its return value's return_value attribute. By 
default MagicMock instance methods always return a new MagicMock 
instance, which will create attributes on demand. You are not actually 
setting the return value of the patched requests, but rather assigning a 
return_value attribute to a local instance of a MagicMock.


> mock_req.get.return_value = 'Hello'
Here you are assigning 'hello' to mock_req instance's get -methods 
return_value. This is probably what you are after. Notice that you are 
not actually calling any of its methods, only assigning.

Mocks are powerful but take some time to get use to.


 >>> from unittest import mock
 >>> a = mock.MagicMock()
 >>> a.get.return_value = 'asd'
 >>> a.get()
'asd'
 >>> a.get.assert_called_once_with()
 >>> b = mock.MagicMock()
 >>> new_mock = b.get()
 >>> new_mock.return_value = 'qwe'
 >>> new_mock()
'qwe'
 >>> b.get.assert_called_once_with()
 >>> new_mock.assert_called_once_with()
 >>> b.get()
<MagicMock name='mock.get()' id='140056664500096'>
 >>> b.get.assert_called_once_with()
Traceback (most recent call last):
 ? File "<stdin>", line 1, in <module>
 ? File "/usr/lib/python3.5/unittest/mock.py", line 802, in 
assert_called_once_with
 ??? raise AssertionError(msg)
AssertionError: Expected 'get' to be called once. Called 2 times.



Hope this helps,

Toni


>
> sample.py file
>
> --
>
> import requests
> def random_testing():
>      out = requests.get('www.cisco.com')
>      a = out.json()
>      return a
>
>
> testing.py file
>
> --
>
> @patch(*?*sample.requests')
> def test_random_testing(self, mock_req):
>      mock_req.get('').return_value = 'Hello'
>      out = api.random_testing()
>
>
> Patching the sample.requests in this way does not lead the output of
> requests.get() function in sample.py file to be ?Hello? as indicated
> in
> mock_req.get('').return_value = 'Hello'
> Instead, it creates a new field called return_value in ?out', and
> hence out.return_value is ?Hello? instead of just ?out?.
>
> But if I patch it as,
>
> @patch(*?*sample.requests')
> def test_random_testing(self, mock_req):
>      mock_req.get.return_value = 'Hello'
>      out = api.random_testing()
>
> It does give the value of ?out? as ?Hello? in sample.py file.
> I know I am missing something, which is where I need some help :)
>
> Thanks.
>