Is it possible to mock more requests types (GET
, POST
, PUT
etc...) in one method? I can mock one type of request with mock.patch
decorator. But, how can I mock more types in one test method? I am looking for a Pythonic and elegant solution for it (I would prefer the mock.patch
decorator but I am open for other solutions as well).
You can see below an example for my problem:
source.py
import requests
def source_function():
x = requests.get("get_url.com")
requests.post("post_url.com/{}".format(x.text))
test.py
import unittest
from unittest import mock
from source import source_function
class TestCases(unittest.TestCase):
@mock.patch("requests.get")
def test_source_function(self, mocked_get):
mocked_get.return_value = mock.Mock(status_code=201, json=lambda: {"data": {"id": "test"}})
source_function() # The POST request is not mocked.
CodePudding user response:
I found the solution. I only had to pass one-by-one the mock objects.
source.py
import requests
def source_function():
x = requests.get("http://get_url.com")
print("Get resp: {}".format(x.json()))
y = requests.post("http://post_url.com")
print("Post resp: {}".format(y.json()))
test.py
import unittest
from unittest import mock
import source
class TestCases(unittest.TestCase):
@mock.patch("source.requests.get")
@mock.patch("source.requests.post")
def test_source_function(self, mocked_post, mocked_get):
mocked_get.return_value = mock.Mock(status_code=200, json=lambda: {"data_get": {"id": "test"}})
mocked_post.return_value = mock.Mock(status_code=200, json=lambda: {"data_post": {"id": "test"}})
source.source_function()
# Entry point of script.
if __name__ == "__main__":
unittest.main()
Output:
>>> python3 test.py
Get resp: {'data_get': {'id': 'test'}}
Post resp: {'data_post': {'id': 'test'}}
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Only the sequence is important. The mock object of the top decorator should be the last one (In my case the GET
method mock object).