Mocking session in the query library

In my python code, I have a global instance of requests.session :

 import requests session = requests.session() 

How can I mock him with Mock ? Is there a decorator for this kind of operation? I tried the following:

 session.get = mock.Mock(side_effect=self.side_effects) 

but (as expected) this code does not return session.get to its original state after each test, for example, @mock.patch decorator do.

+4
source share
3 answers

Use mock.patch to fix the session in your module. Here is a complete working example https://gist.github.com/k-bx/5861641

+2
source

With some inspiration from the previous answer and:

mock-attributes-in-python-mock

I was able to make fun of a session defined as follows:

 class MyClient(object): """ """ def __init__(self): self.session = requests.session() 

with this: (the get call returns a response with the status_code attribute set to 200)

 def test_login_session(): with mock.patch('path.to.requests.session') as patched_session: # instantiate service: Arrange test_client = MyClient() type(patched_session().get.return_value).status_code = mock.PropertyMock(return_value=200) # Act (+assert) resp = test_client.login_cookie() # Assert assert resp is None 
+1
source

Since request.session () returns an instance of the Session class, it is also possible to use patch.object ()

 from requests import Session from unittest.mock import patch @patch.object(Session, 'get') def test_foo(mock_get): mock_get.return_value = 'bar' 
0
source

Source: https://habr.com/ru/post/1487859/


All Articles