I am trying to use Pythons mock package to mock Pythons requests
module. What are the basic calls to get me working in below scenario?
In my views.py, I have a function that makes variety of requests.get() calls with different response each time
def myview(request):
res1 = requests.get('aurl')
res2 = request.get('burl')
res3 = request.get('curl')
In my test class I want to do something like this but cannot figure out exact method calls
Step 1:
# Mock the requests module
# when mockedRequests.get('aurl') is called then return 'a response'
# when mockedRequests.get('burl') is called then return 'b response'
# when mockedRequests.get('curl') is called then return 'c response'
Step 2:
Call my view
Step 3:
verify response contains 'a response', 'b response' , 'c response'
How can I complete Step 1 (mocking the requests module)?
Answers
To mock the requests
module using the unittest.mock
package, you can follow these steps:
Step 1: Mocking the requests.get
calls
You can use unittest.mock.patch
to mock the requests.get
method. Here's how you can do it:
import requests
from unittest import TestCase
from unittest.mock import patch, Mock
class MyViewTest(TestCase):
@patch('requests.get')
def test_myview(self, mock_get):
# Set up the mock responses
mock_get.side_effect = [
Mock(text='a response'), # Response for 'aurl'
Mock(text='b response'), # Response for 'burl'
Mock(text='c response') # Response for 'curl'
]
# Call your view function
response = myview(None) # Replace `None` with a valid request object if necessary
# Verify the responses
self.assertIn('a response', response)
self.assertIn('b response', response)
self.assertIn('c response', response)
Explanation:
- Import Required Modules: You need to import
patch
fromunittest.mock
to mock therequests.get
function. - Using
@patch
Decorator: The@patch('requests.get')
decorator replacesrequests.get
with a mock object during the test. - Setting Up Mock Responses: The
side_effect
attribute allows you to specify different responses for consecutive calls. Each item in the list corresponds to the responses for therequests.get
calls in the order they are made. - Calling Your View: Call the
myview
function to simulate the requests. - Verifying Responses: Use assertions to check if the expected responses are part of the result.
Note:
- Ensure that
myview
returns a response that includes the text from the mocked responses; otherwise, adjust your assertions accordingly. - If your view function processes the responses differently, adapt the assertions to fit your needs.