Debian Codegraph @

influxdb/tests/client_test.py

raw ◀ ▶
4 Debian patches touch this file
1 # -*- coding: utf-8 -*-
2 """Unit tests for the InfluxDBClient.
3
4 NB/WARNING:
5 This module implements tests for the InfluxDBClient class
6 but does so
7 + without any server instance running
8 + by mocking all the expected responses.
9
10 So any change of (response format from) the server will **NOT** be
11 detected by this module.
12
13 See client_test_with_server.py for tests against a running server instance.
14
15 """
16
17 from __future__ import absolute_import
18 from __future__ import division
19 from __future__ import print_function
20 from __future__ import unicode_literals
21
22 import random
23 import socket
24 import unittest
25 import warnings
26
27 import io
28 import gzip
29 import json
•30 from unittest import mock
31 import requests
32 import requests.exceptions
33 import requests_mock
34
•35 from functools import wraps
36
37 def raises(*exceptions):
38 valid = ' or '.join([e.__name__ for e in exceptions])
39
40 def decorate(func):
41 name = func.__name__
42 def newfunc(*arg, **kw):
43 try:
44 func(*arg, **kw)
45 except exceptions:
46 pass
47 except:
48 raise
49 else:
50 message = "%s() did not raise %s" % (name, valid)
51 raise AssertionError(message)
52 newfunc = wraps(func)(newfunc)
53 return newfunc
54 return decorate
55
56 from urllib3.connection import HTTPConnection
57
58 from influxdb import InfluxDBClient
59 from influxdb.resultset import ResultSet
60
61
62 def _build_response_object(status_code=200, content=""):
63 resp = requests.Response()
64 resp.status_code = status_code
65 resp._content = content.encode("utf8")
66 return resp
67
68
69 def _mocked_session(cli, method="GET", status_code=200, content=""):
70 method = method.upper()
71
72 def request(*args, **kwargs):
73 """Request content from the mocked session."""
74 c = content
75
76 # Check method
77 assert method == kwargs.get('method', 'GET')
78
79 if method == 'POST':
80 data = kwargs.get('data', None)
81
82 if data is not None:
83 # Data must be a string
84 assert isinstance(data, str)
85
86 # Data must be a JSON string
87 assert c == json.loads(data, strict=True)
88
89 c = data
90
91 # Anyway, Content must be a JSON string (or empty string)
92 if not isinstance(c, str):
93 c = json.dumps(c)
94
95 return _build_response_object(status_code=status_code, content=c)
96
97 return mock.patch.object(cli._session, 'request', side_effect=request)
98
99
100 class TestInfluxDBClient(unittest.TestCase):
101 """Set up the TestInfluxDBClient object."""
102
103 def setUp(self):
104 """Initialize an instance of TestInfluxDBClient object."""
105 # By default, raise exceptions on warnings
106 warnings.simplefilter('error', FutureWarning)
107
108 self.cli = InfluxDBClient('localhost', 8086, 'username', 'password')
109 self.dummy_points = [
110 {
111 "measurement": "cpu_load_short",
112 "tags": {
113 "host": "server01",
114 "region": "us-west"
115 },
116 "time": "2009-11-10T23:00:00.123456Z",
117 "fields": {
118 "value": 0.64
119 }
120 }
121 ]
122
123 self.dsn_string = 'influxdb://uSr:[email protected]:1886/db'
124
125 def test_scheme(self):
126 """Set up the test schema for TestInfluxDBClient object."""
127 cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
128 self.assertEqual('http://host:8086', cli._baseurl)
129
130 cli = InfluxDBClient(
131 'host', 8086, 'username', 'password', 'database', ssl=True
132 )
133 self.assertEqual('https://host:8086', cli._baseurl)
134
135 cli = InfluxDBClient(
136 'host', 8086, 'username', 'password', 'database', ssl=True,
137 path="somepath"
138 )
139 self.assertEqual('https://host:8086/somepath', cli._baseurl)
140
141 cli = InfluxDBClient(
142 'host', 8086, 'username', 'password', 'database', ssl=True,
143 path=None
144 )
145 self.assertEqual('https://host:8086', cli._baseurl)
146
147 cli = InfluxDBClient(
148 'host', 8086, 'username', 'password', 'database', ssl=True,
149 path="/somepath"
150 )
151 self.assertEqual('https://host:8086/somepath', cli._baseurl)
152
153 def test_dsn(self):
154 """Set up the test datasource name for TestInfluxDBClient object."""
155 cli = InfluxDBClient.from_dsn('influxdb://192.168.0.1:1886')
156 self.assertEqual('http://192.168.0.1:1886', cli._baseurl)
157
158 cli = InfluxDBClient.from_dsn(self.dsn_string)
159 self.assertEqual('http://my.host.fr:1886', cli._baseurl)
160 self.assertEqual('uSr', cli._username)
161 self.assertEqual('pWd', cli._password)
162 self.assertEqual('db', cli._database)
163 self.assertFalse(cli._use_udp)
164
165 cli = InfluxDBClient.from_dsn('udp+' + self.dsn_string)
166 self.assertTrue(cli._use_udp)
167
168 cli = InfluxDBClient.from_dsn('https+' + self.dsn_string)
169 self.assertEqual('https://my.host.fr:1886', cli._baseurl)
170
171 cli = InfluxDBClient.from_dsn('https+' + self.dsn_string,
172 **{'ssl': False})
173 self.assertEqual('http://my.host.fr:1886', cli._baseurl)
174
175 def test_cert(self):
176 """Test mutual TLS authentication for TestInfluxDBClient object."""
177 cli = InfluxDBClient(ssl=True, cert='/etc/pki/tls/private/dummy.crt')
178 self.assertEqual(cli._session.cert, '/etc/pki/tls/private/dummy.crt')
179
180 with self.assertRaises(ValueError):
181 cli = InfluxDBClient(cert='/etc/pki/tls/private/dummy.crt')
182
183 def test_switch_database(self):
184 """Test switch database in TestInfluxDBClient object."""
185 cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
186 cli.switch_database('another_database')
187 self.assertEqual('another_database', cli._database)
188
189 def test_switch_user(self):
190 """Test switch user in TestInfluxDBClient object."""
191 cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
192 cli.switch_user('another_username', 'another_password')
193 self.assertEqual('another_username', cli._username)
194 self.assertEqual('another_password', cli._password)
195
196 def test_write(self):
197 """Test write in TestInfluxDBClient object."""
198 with requests_mock.Mocker() as m:
199 m.register_uri(
200 requests_mock.POST,
201 "http://localhost:8086/write",
202 status_code=204
203 )
204 cli = InfluxDBClient(database='db')
205 cli.write(
206 {"database": "mydb",
207 "retentionPolicy": "mypolicy",
208 "points": [{"measurement": "cpu_load_short",
209 "tags": {"host": "server01",
210 "region": "us-west"},
211 "time": "2009-11-10T23:00:00Z",
212 "fields": {"value": 0.64}}]}
213 )
214
215 self.assertEqual(
216 m.last_request.body,
217 b"cpu_load_short,host=server01,region=us-west "
218 b"value=0.64 1257894000000000000\n",
219 )
220
221 def test_write_points(self):
222 """Test write points for TestInfluxDBClient object."""
223 with requests_mock.Mocker() as m:
224 m.register_uri(
225 requests_mock.POST,
226 "http://localhost:8086/write",
227 status_code=204
228 )
229
230 cli = InfluxDBClient(database='db')
231 cli.write_points(
232 self.dummy_points,
233 )
234 self.assertEqual(
235 'cpu_load_short,host=server01,region=us-west '
236 'value=0.64 1257894000123456000\n',
237 m.last_request.body.decode('utf-8'),
238 )
239
240 def test_write_gzip(self):
241 """Test write in TestInfluxDBClient object."""
242 with requests_mock.Mocker() as m:
243 m.register_uri(
244 requests_mock.POST,
245 "http://localhost:8086/write",
246 status_code=204
247 )
248
249 cli = InfluxDBClient(database='db', gzip=True)
250 cli.write(
251 {"database": "mydb",
252 "retentionPolicy": "mypolicy",
253 "points": [{"measurement": "cpu_load_short",
254 "tags": {"host": "server01",
255 "region": "us-west"},
256 "time": "2009-11-10T23:00:00Z",
257 "fields": {"value": 0.64}}]}
258 )
259
260 compressed = io.BytesIO()
261 with gzip.GzipFile(
262 compresslevel=9,
263 fileobj=compressed,
264 mode='w'
265 ) as f:
266 f.write(
267 b"cpu_load_short,host=server01,region=us-west "
268 b"value=0.64 1257894000000000000\n"
269 )
270
271 self.assertEqual(
272 m.last_request.body,
273 compressed.getvalue(),
274 )
275
276 def test_write_points_gzip(self):
277 """Test write points for TestInfluxDBClient object."""
278 with requests_mock.Mocker() as m:
279 m.register_uri(
280 requests_mock.POST,
281 "http://localhost:8086/write",
282 status_code=204
283 )
284
285 cli = InfluxDBClient(database='db', gzip=True)
286 cli.write_points(
287 self.dummy_points,
288 )
289
290 compressed = io.BytesIO()
291 with gzip.GzipFile(
292 compresslevel=9,
293 fileobj=compressed,
294 mode='w'
295 ) as f:
296 f.write(
297 b'cpu_load_short,host=server01,region=us-west '
298 b'value=0.64 1257894000123456000\n'
299 )
300 self.assertEqual(
301 m.last_request.body,
302 compressed.getvalue(),
303 )
304
305 def test_write_points_toplevel_attributes(self):
306 """Test write points attrs for TestInfluxDBClient object."""
307 with requests_mock.Mocker() as m:
308 m.register_uri(
309 requests_mock.POST,
310 "http://localhost:8086/write",
311 status_code=204
312 )
313
314 cli = InfluxDBClient(database='db')
315 cli.write_points(
316 self.dummy_points,
317 database='testdb',
318 tags={"tag": "hello"},
319 retention_policy="somepolicy"
320 )
321 self.assertEqual(
322 'cpu_load_short,host=server01,region=us-west,tag=hello '
323 'value=0.64 1257894000123456000\n',
324 m.last_request.body.decode('utf-8'),
325 )
326
327 def test_write_points_batch(self):
328 """Test write points batch for TestInfluxDBClient object."""
329 dummy_points = [
330 {"measurement": "cpu_usage", "tags": {"unit": "percent"},
331 "time": "2009-11-10T23:00:00Z", "fields": {"value": 12.34}},
332 {"measurement": "network", "tags": {"direction": "in"},
333 "time": "2009-11-10T23:00:00Z", "fields": {"value": 123.00}},
334 {"measurement": "network", "tags": {"direction": "out"},
335 "time": "2009-11-10T23:00:00Z", "fields": {"value": 12.00}}
336 ]
337 expected_last_body = (
338 "network,direction=out,host=server01,region=us-west "
339 "value=12.0 1257894000000000000\n"
340 )
341
342 with requests_mock.Mocker() as m:
343 m.register_uri(requests_mock.POST,
344 "http://localhost:8086/write",
345 status_code=204)
346 cli = InfluxDBClient(database='db')
347 cli.write_points(points=dummy_points,
348 database='db',
349 tags={"host": "server01",
350 "region": "us-west"},
351 batch_size=2)
352 self.assertEqual(m.call_count, 2)
353 self.assertEqual(expected_last_body,
354 m.last_request.body.decode('utf-8'))
355
356 def test_write_points_batch_generator(self):
357 """Test write points batch from a generator for TestInfluxDBClient."""
358 dummy_points = [
359 {"measurement": "cpu_usage", "tags": {"unit": "percent"},
360 "time": "2009-11-10T23:00:00Z", "fields": {"value": 12.34}},
361 {"measurement": "network", "tags": {"direction": "in"},
362 "time": "2009-11-10T23:00:00Z", "fields": {"value": 123.00}},
363 {"measurement": "network", "tags": {"direction": "out"},
364 "time": "2009-11-10T23:00:00Z", "fields": {"value": 12.00}}
365 ]
366 dummy_points_generator = (point for point in dummy_points)
367 expected_last_body = (
368 "network,direction=out,host=server01,region=us-west "
369 "value=12.0 1257894000000000000\n"
370 )
371
372 with requests_mock.Mocker() as m:
373 m.register_uri(requests_mock.POST,
374 "http://localhost:8086/write",
375 status_code=204)
376 cli = InfluxDBClient(database='db')
377 cli.write_points(points=dummy_points_generator,
378 database='db',
379 tags={"host": "server01",
380 "region": "us-west"},
381 batch_size=2)
382 self.assertEqual(m.call_count, 2)
383 self.assertEqual(expected_last_body,
384 m.last_request.body.decode('utf-8'))
385
386 def test_write_points_udp(self):
387 """Test write points UDP for TestInfluxDBClient object."""
388 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
389 port = random.randint(4000, 8000)
390 s.bind(('0.0.0.0', port))
391
392 cli = InfluxDBClient(
393 'localhost', 8086, 'root', 'root',
394 'test', use_udp=True, udp_port=port
395 )
396 cli.write_points(self.dummy_points)
397
398 received_data, addr = s.recvfrom(1024)
399
400 self.assertEqual(
401 'cpu_load_short,host=server01,region=us-west '
402 'value=0.64 1257894000123456000\n',
403 received_data.decode()
404 )
405
406 @raises(Exception)
407 def test_write_points_fails(self):
408 """Test write points fail for TestInfluxDBClient object."""
409 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
410 with _mocked_session(cli, 'post', 500):
411 cli.write_points([])
412
413 def test_write_points_with_precision(self):
414 """Test write points with precision for TestInfluxDBClient object."""
415 with requests_mock.Mocker() as m:
416 m.register_uri(
417 requests_mock.POST,
418 "http://localhost:8086/write",
419 status_code=204
420 )
421
422 cli = InfluxDBClient(database='db')
423
424 cli.write_points(self.dummy_points, time_precision='n')
425 self.assertEqual(
426 b'cpu_load_short,host=server01,region=us-west '
427 b'value=0.64 1257894000123456000\n',
428 m.last_request.body,
429 )
430
431 cli.write_points(self.dummy_points, time_precision='u')
432 self.assertEqual(
433 b'cpu_load_short,host=server01,region=us-west '
434 b'value=0.64 1257894000123456\n',
435 m.last_request.body,
436 )
437
438 cli.write_points(self.dummy_points, time_precision='ms')
439 self.assertEqual(
440 b'cpu_load_short,host=server01,region=us-west '
441 b'value=0.64 1257894000123\n',
442 m.last_request.body,
443 )
444
445 cli.write_points(self.dummy_points, time_precision='s')
446 self.assertEqual(
447 b"cpu_load_short,host=server01,region=us-west "
448 b"value=0.64 1257894000\n",
449 m.last_request.body,
450 )
451
452 cli.write_points(self.dummy_points, time_precision='m')
453 self.assertEqual(
454 b'cpu_load_short,host=server01,region=us-west '
455 b'value=0.64 20964900\n',
456 m.last_request.body,
457 )
458
459 cli.write_points(self.dummy_points, time_precision='h')
460 self.assertEqual(
461 b'cpu_load_short,host=server01,region=us-west '
462 b'value=0.64 349415\n',
463 m.last_request.body,
464 )
465
466 def test_write_points_with_consistency(self):
467 """Test write points with consistency for TestInfluxDBClient object."""
468 with requests_mock.Mocker() as m:
469 m.register_uri(
470 requests_mock.POST,
471 'http://localhost:8086/write',
472 status_code=204
473 )
474
475 cli = InfluxDBClient(database='db')
476
477 cli.write_points(self.dummy_points, consistency='any')
478 self.assertEqual(
479 m.last_request.qs,
480 {'db': ['db'], 'consistency': ['any']}
481 )
482
483 def test_write_points_with_precision_udp(self):
484 """Test write points with precision for TestInfluxDBClient object."""
485 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
486 port = random.randint(4000, 8000)
487 s.bind(('0.0.0.0', port))
488
489 cli = InfluxDBClient(
490 'localhost', 8086, 'root', 'root',
491 'test', use_udp=True, udp_port=port
492 )
493
494 cli.write_points(self.dummy_points, time_precision='n')
495 received_data, addr = s.recvfrom(1024)
496 self.assertEqual(
497 b'cpu_load_short,host=server01,region=us-west '
498 b'value=0.64 1257894000123456000\n',
499 received_data,
500 )
501
502 cli.write_points(self.dummy_points, time_precision='u')
503 received_data, addr = s.recvfrom(1024)
504 self.assertEqual(
505 b'cpu_load_short,host=server01,region=us-west '
506 b'value=0.64 1257894000123456\n',
507 received_data,
508 )
509
510 cli.write_points(self.dummy_points, time_precision='ms')
511 received_data, addr = s.recvfrom(1024)
512 self.assertEqual(
513 b'cpu_load_short,host=server01,region=us-west '
514 b'value=0.64 1257894000123\n',
515 received_data,
516 )
517
518 cli.write_points(self.dummy_points, time_precision='s')
519 received_data, addr = s.recvfrom(1024)
520 self.assertEqual(
521 b"cpu_load_short,host=server01,region=us-west "
522 b"value=0.64 1257894000\n",
523 received_data,
524 )
525
526 cli.write_points(self.dummy_points, time_precision='m')
527 received_data, addr = s.recvfrom(1024)
528 self.assertEqual(
529 b'cpu_load_short,host=server01,region=us-west '
530 b'value=0.64 20964900\n',
531 received_data,
532 )
533
534 cli.write_points(self.dummy_points, time_precision='h')
535 received_data, addr = s.recvfrom(1024)
536 self.assertEqual(
537 b'cpu_load_short,host=server01,region=us-west '
538 b'value=0.64 349415\n',
539 received_data,
540 )
541
542 def test_write_points_bad_precision(self):
543 """Test write points w/bad precision TestInfluxDBClient object."""
544 cli = InfluxDBClient()
•545 with self.assertRaisesRegex(
546 Exception,
•547 r"Invalid time precision is given. "
548 r"\(use 'n', 'u', 'ms', 's', 'm' or 'h'\)"
549 ):
550 cli.write_points(
551 self.dummy_points,
552 time_precision='g'
553 )
554
555 def test_write_points_bad_consistency(self):
556 """Test write points w/bad consistency value."""
557 cli = InfluxDBClient()
558 with self.assertRaises(ValueError):
559 cli.write_points(
560 self.dummy_points,
561 consistency='boo'
562 )
563
564 @raises(Exception)
565 def test_write_points_with_precision_fails(self):
566 """Test write points w/precision fail for TestInfluxDBClient object."""
567 cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
568 with _mocked_session(cli, 'post', 500):
569 cli.write_points_with_precision([])
570
571 def test_query(self):
572 """Test query method for TestInfluxDBClient object."""
573 example_response = (
574 '{"results": [{"series": [{"measurement": "sdfsdfsdf", '
575 '"columns": ["time", "value"], "values": '
576 '[["2009-11-10T23:00:00Z", 0.64]]}]}, {"series": '
577 '[{"measurement": "cpu_load_short", "columns": ["time", "value"], '
578 '"values": [["2009-11-10T23:00:00Z", 0.64]]}]}]}'
579 )
580
581 with requests_mock.Mocker() as m:
582 m.register_uri(
583 requests_mock.GET,
584 "http://localhost:8086/query",
585 text=example_response
586 )
587 rs = self.cli.query('select * from foo')
588
589 self.assertListEqual(
590 list(rs[0].get_points()),
591 [{'value': 0.64, 'time': '2009-11-10T23:00:00Z'}]
592 )
593
594 def test_query_msgpack(self):
595 """Test query method with a messagepack response."""
596 example_response = bytes(bytearray.fromhex(
597 "81a7726573756c74739182ac73746174656d656e745f696400a673657269"
598 "65739183a46e616d65a161a7636f6c756d6e7392a474696d65a176a67661"
599 "6c7565739192c70c05000000005d26178a019096c8cb3ff0000000000000"
600 ))
601
602 with requests_mock.Mocker() as m:
603 m.register_uri(
604 requests_mock.GET,
605 "http://localhost:8086/query",
606 request_headers={"Accept": "application/x-msgpack"},
607 headers={"Content-Type": "application/x-msgpack"},
608 content=example_response
609 )
610 rs = self.cli.query('select * from a')
611
612 self.assertListEqual(
613 list(rs.get_points()),
614 [{'v': 1.0, 'time': '2019-07-10T16:51:22.026253Z'}]
615 )
616
617 def test_select_into_post(self):
618 """Test SELECT.*INTO is POSTed."""
619 example_response = (
620 '{"results": [{"series": [{"measurement": "sdfsdfsdf", '
621 '"columns": ["time", "value"], "values": '
622 '[["2009-11-10T23:00:00Z", 0.64]]}]}, {"series": '
623 '[{"measurement": "cpu_load_short", "columns": ["time", "value"], '
624 '"values": [["2009-11-10T23:00:00Z", 0.64]]}]}]}'
625 )
626
627 with requests_mock.Mocker() as m:
628 m.register_uri(
629 requests_mock.POST,
630 "http://localhost:8086/query",
631 text=example_response
632 )
633 rs = self.cli.query('select * INTO newmeas from foo')
634
635 self.assertListEqual(
636 list(rs[0].get_points()),
637 [{'value': 0.64, 'time': '2009-11-10T23:00:00Z'}]
638 )
639
640 @unittest.skip('Not implemented for 0.9')
641 def test_query_chunked(self):
642 """Test chunked query for TestInfluxDBClient object."""
643 cli = InfluxDBClient(database='db')
644 example_object = {
645 'points': [
646 [1415206250119, 40001, 667],
647 [1415206244555, 30001, 7],
648 [1415206228241, 20001, 788],
649 [1415206212980, 10001, 555],
650 [1415197271586, 10001, 23]
651 ],
652 'measurement': 'foo',
653 'columns': [
654 'time',
655 'sequence_number',
656 'val'
657 ]
658 }
659 example_response = \
660 json.dumps(example_object) + json.dumps(example_object)
661
662 with requests_mock.Mocker() as m:
663 m.register_uri(
664 requests_mock.GET,
665 "http://localhost:8086/db/db/series",
666 text=example_response
667 )
668
669 self.assertListEqual(
670 cli.query('select * from foo', chunked=True),
671 [example_object, example_object]
672 )
673
674 @raises(Exception)
675 def test_query_fail(self):
676 """Test query failed for TestInfluxDBClient object."""
677 with _mocked_session(self.cli, 'get', 401):
678 self.cli.query('select column_one from foo;')
679
680 def test_ping(self):
681 """Test ping querying InfluxDB version."""
682 with requests_mock.Mocker() as m:
683 m.register_uri(
684 requests_mock.GET,
685 "http://localhost:8086/ping",
686 status_code=204,
687 headers={'X-Influxdb-Version': '1.2.3'}
688 )
689 version = self.cli.ping()
690 self.assertEqual(version, '1.2.3')
691
692 def test_create_database(self):
693 """Test create database for TestInfluxDBClient object."""
694 with requests_mock.Mocker() as m:
695 m.register_uri(
696 requests_mock.POST,
697 "http://localhost:8086/query",
698 text='{"results":[{}]}'
699 )
700 self.cli.create_database('new_db')
701 self.assertEqual(
702 m.last_request.qs['q'][0],
703 'create database "new_db"'
704 )
705
706 def test_create_numeric_named_database(self):
707 """Test create db w/numeric name for TestInfluxDBClient object."""
708 with requests_mock.Mocker() as m:
709 m.register_uri(
710 requests_mock.POST,
711 "http://localhost:8086/query",
712 text='{"results":[{}]}'
713 )
714 self.cli.create_database('123')
715 self.assertEqual(
716 m.last_request.qs['q'][0],
717 'create database "123"'
718 )
719
720 @raises(Exception)
721 def test_create_database_fails(self):
722 """Test create database fail for TestInfluxDBClient object."""
723 with _mocked_session(self.cli, 'post', 401):
724 self.cli.create_database('new_db')
725
726 def test_drop_database(self):
727 """Test drop database for TestInfluxDBClient object."""
728 with requests_mock.Mocker() as m:
729 m.register_uri(
730 requests_mock.POST,
731 "http://localhost:8086/query",
732 text='{"results":[{}]}'
733 )
734 self.cli.drop_database('new_db')
735 self.assertEqual(
736 m.last_request.qs['q'][0],
737 'drop database "new_db"'
738 )
739
740 def test_drop_measurement(self):
741 """Test drop measurement for TestInfluxDBClient object."""
742 with requests_mock.Mocker() as m:
743 m.register_uri(
744 requests_mock.POST,
745 "http://localhost:8086/query",
746 text='{"results":[{}]}'
747 )
748 self.cli.drop_measurement('new_measurement')
749 self.assertEqual(
750 m.last_request.qs['q'][0],
751 'drop measurement "new_measurement"'
752 )
753
754 def test_drop_numeric_named_database(self):
755 """Test drop numeric db for TestInfluxDBClient object."""
756 with requests_mock.Mocker() as m:
757 m.register_uri(
758 requests_mock.POST,
759 "http://localhost:8086/query",
760 text='{"results":[{}]}'
761 )
762 self.cli.drop_database('123')
763 self.assertEqual(
764 m.last_request.qs['q'][0],
765 'drop database "123"'
766 )
767
768 def test_get_list_database(self):
769 """Test get list of databases for TestInfluxDBClient object."""
770 data = {'results': [
771 {'series': [
772 {'name': 'databases',
773 'values': [
774 ['new_db_1'],
775 ['new_db_2']],
776 'columns': ['name']}]}
777 ]}
778
779 with _mocked_session(self.cli, 'get', 200, json.dumps(data)):
780 self.assertListEqual(
781 self.cli.get_list_database(),
782 [{'name': 'new_db_1'}, {'name': 'new_db_2'}]
783 )
784
785 @raises(Exception)
786 def test_get_list_database_fails(self):
787 """Test get list of dbs fail for TestInfluxDBClient object."""
788 cli = InfluxDBClient('host', 8086, 'username', 'password')
789 with _mocked_session(cli, 'get', 401):
790 cli.get_list_database()
791
792 def test_get_list_measurements(self):
793 """Test get list of measurements for TestInfluxDBClient object."""
794 data = {
795 "results": [{
796 "series": [
797 {"name": "measurements",
798 "columns": ["name"],
799 "values": [["cpu"], ["disk"]
800 ]}]}
801 ]
802 }
803
804 with _mocked_session(self.cli, 'get', 200, json.dumps(data)):
805 self.assertListEqual(
806 self.cli.get_list_measurements(),
807 [{'name': 'cpu'}, {'name': 'disk'}]
808 )
809
810 def test_get_list_series(self):
811 """Test get a list of series from the database."""
812 data = {'results': [
813 {'series': [
814 {
815 'values': [
816 ['cpu_load_short,host=server01,region=us-west'],
817 ['memory_usage,host=server02,region=us-east']],
818 'columns': ['key']
819 }
820 ]}
821 ]}
822
823 with _mocked_session(self.cli, 'get', 200, json.dumps(data)):
824 self.assertListEqual(
825 self.cli.get_list_series(),
826 ['cpu_load_short,host=server01,region=us-west',
827 'memory_usage,host=server02,region=us-east'])
828
829 def test_get_list_series_with_measurement(self):
830 """Test get a list of series from the database by filter."""
831 data = {'results': [
832 {'series': [
833 {
834 'values': [
835 ['cpu_load_short,host=server01,region=us-west']],
836 'columns': ['key']
837 }
838 ]}
839 ]}
840
841 with _mocked_session(self.cli, 'get', 200, json.dumps(data)):
842 self.assertListEqual(
843 self.cli.get_list_series(measurement='cpu_load_short'),
844 ['cpu_load_short,host=server01,region=us-west'])
845
846 def test_get_list_series_with_tags(self):
847 """Test get a list of series from the database by tags."""
848 data = {'results': [
849 {'series': [
850 {
851 'values': [
852 ['cpu_load_short,host=server01,region=us-west']],
853 'columns': ['key']
854 }
855 ]}
856 ]}
857
858 with _mocked_session(self.cli, 'get', 200, json.dumps(data)):
859 self.assertListEqual(
860 self.cli.get_list_series(tags={'region': 'us-west'}),
861 ['cpu_load_short,host=server01,region=us-west'])
862
863 @raises(Exception)
864 def test_get_list_series_fails(self):
865 """Test get a list of series from the database but fail."""
866 cli = InfluxDBClient('host', 8086, 'username', 'password')
867 with _mocked_session(cli, 'get', 401):
868 cli.get_list_series()
869
870 def test_create_retention_policy_default(self):
871 """Test create default ret policy for TestInfluxDBClient object."""
872 example_response = '{"results":[{}]}'
873
874 with requests_mock.Mocker() as m:
875 m.register_uri(
876 requests_mock.POST,
877 "http://localhost:8086/query",
878 text=example_response
879 )
880 self.cli.create_retention_policy(
881 'somename', '1d', 4, default=True, database='db'
882 )
883
884 self.assertEqual(
885 m.last_request.qs['q'][0],
886 'create retention policy "somename" on '
887 '"db" duration 1d replication 4 shard duration 0s default'
888 )
889
890 def test_create_retention_policy(self):
891 """Test create retention policy for TestInfluxDBClient object."""
892 example_response = '{"results":[{}]}'
893
894 with requests_mock.Mocker() as m:
895 m.register_uri(
896 requests_mock.POST,
897 "http://localhost:8086/query",
898 text=example_response
899 )
900 self.cli.create_retention_policy(
901 'somename', '1d', 4, database='db'
902 )
903
904 self.assertEqual(
905 m.last_request.qs['q'][0],
906 'create retention policy "somename" on '
907 '"db" duration 1d replication 4 shard duration 0s'
908 )
909
910 def test_create_retention_policy_shard_duration(self):
911 """Test create retention policy with a custom shard duration."""
912 example_response = '{"results":[{}]}'
913
914 with requests_mock.Mocker() as m:
915 m.register_uri(
916 requests_mock.POST,
917 "http://localhost:8086/query",
918 text=example_response
919 )
920 self.cli.create_retention_policy(
921 'somename2', '1d', 4, database='db',
922 shard_duration='1h'
923 )
924
925 self.assertEqual(
926 m.last_request.qs['q'][0],
927 'create retention policy "somename2" on '
928 '"db" duration 1d replication 4 shard duration 1h'
929 )
930
931 def test_create_retention_policy_shard_duration_default(self):
932 """Test create retention policy with a default shard duration."""
933 example_response = '{"results":[{}]}'
934
935 with requests_mock.Mocker() as m:
936 m.register_uri(
937 requests_mock.POST,
938 "http://localhost:8086/query",
939 text=example_response
940 )
941 self.cli.create_retention_policy(
942 'somename3', '1d', 4, database='db',
943 shard_duration='1h', default=True
944 )
945
946 self.assertEqual(
947 m.last_request.qs['q'][0],
948 'create retention policy "somename3" on '
949 '"db" duration 1d replication 4 shard duration 1h '
950 'default'
951 )
952
953 def test_alter_retention_policy(self):
954 """Test alter retention policy for TestInfluxDBClient object."""
955 example_response = '{"results":[{}]}'
956
957 with requests_mock.Mocker() as m:
958 m.register_uri(
959 requests_mock.POST,
960 "http://localhost:8086/query",
961 text=example_response
962 )
963 # Test alter duration
964 self.cli.alter_retention_policy('somename', 'db',
965 duration='4d')
966 self.assertEqual(
967 m.last_request.qs['q'][0],
968 'alter retention policy "somename" on "db" duration 4d'
969 )
970 # Test alter replication
971 self.cli.alter_retention_policy('somename', 'db',
972 replication=4)
973 self.assertEqual(
974 m.last_request.qs['q'][0],
975 'alter retention policy "somename" on "db" replication 4'
976 )
977
978 # Test alter shard duration
979 self.cli.alter_retention_policy('somename', 'db',
980 shard_duration='1h')
981 self.assertEqual(
982 m.last_request.qs['q'][0],
983 'alter retention policy "somename" on "db" shard duration 1h'
984 )
985
986 # Test alter default
987 self.cli.alter_retention_policy('somename', 'db',
988 default=True)
989 self.assertEqual(
990 m.last_request.qs['q'][0],
991 'alter retention policy "somename" on "db" default'
992 )
993
994 @raises(Exception)
995 def test_alter_retention_policy_invalid(self):
996 """Test invalid alter ret policy for TestInfluxDBClient object."""
997 cli = InfluxDBClient('host', 8086, 'username', 'password')
998 with _mocked_session(cli, 'get', 400):
999 self.cli.alter_retention_policy('somename', 'db')
1000
1001 def test_drop_retention_policy(self):
1002 """Test drop retention policy for TestInfluxDBClient object."""
1003 example_response = '{"results":[{}]}'
1004
1005 with requests_mock.Mocker() as m:
1006 m.register_uri(
1007 requests_mock.POST,
1008 "http://localhost:8086/query",
1009 text=example_response
1010 )
1011 self.cli.drop_retention_policy('somename', 'db')
1012 self.assertEqual(
1013 m.last_request.qs['q'][0],
1014 'drop retention policy "somename" on "db"'
1015 )
1016
1017 @raises(Exception)
1018 def test_drop_retention_policy_fails(self):
1019 """Test failed drop ret policy for TestInfluxDBClient object."""
1020 cli = InfluxDBClient('host', 8086, 'username', 'password')
1021 with _mocked_session(cli, 'delete', 401):
1022 cli.drop_retention_policy('default', 'db')
1023
1024 def test_get_list_retention_policies(self):
1025 """Test get retention policies for TestInfluxDBClient object."""
1026 example_response = \
1027 '{"results": [{"series": [{"values": [["fsfdsdf", "24h0m0s", 2]],'\
1028 ' "columns": ["name", "duration", "replicaN"]}]}]}'
1029
1030 with requests_mock.Mocker() as m:
1031 m.register_uri(
1032 requests_mock.GET,
1033 "http://localhost:8086/query",
1034 text=example_response
1035 )
1036 self.assertListEqual(
1037 self.cli.get_list_retention_policies("db"),
1038 [{'duration': '24h0m0s',
1039 'name': 'fsfdsdf', 'replicaN': 2}]
1040 )
1041
1042 @mock.patch('requests.Session.request')
1043 def test_request_retry(self, mock_request):
1044 """Test that two connection errors will be handled."""
1045 class CustomMock(object):
1046 """Create custom mock object for test."""
1047
1048 def __init__(self):
1049 self.i = 0
1050
1051 def connection_error(self, *args, **kwargs):
1052 """Handle a connection error for the CustomMock object."""
1053 self.i += 1
1054
1055 if self.i < 3:
1056 raise requests.exceptions.ConnectionError
1057
1058 r = requests.Response()
1059 r.status_code = 204
1060 return r
1061
1062 mock_request.side_effect = CustomMock().connection_error
1063
1064 cli = InfluxDBClient(database='db')
1065 cli.write_points(
1066 self.dummy_points
1067 )
1068
1069 @mock.patch('requests.Session.request')
1070 def test_request_retry_raises(self, mock_request):
1071 """Test that three requests errors will not be handled."""
1072 class CustomMock(object):
1073 """Create custom mock object for test."""
1074
1075 def __init__(self):
1076 self.i = 0
1077
1078 def connection_error(self, *args, **kwargs):
1079 """Handle a connection error for the CustomMock object."""
1080 self.i += 1
1081
1082 if self.i < 4:
1083 raise requests.exceptions.HTTPError
1084 else:
1085 r = requests.Response()
1086 r.status_code = 200
1087 return r
1088
1089 mock_request.side_effect = CustomMock().connection_error
1090
1091 cli = InfluxDBClient(database='db')
1092
1093 with self.assertRaises(requests.exceptions.HTTPError):
1094 cli.write_points(self.dummy_points)
1095
1096 @mock.patch('requests.Session.request')
1097 def test_random_request_retry(self, mock_request):
1098 """Test that a random number of connection errors will be handled."""
1099 class CustomMock(object):
1100 """Create custom mock object for test."""
1101
1102 def __init__(self, retries):
1103 self.i = 0
1104 self.retries = retries
1105
1106 def connection_error(self, *args, **kwargs):
1107 """Handle a connection error for the CustomMock object."""
1108 self.i += 1
1109
1110 if self.i < self.retries:
1111 raise requests.exceptions.ConnectionError
1112 else:
1113 r = requests.Response()
1114 r.status_code = 204
1115 return r
1116
1117 retries = random.randint(1, 5)
1118 mock_request.side_effect = CustomMock(retries).connection_error
1119
1120 cli = InfluxDBClient(database='db', retries=retries)
1121 cli.write_points(self.dummy_points)
1122
1123 @mock.patch('requests.Session.request')
1124 def test_random_request_retry_raises(self, mock_request):
1125 """Test a random number of conn errors plus one will not be handled."""
1126 class CustomMock(object):
1127 """Create custom mock object for test."""
1128
1129 def __init__(self, retries):
1130 self.i = 0
1131 self.retries = retries
1132
1133 def connection_error(self, *args, **kwargs):
1134 """Handle a connection error for the CustomMock object."""
1135 self.i += 1
1136
1137 if self.i < self.retries + 1:
1138 raise requests.exceptions.ConnectionError
1139 else:
1140 r = requests.Response()
1141 r.status_code = 200
1142 return r
1143
1144 retries = random.randint(1, 5)
1145 mock_request.side_effect = CustomMock(retries).connection_error
1146
1147 cli = InfluxDBClient(database='db', retries=retries)
1148
1149 with self.assertRaises(requests.exceptions.ConnectionError):
1150 cli.write_points(self.dummy_points)
1151
1152 def test_get_list_users(self):
1153 """Test get users for TestInfluxDBClient object."""
1154 example_response = (
1155 '{"results":[{"series":[{"columns":["user","admin"],'
1156 '"values":[["test",false]]}]}]}'
1157 )
1158
1159 with requests_mock.Mocker() as m:
1160 m.register_uri(
1161 requests_mock.GET,
1162 "http://localhost:8086/query",
1163 text=example_response
1164 )
1165
1166 self.assertListEqual(
1167 self.cli.get_list_users(),
1168 [{'user': 'test', 'admin': False}]
1169 )
1170
1171 def test_get_list_users_empty(self):
1172 """Test get empty userlist for TestInfluxDBClient object."""
1173 example_response = (
1174 '{"results":[{"series":[{"columns":["user","admin"]}]}]}'
1175 )
1176 with requests_mock.Mocker() as m:
1177 m.register_uri(
1178 requests_mock.GET,
1179 "http://localhost:8086/query",
1180 text=example_response
1181 )
1182
1183 self.assertListEqual(self.cli.get_list_users(), [])
1184
1185 def test_grant_admin_privileges(self):
1186 """Test grant admin privs for TestInfluxDBClient object."""
1187 example_response = '{"results":[{}]}'
1188
1189 with requests_mock.Mocker() as m:
1190 m.register_uri(
1191 requests_mock.POST,
1192 "http://localhost:8086/query",
1193 text=example_response
1194 )
1195 self.cli.grant_admin_privileges('test')
1196
1197 self.assertEqual(
1198 m.last_request.qs['q'][0],
1199 'grant all privileges to "test"'
1200 )
1201
1202 @raises(Exception)
1203 def test_grant_admin_privileges_invalid(self):
1204 """Test grant invalid admin privs for TestInfluxDBClient object."""
1205 cli = InfluxDBClient('host', 8086, 'username', 'password')
1206 with _mocked_session(cli, 'get', 400):
1207 self.cli.grant_admin_privileges('')
1208
1209 def test_revoke_admin_privileges(self):
1210 """Test revoke admin privs for TestInfluxDBClient object."""
1211 example_response = '{"results":[{}]}'
1212
1213 with requests_mock.Mocker() as m:
1214 m.register_uri(
1215 requests_mock.POST,
1216 "http://localhost:8086/query",
1217 text=example_response
1218 )
1219 self.cli.revoke_admin_privileges('test')
1220
1221 self.assertEqual(
1222 m.last_request.qs['q'][0],
1223 'revoke all privileges from "test"'
1224 )
1225
1226 @raises(Exception)
1227 def test_revoke_admin_privileges_invalid(self):
1228 """Test revoke invalid admin privs for TestInfluxDBClient object."""
1229 cli = InfluxDBClient('host', 8086, 'username', 'password')
1230 with _mocked_session(cli, 'get', 400):
1231 self.cli.revoke_admin_privileges('')
1232
1233 def test_grant_privilege(self):
1234 """Test grant privs for TestInfluxDBClient object."""
1235 example_response = '{"results":[{}]}'
1236
1237 with requests_mock.Mocker() as m:
1238 m.register_uri(
1239 requests_mock.POST,
1240 "http://localhost:8086/query",
1241 text=example_response
1242 )
1243 self.cli.grant_privilege('read', 'testdb', 'test')
1244
1245 self.assertEqual(
1246 m.last_request.qs['q'][0],
1247 'grant read on "testdb" to "test"'
1248 )
1249
1250 @raises(Exception)
1251 def test_grant_privilege_invalid(self):
1252 """Test grant invalid privs for TestInfluxDBClient object."""
1253 cli = InfluxDBClient('host', 8086, 'username', 'password')
1254 with _mocked_session(cli, 'get', 400):
1255 self.cli.grant_privilege('', 'testdb', 'test')
1256
1257 def test_revoke_privilege(self):
1258 """Test revoke privs for TestInfluxDBClient object."""
1259 example_response = '{"results":[{}]}'
1260
1261 with requests_mock.Mocker() as m:
1262 m.register_uri(
1263 requests_mock.POST,
1264 "http://localhost:8086/query",
1265 text=example_response
1266 )
1267 self.cli.revoke_privilege('read', 'testdb', 'test')
1268
1269 self.assertEqual(
1270 m.last_request.qs['q'][0],
1271 'revoke read on "testdb" from "test"'
1272 )
1273
1274 @raises(Exception)
1275 def test_revoke_privilege_invalid(self):
1276 """Test revoke invalid privs for TestInfluxDBClient object."""
1277 cli = InfluxDBClient('host', 8086, 'username', 'password')
1278 with _mocked_session(cli, 'get', 400):
1279 self.cli.revoke_privilege('', 'testdb', 'test')
1280
1281 def test_get_list_privileges(self):
1282 """Test get list of privs for TestInfluxDBClient object."""
1283 data = {'results': [
1284 {'series': [
1285 {'columns': ['database', 'privilege'],
1286 'values': [
1287 ['db1', 'READ'],
1288 ['db2', 'ALL PRIVILEGES'],
1289 ['db3', 'NO PRIVILEGES']]}
1290 ]}
1291 ]}
1292
1293 with _mocked_session(self.cli, 'get', 200, json.dumps(data)):
1294 self.assertListEqual(
1295 self.cli.get_list_privileges('test'),
1296 [{'database': 'db1', 'privilege': 'READ'},
1297 {'database': 'db2', 'privilege': 'ALL PRIVILEGES'},
1298 {'database': 'db3', 'privilege': 'NO PRIVILEGES'}]
1299 )
1300
1301 @raises(Exception)
1302 def test_get_list_privileges_fails(self):
1303 """Test failed get list of privs for TestInfluxDBClient object."""
1304 cli = InfluxDBClient('host', 8086, 'username', 'password')
1305 with _mocked_session(cli, 'get', 401):
1306 cli.get_list_privileges('test')
1307
1308 def test_get_list_continuous_queries(self):
1309 """Test getting a list of continuous queries."""
1310 data = {
1311 "results": [
1312 {
1313 "statement_id": 0,
1314 "series": [
1315 {
1316 "name": "testdb01",
1317 "columns": ["name", "query"],
1318 "values": [["testname01", "testquery01"],
1319 ["testname02", "testquery02"]]
1320 },
1321 {
1322 "name": "testdb02",
1323 "columns": ["name", "query"],
1324 "values": [["testname03", "testquery03"]]
1325 },
1326 {
1327 "name": "testdb03",
1328 "columns": ["name", "query"]
1329 }
1330 ]
1331 }
1332 ]
1333 }
1334
1335 with _mocked_session(self.cli, 'get', 200, json.dumps(data)):
1336 self.assertListEqual(
1337 self.cli.get_list_continuous_queries(),
1338 [
1339 {
1340 'testdb01': [
1341 {'name': 'testname01', 'query': 'testquery01'},
1342 {'name': 'testname02', 'query': 'testquery02'}
1343 ]
1344 },
1345 {
1346 'testdb02': [
1347 {'name': 'testname03', 'query': 'testquery03'}
1348 ]
1349 },
1350 {
1351 'testdb03': []
1352 }
1353 ]
1354 )
1355
1356 @raises(Exception)
1357 def test_get_list_continuous_queries_fails(self):
1358 """Test failing to get a list of continuous queries."""
1359 with _mocked_session(self.cli, 'get', 400):
1360 self.cli.get_list_continuous_queries()
1361
1362 def test_create_continuous_query(self):
1363 """Test continuous query creation."""
1364 data = {"results": [{}]}
1365 with requests_mock.Mocker() as m:
1366 m.register_uri(
1367 requests_mock.GET,
1368 "http://localhost:8086/query",
1369 text=json.dumps(data)
1370 )
1371 query = 'SELECT count("value") INTO "6_months"."events" FROM ' \
1372 '"events" GROUP BY time(10m)'
1373 self.cli.create_continuous_query('cq_name', query, 'db_name')
1374 self.assertEqual(
1375 m.last_request.qs['q'][0],
1376 'create continuous query "cq_name" on "db_name" begin select '
1377 'count("value") into "6_months"."events" from "events" group '
1378 'by time(10m) end'
1379 )
1380 self.cli.create_continuous_query('cq_name', query, 'db_name',
1381 'EVERY 10s FOR 2m')
1382 self.assertEqual(
1383 m.last_request.qs['q'][0],
1384 'create continuous query "cq_name" on "db_name" resample '
1385 'every 10s for 2m begin select count("value") into '
1386 '"6_months"."events" from "events" group by time(10m) end'
1387 )
1388
1389 @raises(Exception)
1390 def test_create_continuous_query_fails(self):
1391 """Test failing to create a continuous query."""
1392 with _mocked_session(self.cli, 'get', 400):
1393 self.cli.create_continuous_query('cq_name', 'select', 'db_name')
1394
1395 def test_drop_continuous_query(self):
1396 """Test dropping a continuous query."""
1397 data = {"results": [{}]}
1398 with requests_mock.Mocker() as m:
1399 m.register_uri(
1400 requests_mock.GET,
1401 "http://localhost:8086/query",
1402 text=json.dumps(data)
1403 )
1404 self.cli.drop_continuous_query('cq_name', 'db_name')
1405 self.assertEqual(
1406 m.last_request.qs['q'][0],
1407 'drop continuous query "cq_name" on "db_name"'
1408 )
1409
1410 @raises(Exception)
1411 def test_drop_continuous_query_fails(self):
1412 """Test failing to drop a continuous query."""
1413 with _mocked_session(self.cli, 'get', 400):
1414 self.cli.drop_continuous_query('cq_name', 'db_name')
1415
1416 def test_invalid_port_fails(self):
1417 """Test invalid port fail for TestInfluxDBClient object."""
1418 with self.assertRaises(ValueError):
1419 InfluxDBClient('host', '80/redir', 'username', 'password')
1420
1421 def test_chunked_response(self):
1422 """Test chunked response for TestInfluxDBClient object."""
1423 example_response = \
1424 u'{"results":[{"statement_id":0,"series":[{"columns":["key"],' \
1425 '"values":[["cpu"],["memory"],["iops"],["network"]],"partial":' \
1426 'true}],"partial":true}]}\n{"results":[{"statement_id":0,' \
1427 '"series":[{"columns":["key"],"values":[["qps"],["uptime"],' \
1428 '["df"],["mount"]]}]}]}\n'
1429
1430 with requests_mock.Mocker() as m:
1431 m.register_uri(
1432 requests_mock.GET,
1433 "http://localhost:8086/query",
1434 text=example_response
1435 )
1436 response = self.cli.query('show series',
1437 chunked=True, chunk_size=4)
1438 res = list(response)
1439 self.assertTrue(len(res) == 2)
1440 self.assertEqual(res[0].__repr__(), ResultSet(
1441 {'series': [{
1442 'columns': ['key'],
1443 'values': [['cpu'], ['memory'], ['iops'], ['network']]
1444 }]}).__repr__())
1445 self.assertEqual(res[1].__repr__(), ResultSet(
1446 {'series': [{
1447 'columns': ['key'],
1448 'values': [['qps'], ['uptime'], ['df'], ['mount']]
1449 }]}).__repr__())
1450
1451 def test_auth_default(self):
1452 """Test auth with default settings."""
1453 with requests_mock.Mocker() as m:
1454 m.register_uri(
1455 requests_mock.GET,
1456 "http://localhost:8086/ping",
1457 status_code=204,
1458 headers={'X-Influxdb-Version': '1.2.3'}
1459 )
1460
1461 cli = InfluxDBClient()
1462 cli.ping()
1463
1464 self.assertEqual(m.last_request.headers["Authorization"],
1465 "Basic cm9vdDpyb290")
1466
1467 def test_auth_username_password(self):
1468 """Test auth with custom username and password."""
1469 with requests_mock.Mocker() as m:
1470 m.register_uri(
1471 requests_mock.GET,
1472 "http://localhost:8086/ping",
1473 status_code=204,
1474 headers={'X-Influxdb-Version': '1.2.3'}
1475 )
1476
1477 cli = InfluxDBClient(username='my-username',
1478 password='my-password')
1479 cli.ping()
1480
1481 self.assertEqual(m.last_request.headers["Authorization"],
1482 "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=")
1483
1484 def test_auth_username_password_none(self):
1485 """Test auth with not defined username or password."""
1486 with requests_mock.Mocker() as m:
1487 m.register_uri(
1488 requests_mock.GET,
1489 "http://localhost:8086/ping",
1490 status_code=204,
1491 headers={'X-Influxdb-Version': '1.2.3'}
1492 )
1493
1494 cli = InfluxDBClient(username=None, password=None)
1495 cli.ping()
1496 self.assertFalse('Authorization' in m.last_request.headers)
1497
1498 cli = InfluxDBClient(username=None)
1499 cli.ping()
1500 self.assertFalse('Authorization' in m.last_request.headers)
1501
1502 cli = InfluxDBClient(password=None)
1503 cli.ping()
1504 self.assertFalse('Authorization' in m.last_request.headers)
1505
1506 def test_auth_token(self):
1507 """Test auth with custom authorization header."""
1508 with requests_mock.Mocker() as m:
1509 m.register_uri(
1510 requests_mock.GET,
1511 "http://localhost:8086/ping",
1512 status_code=204,
1513 headers={'X-Influxdb-Version': '1.2.3'}
1514 )
1515
1516 cli = InfluxDBClient(username=None, password=None,
1517 headers={"Authorization": "my-token"})
1518 cli.ping()
1519 self.assertEqual(m.last_request.headers["Authorization"],
1520 "my-token")
1521
1522 def test_custom_socket_options(self):
1523 """Test custom socket options."""
1524 test_socket_options = HTTPConnection.default_socket_options + \
1525 [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
1526 (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 60),
1527 (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 15)]
1528
1529 cli = InfluxDBClient(username=None, password=None,
1530 socket_options=test_socket_options)
1531
•1532 self.assertEqual(cli._session.adapters.get("http://").socket_options,
1533 test_socket_options)
•1534 self.assertEqual(cli._session.adapters.get("http://").poolmanager.
1535 connection_pool_kw.get("socket_options"),
1536 test_socket_options)
1537
1538 connection_pool = cli._session.adapters.get("http://").poolmanager \
1539 .connection_from_url(
1540 url="http://localhost:8086")
1541 new_connection = connection_pool._new_conn()
•1542 self.assertEqual(new_connection.socket_options, test_socket_options)
1543
1544 def test_none_socket_options(self):
1545 """Test default socket options."""
1546 cli = InfluxDBClient(username=None, password=None)
•1547 self.assertEqual(cli._session.adapters.get("http://").socket_options,
1548 None)
1549 connection_pool = cli._session.adapters.get("http://").poolmanager \
1550 .connection_from_url(
1551 url="http://localhost:8086")
1552 new_connection = connection_pool._new_conn()
•1553 self.assertEqual(new_connection.socket_options,
1554 HTTPConnection.default_socket_options)
1555
1556
1557 class FakeClient(InfluxDBClient):
1558 """Set up a fake client instance of InfluxDBClient."""
1559
1560 def __init__(self, *args, **kwargs):
1561 """Initialize an instance of the FakeClient object."""
1562 super(FakeClient, self).__init__(*args, **kwargs)
1563
1564 def query(self,
1565 query,
1566 params=None,
1567 expected_response_code=200,
1568 database=None):
1569 """Query data from the FakeClient object."""
1570 if query == 'Fail':
1571 raise Exception("Fail")
1572 elif query == 'Fail once' and self._host == 'host1':
1573 raise Exception("Fail Once")
1574 elif query == 'Fail twice' and self._host in 'host1 host2':
1575 raise Exception("Fail Twice")
1576 else:
1577 return "Success"