Debian Codegraph @

influxdb/tests/influxdb08/client_test.py

raw ◀ ▶
Source reconstructed at patch state 0 of 4 — not the installed (fully patched) source.
4 Debian patches touch this file
1 # -*- coding: utf-8 -*-
2 """Client unit tests."""
3
4 import json
5 import socket
6 import sys
7 import unittest
8 import random
9 import warnings
10
11 import mock
12 import requests
13 import requests.exceptions
14 import requests_mock
15
16 from nose.tools import raises
17 from mock import patch
18
19 from influxdb.influxdb08 import InfluxDBClient
20 from influxdb.influxdb08.client import session
21
22 if sys.version < '3':
23 import codecs
24
25 def u(x):
26 """Test codec."""
27 return codecs.unicode_escape_decode(x)[0]
28 else:
29 def u(x):
30 """Test codec."""
31 return x
32
33
34 def _build_response_object(status_code=200, content=""):
35 resp = requests.Response()
36 resp.status_code = status_code
37 resp._content = content.encode("utf8")
38 return resp
39
40
41 def _mocked_session(method="GET", status_code=200, content=""):
42 method = method.upper()
43
44 def request(*args, **kwargs):
45 """Define a request for the _mocked_session."""
46 c = content
47
48 # Check method
49 assert method == kwargs.get('method', 'GET')
50
51 if method == 'POST':
52 data = kwargs.get('data', None)
53
54 if data is not None:
55 # Data must be a string
56 assert isinstance(data, str)
57
58 # Data must be a JSON string
59 assert c == json.loads(data, strict=True)
60
61 c = data
62
63 # Anyway, Content must be a JSON string (or empty string)
64 if not isinstance(c, str):
65 c = json.dumps(c)
66
67 return _build_response_object(status_code=status_code, content=c)
68
69 mocked = patch.object(
70 session,
71 'request',
72 side_effect=request
73 )
74
75 return mocked
76
77
78 class TestInfluxDBClient(unittest.TestCase):
79 """Define a TestInfluxDBClient object."""
80
81 def setUp(self):
82 """Set up a TestInfluxDBClient object."""
83 # By default, raise exceptions on warnings
84 warnings.simplefilter('error', FutureWarning)
85
86 self.dummy_points = [
87 {
88 "points": [
89 ["1", 1, 1.0],
90 ["2", 2, 2.0]
91 ],
92 "name": "foo",
93 "columns": ["column_one", "column_two", "column_three"]
94 }
95 ]
96
97 self.dsn_string = 'influxdb://uSr:pWd@host:1886/db'
98
99 def test_scheme(self):
100 """Test database scheme for TestInfluxDBClient object."""
101 cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
102 self.assertEqual(cli._baseurl, 'http://host:8086')
103
104 cli = InfluxDBClient(
105 'host', 8086, 'username', 'password', 'database', ssl=True
106 )
107 self.assertEqual(cli._baseurl, 'https://host:8086')
108
109 def test_dsn(self):
110 """Test datasource name for TestInfluxDBClient object."""
111 cli = InfluxDBClient.from_dsn(self.dsn_string)
112 self.assertEqual('http://host:1886', cli._baseurl)
113 self.assertEqual('uSr', cli._username)
114 self.assertEqual('pWd', cli._password)
115 self.assertEqual('db', cli._database)
116 self.assertFalse(cli._use_udp)
117
118 cli = InfluxDBClient.from_dsn('udp+' + self.dsn_string)
119 self.assertTrue(cli._use_udp)
120
121 cli = InfluxDBClient.from_dsn('https+' + self.dsn_string)
122 self.assertEqual('https://host:1886', cli._baseurl)
123
124 cli = InfluxDBClient.from_dsn('https+' + self.dsn_string,
125 **{'ssl': False})
126 self.assertEqual('http://host:1886', cli._baseurl)
127
128 def test_switch_database(self):
129 """Test switch database for TestInfluxDBClient object."""
130 cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
131 cli.switch_database('another_database')
132 self.assertEqual(cli._database, 'another_database')
133
134 @raises(FutureWarning)
135 def test_switch_db_deprecated(self):
136 """Test deprecated switch database for TestInfluxDBClient object."""
137 cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
138 cli.switch_db('another_database')
139 self.assertEqual(cli._database, 'another_database')
140
141 def test_switch_user(self):
142 """Test switch user for TestInfluxDBClient object."""
143 cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
144 cli.switch_user('another_username', 'another_password')
145 self.assertEqual(cli._username, 'another_username')
146 self.assertEqual(cli._password, 'another_password')
147
148 def test_write(self):
149 """Test write to database for TestInfluxDBClient object."""
150 with requests_mock.Mocker() as m:
151 m.register_uri(
152 requests_mock.POST,
153 "http://localhost:8086/write"
154 )
155 cli = InfluxDBClient(database='db')
156 cli.write(
157 {"database": "mydb",
158 "retentionPolicy": "mypolicy",
159 "points": [{"name": "cpu_load_short",
160 "tags": {"host": "server01",
161 "region": "us-west"},
162 "timestamp": "2009-11-10T23:00:00Z",
163 "values": {"value": 0.64}}]}
164 )
165
166 self.assertEqual(
167 json.loads(m.last_request.body),
168 {"database": "mydb",
169 "retentionPolicy": "mypolicy",
170 "points": [{"name": "cpu_load_short",
171 "tags": {"host": "server01",
172 "region": "us-west"},
173 "timestamp": "2009-11-10T23:00:00Z",
174 "values": {"value": 0.64}}]}
175 )
176
177 def test_write_points(self):
178 """Test write points for TestInfluxDBClient object."""
179 with requests_mock.Mocker() as m:
180 m.register_uri(
181 requests_mock.POST,
182 "http://localhost:8086/db/db/series"
183 )
184
185 cli = InfluxDBClient(database='db')
186 cli.write_points(
187 self.dummy_points
188 )
189
190 self.assertListEqual(
191 json.loads(m.last_request.body),
192 self.dummy_points
193 )
194
195 def test_write_points_string(self):
196 """Test write string points for TestInfluxDBClient object."""
197 with requests_mock.Mocker() as m:
198 m.register_uri(
199 requests_mock.POST,
200 "http://localhost:8086/db/db/series"
201 )
202
203 cli = InfluxDBClient(database='db')
204 cli.write_points(
205 str(json.dumps(self.dummy_points))
206 )
207
208 self.assertListEqual(
209 json.loads(m.last_request.body),
210 self.dummy_points
211 )
212
213 def test_write_points_batch(self):
214 """Test write batch points for TestInfluxDBClient object."""
215 with requests_mock.Mocker() as m:
216 m.register_uri(requests_mock.POST,
217 "http://localhost:8086/db/db/series")
218 cli = InfluxDBClient('localhost', 8086,
219 'username', 'password', 'db')
220 cli.write_points(data=self.dummy_points, batch_size=2)
221 self.assertEqual(1, m.call_count)
222
223 def test_write_points_batch_invalid_size(self):
224 """Test write batch points invalid size for TestInfluxDBClient."""
225 with requests_mock.Mocker() as m:
226 m.register_uri(requests_mock.POST,
227 "http://localhost:8086/db/db/series")
228 cli = InfluxDBClient('localhost', 8086,
229 'username', 'password', 'db')
230 cli.write_points(data=self.dummy_points, batch_size=-2)
231 self.assertEqual(1, m.call_count)
232
233 def test_write_points_batch_multiple_series(self):
234 """Test write points batch multiple series."""
235 dummy_points = [
236 {"points": [["1", 1, 1.0], ["2", 2, 2.0], ["3", 3, 3.0],
237 ["4", 4, 4.0], ["5", 5, 5.0]],
238 "name": "foo",
239 "columns": ["val1", "val2", "val3"]},
240 {"points": [["1", 1, 1.0], ["2", 2, 2.0], ["3", 3, 3.0],
241 ["4", 4, 4.0], ["5", 5, 5.0], ["6", 6, 6.0],
242 ["7", 7, 7.0], ["8", 8, 8.0]],
243 "name": "bar",
244 "columns": ["val1", "val2", "val3"]},
245 ]
246 expected_last_body = [{'points': [['7', 7, 7.0], ['8', 8, 8.0]],
247 'name': 'bar',
248 'columns': ['val1', 'val2', 'val3']}]
249 with requests_mock.Mocker() as m:
250 m.register_uri(requests_mock.POST,
251 "http://localhost:8086/db/db/series")
252 cli = InfluxDBClient('localhost', 8086,
253 'username', 'password', 'db')
254 cli.write_points(data=dummy_points, batch_size=3)
255 self.assertEqual(m.call_count, 5)
256 self.assertEqual(expected_last_body, m.request_history[4].json())
257
258 def test_write_points_udp(self):
259 """Test write points UDP for TestInfluxDBClient object."""
260 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
261 port = random.randint(4000, 8000)
262 s.bind(('0.0.0.0', port))
263
264 cli = InfluxDBClient(
265 'localhost', 8086, 'root', 'root',
266 'test', use_udp=True, udp_port=port
267 )
268 cli.write_points(self.dummy_points)
269
270 received_data, addr = s.recvfrom(1024)
271
272 self.assertEqual(self.dummy_points,
273 json.loads(received_data.decode(), strict=True))
274
275 def test_write_bad_precision_udp(self):
276 """Test write UDP w/bad precision."""
277 cli = InfluxDBClient(
278 'localhost', 8086, 'root', 'root',
279 'test', use_udp=True, udp_port=4444
280 )
281
282 with self.assertRaisesRegexp(
283 Exception,
284 "InfluxDB only supports seconds precision for udp writes"
285 ):
286 cli.write_points(
287 self.dummy_points,
288 time_precision='ms'
289 )
290
291 @raises(Exception)
292 def test_write_points_fails(self):
293 """Test failed write points for TestInfluxDBClient object."""
294 with _mocked_session('post', 500):
295 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
296 cli.write_points([])
297
298 def test_write_points_with_precision(self):
299 """Test write points with precision."""
300 with _mocked_session('post', 200, self.dummy_points):
301 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
302 self.assertTrue(cli.write_points(self.dummy_points))
303
304 def test_write_points_bad_precision(self):
305 """Test write points with bad precision."""
306 cli = InfluxDBClient()
307 with self.assertRaisesRegexp(
308 Exception,
309 "Invalid time precision is given. \(use 's', 'm', 'ms' or 'u'\)"
310 ):
311 cli.write_points(
312 self.dummy_points,
313 time_precision='g'
314 )
315
316 @raises(Exception)
317 def test_write_points_with_precision_fails(self):
318 """Test write points where precision fails."""
319 with _mocked_session('post', 500):
320 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
321 cli.write_points_with_precision([])
322
323 def test_delete_points(self):
324 """Test delete points for TestInfluxDBClient object."""
325 with _mocked_session('delete', 204) as mocked:
326 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
327 self.assertTrue(cli.delete_points("foo"))
328
329 self.assertEqual(len(mocked.call_args_list), 1)
330 args, kwds = mocked.call_args_list[0]
331
332 self.assertEqual(kwds['params'],
333 {'u': 'username', 'p': 'password'})
334 self.assertEqual(kwds['url'], 'http://host:8086/db/db/series/foo')
335
336 @raises(Exception)
337 def test_delete_points_with_wrong_name(self):
338 """Test delete points with wrong name."""
339 with _mocked_session('delete', 400):
340 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
341 cli.delete_points("nonexist")
342
343 @raises(NotImplementedError)
344 def test_create_scheduled_delete(self):
345 """Test create scheduled deletes."""
346 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
347 cli.create_scheduled_delete([])
348
349 @raises(NotImplementedError)
350 def test_get_list_scheduled_delete(self):
351 """Test get schedule list of deletes TestInfluxDBClient."""
352 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
353 cli.get_list_scheduled_delete()
354
355 @raises(NotImplementedError)
356 def test_remove_scheduled_delete(self):
357 """Test remove scheduled delete TestInfluxDBClient."""
358 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
359 cli.remove_scheduled_delete(1)
360
361 def test_query(self):
362 """Test query for TestInfluxDBClient object."""
363 data = [
364 {
365 "name": "foo",
366 "columns": ["time", "sequence_number", "column_one"],
367 "points": [
368 [1383876043, 16, "2"], [1383876043, 15, "1"],
369 [1383876035, 14, "2"], [1383876035, 13, "1"]
370 ]
371 }
372 ]
373 with _mocked_session('get', 200, data):
374 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
375 result = cli.query('select column_one from foo;')
376 self.assertEqual(len(result[0]['points']), 4)
377
378 def test_query_chunked(self):
379 """Test chunked query for TestInfluxDBClient object."""
380 cli = InfluxDBClient(database='db')
381 example_object = {
382 'points': [
383 [1415206250119, 40001, 667],
384 [1415206244555, 30001, 7],
385 [1415206228241, 20001, 788],
386 [1415206212980, 10001, 555],
387 [1415197271586, 10001, 23]
388 ],
389 'name': 'foo',
390 'columns': [
391 'time',
392 'sequence_number',
393 'val'
394 ]
395 }
396 example_response = \
397 json.dumps(example_object) + json.dumps(example_object)
398
399 with requests_mock.Mocker() as m:
400 m.register_uri(
401 requests_mock.GET,
402 "http://localhost:8086/db/db/series",
403 text=example_response
404 )
405
406 self.assertListEqual(
407 cli.query('select * from foo', chunked=True),
408 [example_object, example_object]
409 )
410
411 def test_query_chunked_unicode(self):
412 """Test unicode chunked query for TestInfluxDBClient object."""
413 cli = InfluxDBClient(database='db')
414 example_object = {
415 'points': [
416 [1415206212980, 10001, u('unicode-\xcf\x89')],
417 [1415197271586, 10001, u('more-unicode-\xcf\x90')]
418 ],
419 'name': 'foo',
420 'columns': [
421 'time',
422 'sequence_number',
423 'val'
424 ]
425 }
426 example_response = \
427 json.dumps(example_object) + json.dumps(example_object)
428
429 with requests_mock.Mocker() as m:
430 m.register_uri(
431 requests_mock.GET,
432 "http://localhost:8086/db/db/series",
433 text=example_response
434 )
435
436 self.assertListEqual(
437 cli.query('select * from foo', chunked=True),
438 [example_object, example_object]
439 )
440
441 @raises(Exception)
442 def test_query_fail(self):
443 """Test failed query for TestInfluxDBClient."""
444 with _mocked_session('get', 401):
445 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
446 cli.query('select column_one from foo;')
447
448 def test_query_bad_precision(self):
449 """Test query with bad precision for TestInfluxDBClient."""
450 cli = InfluxDBClient()
451 with self.assertRaisesRegexp(
452 Exception,
453 "Invalid time precision is given. \(use 's', 'm', 'ms' or 'u'\)"
454 ):
455 cli.query('select column_one from foo', time_precision='g')
456
457 def test_create_database(self):
458 """Test create database for TestInfluxDBClient."""
459 with _mocked_session('post', 201, {"name": "new_db"}):
460 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
461 self.assertTrue(cli.create_database('new_db'))
462
463 @raises(Exception)
464 def test_create_database_fails(self):
465 """Test failed create database for TestInfluxDBClient."""
466 with _mocked_session('post', 401):
467 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
468 cli.create_database('new_db')
469
470 def test_delete_database(self):
471 """Test delete database for TestInfluxDBClient."""
472 with _mocked_session('delete', 204):
473 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
474 self.assertTrue(cli.delete_database('old_db'))
475
476 @raises(Exception)
477 def test_delete_database_fails(self):
478 """Test failed delete database for TestInfluxDBClient."""
479 with _mocked_session('delete', 401):
480 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
481 cli.delete_database('old_db')
482
483 def test_get_list_database(self):
484 """Test get list of databases for TestInfluxDBClient."""
485 data = [
486 {"name": "a_db"}
487 ]
488 with _mocked_session('get', 200, data):
489 cli = InfluxDBClient('host', 8086, 'username', 'password')
490 self.assertEqual(len(cli.get_list_database()), 1)
491 self.assertEqual(cli.get_list_database()[0]['name'], 'a_db')
492
493 @raises(Exception)
494 def test_get_list_database_fails(self):
495 """Test failed get list of databases for TestInfluxDBClient."""
496 with _mocked_session('get', 401):
497 cli = InfluxDBClient('host', 8086, 'username', 'password')
498 cli.get_list_database()
499
500 @raises(FutureWarning)
501 def test_get_database_list_deprecated(self):
502 """Test deprecated get database list for TestInfluxDBClient."""
503 data = [
504 {"name": "a_db"}
505 ]
506 with _mocked_session('get', 200, data):
507 cli = InfluxDBClient('host', 8086, 'username', 'password')
508 self.assertEqual(len(cli.get_database_list()), 1)
509 self.assertEqual(cli.get_database_list()[0]['name'], 'a_db')
510
511 def test_delete_series(self):
512 """Test delete series for TestInfluxDBClient."""
513 with _mocked_session('delete', 204):
514 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
515 cli.delete_series('old_series')
516
517 @raises(Exception)
518 def test_delete_series_fails(self):
519 """Test failed delete series for TestInfluxDBClient."""
520 with _mocked_session('delete', 401):
521 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
522 cli.delete_series('old_series')
523
524 def test_get_series_list(self):
525 """Test get list of series for TestInfluxDBClient."""
526 cli = InfluxDBClient(database='db')
527
528 with requests_mock.Mocker() as m:
529 example_response = \
530 '[{"name":"list_series_result","columns":' \
531 '["time","name"],"points":[[0,"foo"],[0,"bar"]]}]'
532
533 m.register_uri(
534 requests_mock.GET,
535 "http://localhost:8086/db/db/series",
536 text=example_response
537 )
538
539 self.assertListEqual(
540 cli.get_list_series(),
541 ['foo', 'bar']
542 )
543
544 def test_get_continuous_queries(self):
545 """Test get continuous queries for TestInfluxDBClient."""
546 cli = InfluxDBClient(database='db')
547
548 with requests_mock.Mocker() as m:
549
550 # Tip: put this in a json linter!
551 example_response = '[ { "name": "continuous queries", "columns"' \
552 ': [ "time", "id", "query" ], "points": [ [ ' \
553 '0, 1, "select foo(bar,95) from \\"foo_bar' \
554 's\\" group by time(5m) into response_times.' \
555 'percentiles.5m.95" ], [ 0, 2, "select perce' \
556 'ntile(value,95) from \\"response_times\\" g' \
557 'roup by time(5m) into response_times.percen' \
558 'tiles.5m.95" ] ] } ]'
559
560 m.register_uri(
561 requests_mock.GET,
562 "http://localhost:8086/db/db/series",
563 text=example_response
564 )
565
566 self.assertListEqual(
567 cli.get_list_continuous_queries(),
568 [
569 'select foo(bar,95) from "foo_bars" group '
570 'by time(5m) into response_times.percentiles.5m.95',
571
572 'select percentile(value,95) from "response_times" group '
573 'by time(5m) into response_times.percentiles.5m.95'
574 ]
575 )
576
577 def test_get_list_cluster_admins(self):
578 """Test get list of cluster admins, not implemented."""
579 pass
580
581 def test_add_cluster_admin(self):
582 """Test add cluster admin for TestInfluxDBClient."""
583 with requests_mock.Mocker() as m:
584 m.register_uri(
585 requests_mock.POST,
586 "http://localhost:8086/cluster_admins"
587 )
588
589 cli = InfluxDBClient(database='db')
590 cli.add_cluster_admin(
591 new_username='paul',
592 new_password='laup'
593 )
594
595 self.assertDictEqual(
596 json.loads(m.last_request.body),
597 {
598 'name': 'paul',
599 'password': 'laup'
600 }
601 )
602
603 def test_update_cluster_admin_password(self):
604 """Test update cluster admin pass for TestInfluxDBClient."""
605 with requests_mock.Mocker() as m:
606 m.register_uri(
607 requests_mock.POST,
608 "http://localhost:8086/cluster_admins/paul"
609 )
610
611 cli = InfluxDBClient(database='db')
612 cli.update_cluster_admin_password(
613 username='paul',
614 new_password='laup'
615 )
616
617 self.assertDictEqual(
618 json.loads(m.last_request.body),
619 {'password': 'laup'}
620 )
621
622 def test_delete_cluster_admin(self):
623 """Test delete cluster admin for TestInfluxDBClient."""
624 with requests_mock.Mocker() as m:
625 m.register_uri(
626 requests_mock.DELETE,
627 "http://localhost:8086/cluster_admins/paul",
628 status_code=200,
629 )
630
631 cli = InfluxDBClient(database='db')
632 cli.delete_cluster_admin(username='paul')
633
634 self.assertIsNone(m.last_request.body)
635
636 def test_set_database_admin(self):
637 """Test set database admin for TestInfluxDBClient."""
638 pass
639
640 def test_unset_database_admin(self):
641 """Test unset database admin for TestInfluxDBClient."""
642 pass
643
644 def test_alter_database_admin(self):
645 """Test alter database admin for TestInfluxDBClient."""
646 with requests_mock.Mocker() as m:
647 m.register_uri(
648 requests_mock.POST,
649 "http://localhost:8086/db/db/users/paul"
650 )
651
652 cli = InfluxDBClient(database='db')
653 cli.alter_database_admin(
654 username='paul',
655 is_admin=False
656 )
657
658 self.assertDictEqual(
659 json.loads(m.last_request.body),
660 {
661 'admin': False
662 }
663 )
664
665 @raises(NotImplementedError)
666 def test_get_list_database_admins(self):
667 """Test get list of database admins for TestInfluxDBClient."""
668 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
669 cli.get_list_database_admins()
670
671 @raises(NotImplementedError)
672 def test_add_database_admin(self):
673 """Test add database admins for TestInfluxDBClient."""
674 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
675 cli.add_database_admin('admin', 'admin_secret_password')
676
677 @raises(NotImplementedError)
678 def test_update_database_admin_password(self):
679 """Test update database admin pass for TestInfluxDBClient."""
680 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
681 cli.update_database_admin_password('admin', 'admin_secret_password')
682
683 @raises(NotImplementedError)
684 def test_delete_database_admin(self):
685 """Test delete database admin for TestInfluxDBClient."""
686 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
687 cli.delete_database_admin('admin')
688
689 def test_get_database_users(self):
690 """Test get database users for TestInfluxDBClient."""
691 cli = InfluxDBClient('localhost', 8086, 'username', 'password', 'db')
692
693 example_response = \
694 '[{"name":"paul","isAdmin":false,"writeTo":".*","readFrom":".*"},'\
695 '{"name":"bobby","isAdmin":false,"writeTo":".*","readFrom":".*"}]'
696
697 with requests_mock.Mocker() as m:
698 m.register_uri(
699 requests_mock.GET,
700 "http://localhost:8086/db/db/users",
701 text=example_response
702 )
703 users = cli.get_database_users()
704
705 self.assertEqual(json.loads(example_response), users)
706
707 def test_add_database_user(self):
708 """Test add database user for TestInfluxDBClient."""
709 with requests_mock.Mocker() as m:
710 m.register_uri(
711 requests_mock.POST,
712 "http://localhost:8086/db/db/users"
713 )
714 cli = InfluxDBClient(database='db')
715 cli.add_database_user(
716 new_username='paul',
717 new_password='laup',
718 permissions=('.*', '.*')
719 )
720
721 self.assertDictEqual(
722 json.loads(m.last_request.body),
723 {
724 'writeTo': '.*',
725 'password': 'laup',
726 'readFrom': '.*',
727 'name': 'paul'
728 }
729 )
730
731 def test_add_database_user_bad_permissions(self):
732 """Test add database user with bad perms for TestInfluxDBClient."""
733 cli = InfluxDBClient()
734
735 with self.assertRaisesRegexp(
736 Exception,
737 "'permissions' must be \(readFrom, writeTo\) tuple"
738 ):
739 cli.add_database_user(
740 new_password='paul',
741 new_username='paul',
742 permissions=('hello', 'hello', 'hello')
743 )
744
745 def test_alter_database_user_password(self):
746 """Test alter database user pass for TestInfluxDBClient."""
747 with requests_mock.Mocker() as m:
748 m.register_uri(
749 requests_mock.POST,
750 "http://localhost:8086/db/db/users/paul"
751 )
752
753 cli = InfluxDBClient(database='db')
754 cli.alter_database_user(
755 username='paul',
756 password='n3wp4ss!'
757 )
758
759 self.assertDictEqual(
760 json.loads(m.last_request.body),
761 {
762 'password': 'n3wp4ss!'
763 }
764 )
765
766 def test_alter_database_user_permissions(self):
767 """Test alter database user perms for TestInfluxDBClient."""
768 with requests_mock.Mocker() as m:
769 m.register_uri(
770 requests_mock.POST,
771 "http://localhost:8086/db/db/users/paul"
772 )
773
774 cli = InfluxDBClient(database='db')
775 cli.alter_database_user(
776 username='paul',
777 permissions=('^$', '.*')
778 )
779
780 self.assertDictEqual(
781 json.loads(m.last_request.body),
782 {
783 'readFrom': '^$',
784 'writeTo': '.*'
785 }
786 )
787
788 def test_alter_database_user_password_and_permissions(self):
789 """Test alter database user pass and perms for TestInfluxDBClient."""
790 with requests_mock.Mocker() as m:
791 m.register_uri(
792 requests_mock.POST,
793 "http://localhost:8086/db/db/users/paul"
794 )
795
796 cli = InfluxDBClient(database='db')
797 cli.alter_database_user(
798 username='paul',
799 password='n3wp4ss!',
800 permissions=('^$', '.*')
801 )
802
803 self.assertDictEqual(
804 json.loads(m.last_request.body),
805 {
806 'password': 'n3wp4ss!',
807 'readFrom': '^$',
808 'writeTo': '.*'
809 }
810 )
811
812 def test_update_database_user_password_current_user(self):
813 """Test update database user pass for TestInfluxDBClient."""
814 cli = InfluxDBClient(
815 username='root',
816 password='hello',
817 database='database'
818 )
819 with requests_mock.Mocker() as m:
820 m.register_uri(
821 requests_mock.POST,
822 "http://localhost:8086/db/database/users/root"
823 )
824
825 cli.update_database_user_password(
826 username='root',
827 new_password='bye'
828 )
829
830 self.assertEqual(cli._password, 'bye')
831
832 def test_delete_database_user(self):
833 """Test delete database user for TestInfluxDBClient."""
834 with requests_mock.Mocker() as m:
835 m.register_uri(
836 requests_mock.DELETE,
837 "http://localhost:8086/db/db/users/paul"
838 )
839
840 cli = InfluxDBClient(database='db')
841 cli.delete_database_user(username='paul')
842
843 self.assertIsNone(m.last_request.body)
844
845 @raises(NotImplementedError)
846 def test_update_permission(self):
847 """Test update permission for TestInfluxDBClient."""
848 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
849 cli.update_permission('admin', [])
850
851 @mock.patch('requests.Session.request')
852 def test_request_retry(self, mock_request):
853 """Test that two connection errors will be handled."""
854 class CustomMock(object):
855 """Define CustomMock object."""
856
857 def __init__(self):
858 self.i = 0
859
860 def connection_error(self, *args, **kwargs):
861 """Test connection error in CustomMock."""
862 self.i += 1
863
864 if self.i < 3:
865 raise requests.exceptions.ConnectionError
866 else:
867 r = requests.Response()
868 r.status_code = 200
869 return r
870
871 mock_request.side_effect = CustomMock().connection_error
872
873 cli = InfluxDBClient(database='db')
874 cli.write_points(
875 self.dummy_points
876 )
877
878 @mock.patch('requests.Session.request')
879 def test_request_retry_raises(self, mock_request):
880 """Test that three connection errors will not be handled."""
881 class CustomMock(object):
882 """Define CustomMock object."""
883
884 def __init__(self):
885 """Initialize the object."""
886 self.i = 0
887
888 def connection_error(self, *args, **kwargs):
889 """Test the connection error for CustomMock."""
890 self.i += 1
891
892 if self.i < 4:
893 raise requests.exceptions.ConnectionError
894 else:
895 r = requests.Response()
896 r.status_code = 200
897 return r
898
899 mock_request.side_effect = CustomMock().connection_error
900
901 cli = InfluxDBClient(database='db')
902
903 with self.assertRaises(requests.exceptions.ConnectionError):
904 cli.write_points(self.dummy_points)