Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mocking session in requests library

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.

like image 255
Artem Mezhenin Avatar asked Jun 24 '13 10:06

Artem Mezhenin


People also ask

How do you send a mock request in Python?

To mock the requests module, you can use the patch() function. Suppose that the mock_requests is a mock of the requests module. The mock_requests. get() should return a mock for the response.

What is mock library?

mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.

What does mock mock () do?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.

How do you mock request in flask?

Here's an example below. import pytest from app import create_app @pytest. fixture def request_context(): """create the app and return the request context as a fixture so that this process does not need to be repeated in each test """ app = create_app('module.


1 Answers

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'   
like image 92
Blafkees Avatar answered Sep 18 '22 18:09

Blafkees