[TIP] py.test + mock - how to test attribute "call"? REST api testing requests

Sylvain Viart sylvain at opensource-expert.com
Thu Nov 3 06:10:17 PDT 2016


Le 03/11/2016 à 10:35, Daniel Bradburn a écrit :
> Ah I see what you are trying to do now, I think the problem is that
> your function is returning r.text which is a new mock object when
> really you want to assert attribute access on the original return
> value from requests, this seems to reflect your use case:
> >>> import mock
> >>> r = mock.MagicMock()
> >>> r = r.text
> >>> assert 'text' in r._mock_parent._mock_children
> However, it is probably unwise to access the protected attributes like
> this, perhaps you could just mock requests.get(call_url,
> headers=headers) yourself, I think you can probably use something like
> this as a starting point for what you are trying to do...

Thanks Dan, that's it.

And you're also right: it's ugly.

I was hoping to find a quick way to do it in a short time.
It is interesting, and I will develop something around that.

Nice colored formating, how do you did that?
> r = mock.MagicMock()
> with mock.patch('requests.get', return_value=r) as get:
>     result = function_under_test('https://www.google.nl', False)
>     str(result)
>     r.json.assert_called_once()
>     r.text.__str__.assert_not_called()

I still not "like" that way either.

What is the effect of: str(result) ?


Sylvain Viart - DevOps système linux - freelance developer

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20161103/b4afb57b/attachment.htm>

More information about the testing-in-python mailing list