20

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

import requests
session = requests.session()

How can I mock it with Mock? Is there any decorator for this kind of operations? I tried following:

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

but (as expected) this code doesn't return session.get to original state after each test, like @mock.patch decorator do.

Artem Mezhenin
  • 5,539
  • 6
  • 32
  • 51

4 Answers4

15

Since requests.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'   
Blafkees
  • 151
  • 1
  • 5
6

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

Konstantine Rybnikov
  • 2,457
  • 1
  • 22
  • 29
1

With some inspiration from the previous answer and :

mock-attributes-in-python-mock

I was able to mock a session defined like this:

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

with that: (the call to get returns a response with a 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
Community
  • 1
  • 1
howaryoo
  • 1,241
  • 11
  • 16
1

I discovered the requests_mock library. It saved me a lot of bother. With pytest...

def test_success(self, requests_mock):
    """They give us a token.
    """
    requests_mock.get("https://example.com/api/v1/login", 
        text=(
          '{"result":1001, "errMsg":null,'
          f'"token":"TEST_TOKEN",' '"expire":1799}'))

    auth_token = the_module_I_am_testing.BearerAuth('test_apikey')

    assert auth_token == 'TEST_TOKEN'

The module I am testing has my BearerAuth class which hits an endpoint for a token to start a requests.session with.

John Mee
  • 50,179
  • 34
  • 152
  • 186