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.
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.
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With