I tried reading some of the things regarding unittest.mock but I couldn't grasp it so maybe using my use case will help me learn more about this.
Basically I have this function that calls an external api:
# service.py
def create_user(name):
headers = {
...
}
url = external.URL + 'user/'
payload = {
"name": name
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
return response.json()
so I'm trying to create a test but I'm not sure how to use unittest.mock for this function. I could test this function directly but I want to learn more about mocking and why should I do it. Sorry if this question has been asked many times but I really want to understand it with my use case.
You could use patch.object to mock requests.post
method.
Eg
service.py
:
import json
import requests
from collections import namedtuple
external = namedtuple('URL', 'URL')
external = external('http://localhost:3000/api/')
def create_user(name):
headers = {}
url = external.URL + 'user/'
payload = {
"name": name
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
return response.json()
test_service.py
:
import unittest
import requests
from service import create_user
from unittest.mock import patch, Mock
import json
class TestService(unittest.TestCase):
@patch.object(requests, 'post')
def test_create_user(self, mock_post):
mock_json = Mock()
mock_json.return_value = 'mock data'
mock_post.return_value.json = mock_json
actual = create_user("teresa teng")
mock_post.assert_called_with('http://localhost:3000/api/user/', headers={},
data=json.dumps({"name": "teresa teng"}))
self.assertEqual(actual, 'mock data')
if __name__ == '__main__':
unittest.main()
unit test result with coverage report:
coverage run /Users/ldu020/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/63899742/test_service.py && coverage report -m --include="src/*"
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Name Stmts Miss Cover Missing
--------------------------------------------------------------------------
src/stackoverflow/63899742/service.py 11 0 100%
src/stackoverflow/63899742/test_service.py 15 0 100%
--------------------------------------------------------------------------
TOTAL 26 0 100%
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.