-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest.py
332 lines (266 loc) · 8.65 KB
/
test.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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import io
import json
import librato
import urllib2
import unittest
import urlparse
OPTIONS = {
"logger": lambda *msgs: None # no-op logger
}
orig_urlopen = urllib2.urlopen
class TestLibrato(unittest.TestCase):
def tearDown(self):
urllib2.urlopen = orig_urlopen
def test_auth(self):
"user and token are encoded correclty in HTTP authorization header"
auths = []
def urlopen(req):
auths.append(req.get_header("Authorization"))
return io.BytesIO("{}")
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
"metrics": [ "cpu_time" ]
}, OPTIONS)
l.read()
self.assertEqual(auths[0], "Basic QWxhZGRpbjpPcGVuU2VzYW1l")
def test_url(self):
"valid url suffixed with the metric name"
urls = []
def urlopen(req):
urls.append(req.get_full_url())
return io.BytesIO("{}")
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
"metrics": [ "cpu_time", "cpu_idle" ]
}, OPTIONS)
l.read() # first metric
l.read() # second metric
expected = "https://metrics-api.librato.com/v1/metrics/cpu_time?"
self.assertTrue(urls[0].startswith(expected))
expected = "https://metrics-api.librato.com/v1/metrics/cpu_idle?"
self.assertTrue(urls[1].startswith(expected))
def test_get_metrics(self):
"retrieves the full list of available metrics"
urls = []
def urlopen(req):
urls.append(req.get_full_url())
res = {
"metrics": [
{"name": "cpu_time", "display_name": "hello"},
{"name": "cpu_idle", "display_name": "world"},
]
}
return io.BytesIO(json.dumps(res))
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
}, OPTIONS)
metrics = l.get_metrics()
self.assertEqual(metrics, ["cpu_time", "cpu_idle"])
self.assertEqual(urls,["https://metrics-api.librato.com/v1/metrics"])
def test_failed_authentication(self):
"fail to authenticate request"
urls = []
def urlopen(req):
raise Exception("fail")
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
}, OPTIONS)
try:
metrics = l.get_metrics()
except Exception as e:
err_message = ('Authentication failed.'
' Please check your credentials and try again')
self.assertEqual(e.args[0], err_message)
def test_done(self):
"_read() returns None when all results where consumed"
def urlopen(req):
return io.BytesIO("{}")
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
"metrics": [ "cpu_time", "cpu_idle" ]
}, OPTIONS)
self.assertIsNotNone(l.read()) # first metric
self.assertIsNotNone(l.read()) # second metric
self.assertIsNone(l.read()) # should be done by now
def test_pagination(self):
"_read() continues to read the same metric with the new start time"
times = [ 100, 200 ]
urls = []
def urlopen(req):
urls.append(req.get_full_url())
nexttime = times.pop(0) if len(times) > 0 else None
res = { "query": { "next_time": nexttime } }
return io.BytesIO(json.dumps(res))
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
"metrics": [ "cpu_time" ]
}, OPTIONS)
self.assertIsNotNone(l.read()) # first start time
self.assertIsNotNone(l.read()) # 100
self.assertIsNotNone(l.read()) # 200; last
self.assertIsNone(l.read()) # done.
# urls[0] has the default start time; irrelevant for pagination
qs = parseqs(urls[1])
self.assertEqual(qs["start_time"], ["100"])
qs = parseqs(urls[2])
self.assertEqual(qs["start_time"], ["200"])
def test_progress(self):
"test that the progress notifications are fired"
pass
def test_results(self):
"parse results json and breakdown all measurements to a list of results"
def urlopen(req):
return io.BytesIO(json.dumps(RESULTS))
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
"metrics": [ "cpu_time" ]
}, OPTIONS)
res = l.read()
self.assertEqual(res, EXPECTED)
def test_request_err(self):
"parses request errors and returns the descriptive message"
def urlopen(req):
url = req.get_full_url()
body = io.BytesIO(json.dumps({
"errors": {
"request": [
"one two",
"three four"
]
}
}))
raise urllib2.HTTPError(url, 400, "Bad Request", {}, body)
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
"metrics": [ "cpu_time", "cpu_idle" ]
}, OPTIONS)
try:
l.read()
except librato.LibratoError, e:
self.assertEqual(str(e), "one two")
def test_params_err(self):
"parses params errors and returns the descriptive message"
def urlopen(req):
url = req.get_full_url()
body = io.BytesIO(json.dumps({
"errors": {
"params": {
"name": ["is missing", "is required"],
"value": ["is not a number", "is too big"]
}
}
}))
raise urllib2.HTTPError(url, 400, "Bad Request", {}, body)
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
"metrics": [ "cpu_time", "cpu_idle" ]
}, OPTIONS)
try:
l.read()
except librato.LibratoError, e:
self.assertEqual(str(e), "name is missing")
def test_unknown_err(self):
"forwards all other errors as-is"
raised = {}
def urlopen(req):
url = req.get_full_url()
body = io.BytesIO(json.dumps({}))
e = urllib2.HTTPError(url, 400, "Bad Request", {}, body)
raised["error"] = e
raise e
urllib2.urlopen = urlopen
l = librato.Librato({
"user": "Aladdin",
"token": "OpenSesame",
"metrics": [ "cpu_time", "cpu_idle" ]
}, OPTIONS)
try:
l.read()
except Exception, e:
self.assertEqual(e, raised["error"])
# test data that returns from the API
RESULTS = {
"resolution": 60,
"measurements": {
"server1.acme.com": [
{
"measure_time": 1234567890,
"value": 84.5,
"count": 1
},
{
"measure_time": 1234567950,
"value": 86.7,
"count": 1
}
],
"server2.acme.com": [
{
"measure_time": 1234567890,
"value": 94.5,
"count": 1
},
{
"measure_time": 1234567890,
"value": 96.7,
"count": 1
}
]
}
}
# the expected parsed output data from the previous RESULTS variable
EXPECTED = [
{
"count": 1,
"source": "server2.acme.com",
"metric": "cpu_time",
"value": 94.5,
"time": 1234567890
},
{
"count": 1,
"source": "server2.acme.com",
"metric": "cpu_time",
"value": 96.7,
"time": 1234567890
},
{
"count": 1,
"source": "server1.acme.com",
"metric": "cpu_time",
"value": 84.5,
"time": 1234567890
},
{
"count": 1,
"source": "server1.acme.com",
"metric": "cpu_time",
"value": 86.7,
"time": 1234567950
}
]
# -- helper functions
def parseqs(url):
"parses a url and returns its parsed query string"
return urlparse.parse_qs(urlparse.urlparse(url).query)
# fire it up.
if __name__ == "__main__":
unittest.main()