-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo_mock.py
91 lines (71 loc) · 2.4 KB
/
demo_mock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import unittest
from unittest import mock
import requests
import responses
from prettyprinter import cpprint
from src.user import User
class APIUnreachableException(Exception): pass
class HttpNotFound(Exception): pass
def get_user():
user = None
try:
response = requests.get('http://randomuser.me/api/')
if response.status_code == 404:
raise HttpNotFound()
result = response.json()
# prettyprinter.cpprint(result)
record = result['results'][0]
return User(record['name']['title'], record['name']['last'], record['name']['first'],
record['login']['username'],
record['email'])
except requests.exceptions.ConnectionError:
raise APIUnreachableException()
def main():
try:
user = get_user()
cpprint(user)
# print(f"{user.titre} {user.nom_complet}")
except APIUnreachableException:
print("L'API est injoignable.")
except HttpNotFound:
print("l'URL n'exite pas")
mock_user = {
'results': [{
'email': '[email protected]',
'name': {
'title': 'Mr',
'first': 'Stéphane',
'last': 'THIPHONET',
},
'login': {
'username': 'Pingoo'
},
'gender': 'male',
}]
}
class Test_user(unittest.TestCase):
@responses.activate
def test_get_user(self):
responses.add(responses.GET, 'http://randomuser.me/api/', json=mock_user)
user = get_user()
self.assertIsInstance(user, User)
self.assertEqual(user.prenom, "Stéphane")
self.assertEqual(user.nom, "THIPHONET")
# @unittest.skip("In progress")
@responses.activate
def test_get_user_server_unreachable(self):
with self.assertRaises(APIUnreachableException):
user = get_user()
# @unittest.skip("In progress")
@responses.activate
def test_get_user_url_not_exist(self):
responses.add(responses.GET, 'http://randomuser.me/api/', status=404)
with self.assertRaises(HttpNotFound):
user = get_user()
@mock.patch('demo_mock.get_user')
def test_get_user_mock(self, mock_get_user):
mock_get_user.return_value = User.create_from_api(mock_user)
user = get_user()
self.assertIsInstance(user, User)
self.assertEqual(user.prenom, "Stéphane")
self.assertEqual(user.nom, "THIPHONET")