-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathtest_withings_api.py
More file actions
232 lines (211 loc) · 8.72 KB
/
test_withings_api.py
File metadata and controls
232 lines (211 loc) · 8.72 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import json
import time
import unittest
from datetime import datetime
from requests import Session
from withings import (
WithingsApi,
WithingsCredentials,
WithingsMeasureGroup,
WithingsMeasures
)
try:
import configparser
except ImportError: # Python 2.x fallback
import ConfigParser as configparser
try:
from unittest.mock import MagicMock
except ImportError: # Python 2.x fallback
from mock import MagicMock
class TestWithingsApi(unittest.TestCase):
def setUp(self):
self.mock_api = True
if self.mock_api:
self.creds = WithingsCredentials()
else:
config = ConfigParser.ConfigParser()
config.read('withings.conf')
self.creds = WithingsCredentials(
consumer_key=config.get('withings', 'consumer_key'),
consumer_secret=config.get('withings', 'consumer_secret'),
access_token=config.get('withings', 'access_token'),
access_token_secret=config.get('withings',
'access_token_secret'),
user_id=config.get('withings', 'user_id'))
self.api = WithingsApi(self.creds)
def test_attributes(self):
""" Make sure the WithingsApi objects have the right attributes """
assert hasattr(WithingsApi, 'URL')
creds = WithingsCredentials(user_id='FAKEID')
api = WithingsApi(creds)
assert hasattr(api, 'credentials')
assert hasattr(api, 'oauth')
assert hasattr(api, 'client')
def test_attribute_defaults(self):
"""
Make sure WithingsApi object attributes have the correct defaults
"""
self.assertEqual(WithingsApi.URL, 'http://wbsapi.withings.net')
creds = WithingsCredentials(user_id='FAKEID')
api = WithingsApi(creds)
self.assertEqual(api.credentials, creds)
self.assertEqual(api.client.auth, api.oauth)
self.assertEqual(api.client.params, {'userid': creds.user_id})
def test_request(self):
"""
Make sure the request method builds the proper URI and returns the
request body as a python dict.
"""
self.mock_request({})
resp = self.api.request('fake_service', 'fake_action')
Session.request.assert_called_once_with(
'GET', 'http://wbsapi.withings.net/fake_service',
params={'action': 'fake_action'})
self.assertEqual(resp, {})
def test_request_params(self):
"""
Check that the request method passes along extra params and works
with different HTTP methods
"""
self.mock_request({})
resp = self.api.request('user', 'getbyuserid', params={'p2': 'p2'},
method='POST')
Session.request.assert_called_once_with(
'POST', 'http://wbsapi.withings.net/user',
params={'p2': 'p2', 'action': 'getbyuserid'})
self.assertEqual(resp, {})
def test_request_error(self):
""" Check that requests raises an exception when there is an error """
self.mock_request('', status=1)
self.assertRaises(Exception, self.api.request, ('user', 'getbyuserid'))
def test_get_user(self):
""" Check that the get_user method fetches the right URL """
self.mock_request({
'users': [
{'id': 1111111, 'birthdate': 364305600, 'lastname': 'Baggins',
'ispublic': 255, 'firstname': 'Frodo', 'fatmethod': 131,
'gender': 0, 'shortname': 'FRO'}
]
})
resp = self.api.get_user()
Session.request.assert_called_once_with(
'GET', 'http://wbsapi.withings.net/user',
params={'action': 'getbyuserid'})
self.assertEqual(type(resp), dict)
assert 'users' in resp
self.assertEqual(type(resp['users']), list)
self.assertEqual(len(resp['users']), 1)
self.assertEqual(resp['users'][0]['firstname'], 'Frodo')
self.assertEqual(resp['users'][0]['lastname'], 'Baggins')
def test_get_measures(self):
"""
Check that get_measures fetches the appriate URL, the response looks
correct, and the return value is a WithingsMeasures object
"""
body = {
'updatetime': 1409596058,
'measuregrps': [
{'attrib': 2, 'measures': [
{'unit': -1, 'type': 1, 'value': 860}
], 'date': 1409361740, 'category': 1, 'grpid': 111111111},
{'attrib': 2, 'measures': [
{'unit': -2, 'type': 4, 'value': 185}
], 'date': 1409361740, 'category': 1, 'grpid': 111111112}
]
}
self.mock_request(body)
resp = self.api.get_measures()
Session.request.assert_called_once_with(
'GET', 'http://wbsapi.withings.net/measure',
params={'action': 'getmeas'})
self.assertEqual(type(resp), WithingsMeasures)
self.assertEqual(len(resp), 2)
self.assertEqual(type(resp[0]), WithingsMeasureGroup)
self.assertEqual(resp[0].weight, 86.0)
self.assertEqual(resp[1].height, 1.85)
# Test limit=1
body['measuregrps'].pop()
self.mock_request(body)
resp = self.api.get_measures(limit=1)
Session.request.assert_called_once_with(
'GET', 'http://wbsapi.withings.net/measure',
params={'action': 'getmeas', 'limit': 1})
self.assertEqual(len(resp), 1)
self.assertEqual(resp[0].weight, 86.0)
def test_subscribe(self):
"""
Check that subscribe fetches the right URL and returns the expected
results
"""
self.mock_request(None)
resp = self.api.subscribe('http://www.example.com/', 'fake_comment')
Session.request.assert_called_once_with(
'GET', 'http://wbsapi.withings.net/notify',
params={'action': 'subscribe', 'appli': 1,
'comment': 'fake_comment',
'callbackurl': 'http://www.example.com/'})
self.assertEqual(resp, None)
def test_unsubscribe(self):
"""
Check that unsubscribe fetches the right URL and returns the expected
results
"""
self.mock_request(None)
resp = self.api.unsubscribe('http://www.example.com/')
Session.request.assert_called_once_with(
'GET', 'http://wbsapi.withings.net/notify',
params={'action': 'revoke', 'appli': 1,
'callbackurl': 'http://www.example.com/'})
self.assertEqual(resp, None)
def test_is_subscribed(self):
"""
Check that is_subscribed fetches the right URL and returns the
expected results
"""
url = 'http://wbsapi.withings.net/notify'
params = {
'callbackurl': 'http://www.example.com/',
'action': 'get',
'appli': 1
}
self.mock_request({'expires': 2147483647, 'comment': 'fake_comment'})
resp = self.api.is_subscribed('http://www.example.com/')
Session.request.assert_called_once_with('GET', url, params=params)
self.assertEquals(resp, True)
# Not subscribed
self.mock_request(None, status=343)
resp = self.api.is_subscribed('http://www.example.com/')
Session.request.assert_called_once_with('GET', url, params=params)
self.assertEquals(resp, False)
def test_list_subscriptions(self):
"""
Check that list_subscriptions fetches the right URL and returns the
expected results
"""
self.mock_request({'profiles': [
{'comment': 'fake_comment', 'expires': 2147483647}
]})
resp = self.api.list_subscriptions()
Session.request.assert_called_once_with(
'GET', 'http://wbsapi.withings.net/notify',
params={'action': 'list', 'appli': 1})
self.assertEqual(type(resp), list)
self.assertEqual(len(resp), 1)
self.assertEqual(resp[0]['comment'], 'fake_comment')
self.assertEqual(resp[0]['expires'], 2147483647)
# No subscriptions
self.mock_request({'profiles': []})
resp = self.api.list_subscriptions()
Session.request.assert_called_once_with(
'GET', 'http://wbsapi.withings.net/notify',
params={'action': 'list', 'appli': 1})
self.assertEqual(type(resp), list)
self.assertEqual(len(resp), 0)
def mock_request(self, body, status=0):
if self.mock_api:
json_content = {'status': status}
if body != None:
json_content['body'] = body
response = MagicMock()
response.content = json.dumps(json_content).encode('utf8')
Session.request = MagicMock(return_value=response)