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