Skip to content

Commit e7192f3

Browse files
committed
Add mock
1 parent cc439d7 commit e7192f3

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

python_test_example/mock/__init__.py

Whitespace-only changes.

python_test_example/mock/my_class.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import requests
2+
3+
class MyClass:
4+
def fetch_json(self, url: str):
5+
response = requests.get(url)
6+
return response.json()
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from unittest import TestCase, main, mock
2+
3+
from mock.my_class import MyClass
4+
5+
class MyClassTestCase(TestCase):
6+
def mocked_requests_get(*args, **kwargs):
7+
class MockResponse:
8+
def __init__(self, json_data, status_code):
9+
self.json_data = json_data
10+
self.status_code = status_code
11+
12+
def json(self):
13+
return self.json_data
14+
15+
if args[0] == 'http://example.com/test.json':
16+
return MockResponse({'key1': 'value1'}, 200)
17+
elif args[0] == 'http://example.com/another_test.json':
18+
return MockResponse({'key2': 'value2'}, 200)
19+
20+
return MockResponse(None, 404)
21+
22+
@mock.patch('requests.get', side_effect=mocked_requests_get)
23+
def test_fetch_json(self, mock_get):
24+
my_class = MyClass()
25+
26+
json_data = my_class.fetch_json('http://example.com/test.json')
27+
self.assertEqual(json_data, {'key1': 'value1'})
28+
json_data = my_class.fetch_json('http://example.com/another_test.json')
29+
self.assertEqual(json_data, {'key2': 'value2'})
30+
json_data = my_class.fetch_json('http://no_example.com/test.json')
31+
self.assertIsNone(json_data)
32+
33+
self.assertIn(
34+
mock.call('http://example.com/test.json'), mock_get.call_args_list
35+
)
36+
self.assertIn(
37+
mock.call('http://example.com/another_test.json'), mock_get.call_args_list
38+
)
39+
40+
self.assertEqual(len(mock_get.call_args_list), 3)
41+
42+
if __name__ == '__main__':
43+
main()

0 commit comments

Comments
 (0)