Debian Codegraph @

influxdb/tests/dataframe_client_test.py

raw ◀ ▶
5 Debian patches touch this file
1 # -*- coding: utf-8 -*-
2 """Unit tests for misc module."""
3
4 from __future__ import absolute_import
5 from __future__ import division
6 from __future__ import print_function
7 from __future__ import unicode_literals
8
9 from datetime import timedelta
10
11 import json
12 import unittest
13 import warnings
14 import requests_mock
15
•16 from functools import wraps
17
18 def raises(*exceptions):
19 valid = ' or '.join([e.__name__ for e in exceptions])
20
21 def decorate(func):
22 name = func.__name__
23 def newfunc(*arg, **kw):
24 try:
25 func(*arg, **kw)
26 except exceptions:
27 pass
28 except:
29 raise
30 else:
31 message = "%s() did not raise %s" % (name, valid)
32 raise AssertionError(message)
33 newfunc = wraps(func)(newfunc)
34 return newfunc
35 return decorate
36
37 from influxdb.tests import skip_if_pypy, using_pypy
38
39 from .client_test import _mocked_session
40
41 if not using_pypy:
42 import pandas as pd
•43 from pandas.testing import assert_frame_equal
44 from influxdb import DataFrameClient
45 import numpy as np
46
47
48 @skip_if_pypy
49 class TestDataFrameClient(unittest.TestCase):
50 """Set up a test DataFrameClient object."""
51
52 def setUp(self):
53 """Instantiate a TestDataFrameClient object."""
54 # By default, raise exceptions on warnings
55 warnings.simplefilter('error', FutureWarning)
56
57 def test_write_points_from_dataframe(self):
58 """Test write points from df in TestDataFrameClient object."""
59 now = pd.Timestamp('1970-01-01 00:00+00:00')
60 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
61 index=[now, now + timedelta(hours=1)],
62 columns=["column_one", "column_two",
63 "column_three"])
64 expected = (
65 b"foo column_one=\"1\",column_two=1i,column_three=1.0 0\n"
66 b"foo column_one=\"2\",column_two=2i,column_three=2.0 "
67 b"3600000000000\n"
68 )
69
70 with requests_mock.Mocker() as m:
71 m.register_uri(requests_mock.POST,
72 "http://localhost:8086/write",
73 status_code=204)
74
75 cli = DataFrameClient(database='db')
76
77 cli.write_points(dataframe, 'foo')
78 self.assertEqual(m.last_request.body, expected)
79
80 cli.write_points(dataframe, 'foo', tags=None)
81 self.assertEqual(m.last_request.body, expected)
82
83 def test_dataframe_write_points_with_whitespace_measurement(self):
84 """write_points should escape white space in measurements."""
85 now = pd.Timestamp('1970-01-01 00:00+00:00')
86 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
87 index=[now, now + timedelta(hours=1)],
88 columns=["column_one", "column_two",
89 "column_three"])
90 expected = (
91 b"meas\\ with\\ space "
92 b"column_one=\"1\",column_two=1i,column_three=1.0 0\n"
93 b"meas\\ with\\ space "
94 b"column_one=\"2\",column_two=2i,column_three=2.0 "
95 b"3600000000000\n"
96 )
97 with requests_mock.Mocker() as m:
98 m.register_uri(requests_mock.POST,
99 "http://localhost:8086/write",
100 status_code=204)
101 cli = DataFrameClient(database='db')
102 cli.write_points(dataframe, 'meas with space')
103 self.assertEqual(m.last_request.body, expected)
104
105 def test_dataframe_write_points_with_whitespace_in_column_names(self):
106 """write_points should escape white space in column names."""
107 now = pd.Timestamp('1970-01-01 00:00+00:00')
108 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
109 index=[now, now + timedelta(hours=1)],
110 columns=["column one", "column two",
111 "column three"])
112 expected = (
113 b"foo column\\ one=\"1\",column\\ two=1i,column\\ three=1.0 0\n"
114 b"foo column\\ one=\"2\",column\\ two=2i,column\\ three=2.0 "
115 b"3600000000000\n"
116 )
117 with requests_mock.Mocker() as m:
118 m.register_uri(requests_mock.POST,
119 "http://localhost:8086/write",
120 status_code=204)
121 cli = DataFrameClient(database='db')
122 cli.write_points(dataframe, 'foo')
123 self.assertEqual(m.last_request.body, expected)
124
125 def test_write_points_from_dataframe_with_none(self):
126 """Test write points from df in TestDataFrameClient object."""
127 now = pd.Timestamp('1970-01-01 00:00+00:00')
128 dataframe = pd.DataFrame(data=[["1", None, 1.0], ["2", 2.0, 2.0]],
129 index=[now, now + timedelta(hours=1)],
130 columns=["column_one", "column_two",
131 "column_three"])
132 expected = (
133 b"foo column_one=\"1\",column_three=1.0 0\n"
134 b"foo column_one=\"2\",column_two=2.0,column_three=2.0 "
135 b"3600000000000\n"
136 )
137
138 with requests_mock.Mocker() as m:
139 m.register_uri(requests_mock.POST,
140 "http://localhost:8086/write",
141 status_code=204)
142
143 cli = DataFrameClient(database='db')
144
145 cli.write_points(dataframe, 'foo')
146 self.assertEqual(m.last_request.body, expected)
147
148 cli.write_points(dataframe, 'foo', tags=None)
149 self.assertEqual(m.last_request.body, expected)
150
151 def test_write_points_from_dataframe_with_line_of_none(self):
152 """Test write points from df in TestDataFrameClient object."""
153 now = pd.Timestamp('1970-01-01 00:00+00:00')
154 dataframe = pd.DataFrame(data=[[None, None, None], ["2", 2.0, 2.0]],
155 index=[now, now + timedelta(hours=1)],
156 columns=["column_one", "column_two",
157 "column_three"])
158 expected = (
159 b"foo column_one=\"2\",column_two=2.0,column_three=2.0 "
160 b"3600000000000\n"
161 )
162
163 with requests_mock.Mocker() as m:
164 m.register_uri(requests_mock.POST,
165 "http://localhost:8086/write",
166 status_code=204)
167
168 cli = DataFrameClient(database='db')
169
170 cli.write_points(dataframe, 'foo')
171 self.assertEqual(m.last_request.body, expected)
172
173 cli.write_points(dataframe, 'foo', tags=None)
174 self.assertEqual(m.last_request.body, expected)
175
176 def test_write_points_from_dataframe_with_all_none(self):
177 """Test write points from df in TestDataFrameClient object."""
178 now = pd.Timestamp('1970-01-01 00:00+00:00')
179 dataframe = pd.DataFrame(data=[[None, None, None], [None, None, None]],
180 index=[now, now + timedelta(hours=1)],
181 columns=["column_one", "column_two",
182 "column_three"])
183 expected = (
184 b"\n"
185 )
186
187 with requests_mock.Mocker() as m:
188 m.register_uri(requests_mock.POST,
189 "http://localhost:8086/write",
190 status_code=204)
191
192 cli = DataFrameClient(database='db')
193
194 cli.write_points(dataframe, 'foo')
195 self.assertEqual(m.last_request.body, expected)
196
197 cli.write_points(dataframe, 'foo', tags=None)
198 self.assertEqual(m.last_request.body, expected)
199
200 def test_write_points_from_dataframe_in_batches(self):
201 """Test write points in batch from df in TestDataFrameClient object."""
202 now = pd.Timestamp('1970-01-01 00:00+00:00')
203 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
204 index=[now, now + timedelta(hours=1)],
205 columns=["column_one", "column_two",
206 "column_three"])
207 with requests_mock.Mocker() as m:
208 m.register_uri(requests_mock.POST,
209 "http://localhost:8086/write",
210 status_code=204)
211
212 cli = DataFrameClient(database='db')
213 self.assertTrue(cli.write_points(dataframe, "foo", batch_size=1))
214
215 def test_write_points_from_dataframe_with_tag_columns(self):
216 """Test write points from df w/tag in TestDataFrameClient object."""
217 now = pd.Timestamp('1970-01-01 00:00+00:00')
218 dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, 1.0],
219 ['red', 0, "2", 2, 2.0]],
220 index=[now, now + timedelta(hours=1)],
221 columns=["tag_one", "tag_two", "column_one",
222 "column_two", "column_three"])
223 expected = (
224 b"foo,tag_one=blue,tag_two=1 "
225 b"column_one=\"1\",column_two=1i,column_three=1.0 "
226 b"0\n"
227 b"foo,tag_one=red,tag_two=0 "
228 b"column_one=\"2\",column_two=2i,column_three=2.0 "
229 b"3600000000000\n"
230 )
231
232 with requests_mock.Mocker() as m:
233 m.register_uri(requests_mock.POST,
234 "http://localhost:8086/write",
235 status_code=204)
236
237 cli = DataFrameClient(database='db')
238
239 cli.write_points(dataframe, 'foo',
240 tag_columns=['tag_one', 'tag_two'])
241 self.assertEqual(m.last_request.body, expected)
242
243 cli.write_points(dataframe, 'foo',
244 tag_columns=['tag_one', 'tag_two'], tags=None)
245 self.assertEqual(m.last_request.body, expected)
246
247 def test_write_points_from_dataframe_with_tag_cols_and_global_tags(self):
248 """Test write points from df w/tag + cols in TestDataFrameClient."""
249 now = pd.Timestamp('1970-01-01 00:00+00:00')
250 dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, 1.0],
251 ['red', 0, "2", 2, 2.0]],
252 index=[now, now + timedelta(hours=1)],
253 columns=["tag_one", "tag_two", "column_one",
254 "column_two", "column_three"])
255 expected = (
256 b"foo,global_tag=value,tag_one=blue,tag_two=1 "
257 b"column_one=\"1\",column_two=1i,column_three=1.0 "
258 b"0\n"
259 b"foo,global_tag=value,tag_one=red,tag_two=0 "
260 b"column_one=\"2\",column_two=2i,column_three=2.0 "
261 b"3600000000000\n"
262 )
263
264 with requests_mock.Mocker() as m:
265 m.register_uri(requests_mock.POST,
266 "http://localhost:8086/write",
267 status_code=204)
268
269 cli = DataFrameClient(database='db')
270
271 cli.write_points(dataframe, 'foo',
272 tag_columns=['tag_one', 'tag_two'],
273 tags={'global_tag': 'value'})
274 self.assertEqual(m.last_request.body, expected)
275
276 def test_write_points_from_dataframe_with_tag_cols_and_defaults(self):
277 """Test default write points from df w/tag in TestDataFrameClient."""
278 now = pd.Timestamp('1970-01-01 00:00+00:00')
279 dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, 1.0, 'hot'],
280 ['red', 0, "2", 2, 2.0, 'cold']],
281 index=[now, now + timedelta(hours=1)],
282 columns=["tag_one", "tag_two", "column_one",
283 "column_two", "column_three",
284 "tag_three"])
285 expected_tags_and_fields = (
286 b"foo,tag_one=blue "
287 b"column_one=\"1\",column_two=1i "
288 b"0\n"
289 b"foo,tag_one=red "
290 b"column_one=\"2\",column_two=2i "
291 b"3600000000000\n"
292 )
293
294 expected_tags_no_fields = (
295 b"foo,tag_one=blue,tag_two=1 "
296 b"column_one=\"1\",column_two=1i,column_three=1.0,"
297 b"tag_three=\"hot\" 0\n"
298 b"foo,tag_one=red,tag_two=0 "
299 b"column_one=\"2\",column_two=2i,column_three=2.0,"
300 b"tag_three=\"cold\" 3600000000000\n"
301 )
302
303 expected_fields_no_tags = (
304 b"foo,tag_one=blue,tag_three=hot,tag_two=1 "
305 b"column_one=\"1\",column_two=1i,column_three=1.0 "
306 b"0\n"
307 b"foo,tag_one=red,tag_three=cold,tag_two=0 "
308 b"column_one=\"2\",column_two=2i,column_three=2.0 "
309 b"3600000000000\n"
310 )
311
312 expected_no_tags_no_fields = (
313 b"foo "
314 b"tag_one=\"blue\",tag_two=1i,column_one=\"1\","
315 b"column_two=1i,column_three=1.0,tag_three=\"hot\" "
316 b"0\n"
317 b"foo "
318 b"tag_one=\"red\",tag_two=0i,column_one=\"2\","
319 b"column_two=2i,column_three=2.0,tag_three=\"cold\" "
320 b"3600000000000\n"
321 )
322
323 with requests_mock.Mocker() as m:
324 m.register_uri(requests_mock.POST,
325 "http://localhost:8086/write",
326 status_code=204)
327
328 cli = DataFrameClient(database='db')
329
330 cli.write_points(dataframe, 'foo',
331 field_columns=['column_one', 'column_two'],
332 tag_columns=['tag_one'])
333 self.assertEqual(m.last_request.body, expected_tags_and_fields)
334
335 cli.write_points(dataframe, 'foo',
336 tag_columns=['tag_one', 'tag_two'])
337 self.assertEqual(m.last_request.body, expected_tags_no_fields)
338
339 cli.write_points(dataframe, 'foo',
340 field_columns=['column_one', 'column_two',
341 'column_three'])
342 self.assertEqual(m.last_request.body, expected_fields_no_tags)
343
344 cli.write_points(dataframe, 'foo')
345 self.assertEqual(m.last_request.body, expected_no_tags_no_fields)
346
347 def test_write_points_from_dataframe_with_tag_escaped(self):
348 """Test write points from df w/escaped tag in TestDataFrameClient."""
349 now = pd.Timestamp('1970-01-01 00:00+00:00')
350 dataframe = pd.DataFrame(
351 data=[
352 ['blue orange', "1", 1, 'hot=cold'], # space, equal
353 ['red,green', "2", 2, r'cold\fire'], # comma, backslash
354 ['some', "2", 2, ''], # skip empty
355 ['some', "2", 2, None], # skip None
356 ['', "2", 2, None], # all tags empty
357 ],
•358 index=pd.period_range(now, freq='h', periods=5),
359 columns=["tag_one", "column_one", "column_two", "tag_three"]
360 )
361
362 expected_escaped_tags = (
363 b"foo,tag_one=blue\\ orange,tag_three=hot\\=cold "
364 b"column_one=\"1\",column_two=1i "
365 b"0\n"
366 b"foo,tag_one=red\\,green,tag_three=cold\\\\fire "
367 b"column_one=\"2\",column_two=2i "
368 b"3600000000000\n"
369 b"foo,tag_one=some "
370 b"column_one=\"2\",column_two=2i "
371 b"7200000000000\n"
372 b"foo,tag_one=some "
373 b"column_one=\"2\",column_two=2i "
374 b"10800000000000\n"
375 b"foo "
376 b"column_one=\"2\",column_two=2i "
377 b"14400000000000\n"
378 )
379
380 with requests_mock.Mocker() as m:
381 m.register_uri(requests_mock.POST,
382 "http://localhost:8086/write",
383 status_code=204)
384 cli = DataFrameClient(database='db')
385 cli.write_points(dataframe, 'foo',
386 field_columns=['column_one', 'column_two'],
387 tag_columns=['tag_one', 'tag_three'])
388 self.assertEqual(m.last_request.body, expected_escaped_tags)
389
390 def test_write_points_from_dataframe_with_numeric_column_names(self):
391 """Test write points from df with numeric cols."""
392 now = pd.Timestamp('1970-01-01 00:00+00:00')
393 # df with numeric column names
394 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
395 index=[now, now + timedelta(hours=1)])
396
397 expected = (
398 b'foo,hello=there 0=\"1\",1=1i,2=1.0 0\n'
399 b'foo,hello=there 0=\"2\",1=2i,2=2.0 3600000000000\n'
400 )
401
402 with requests_mock.Mocker() as m:
403 m.register_uri(requests_mock.POST,
404 "http://localhost:8086/write",
405 status_code=204)
406
407 cli = DataFrameClient(database='db')
408 cli.write_points(dataframe, "foo", {"hello": "there"})
409
410 self.assertEqual(m.last_request.body, expected)
411
412 def test_write_points_from_dataframe_with_leading_none_column(self):
413 """write_points detect erroneous leading comma for null first field."""
414 dataframe = pd.DataFrame(
415 dict(
416 first=[1, None, None, 8, 9],
417 second=[2, None, None, None, 10],
418 third=[3, 4.1, None, None, 11],
419 first_tag=["one", None, None, "eight", None],
420 second_tag=["two", None, None, None, None],
421 third_tag=["three", "four", None, None, None],
422 comment=[
423 "All columns filled",
424 "First two of three empty",
425 "All empty",
426 "Last two of three empty",
427 "Empty tags with values",
428 ]
429 ),
430 index=pd.date_range(
431 start=pd.to_datetime('2018-01-01'),
432 freq='1D',
433 periods=5,
434 )
435 )
436 expected = (
437 b'foo,first_tag=one,second_tag=two,third_tag=three'
438 b' comment="All columns filled",first=1.0,second=2.0,third=3.0'
439 b' 1514764800000000000\n'
440 b'foo,third_tag=four'
441 b' comment="First two of three empty",third=4.1'
442 b' 1514851200000000000\n'
443 b'foo comment="All empty" 1514937600000000000\n'
444 b'foo,first_tag=eight'
445 b' comment="Last two of three empty",first=8.0'
446 b' 1515024000000000000\n'
447 b'foo'
448 b' comment="Empty tags with values",first=9.0,second=10.0'
449 b',third=11.0'
450 b' 1515110400000000000\n'
451 )
452
453 with requests_mock.Mocker() as m:
454 m.register_uri(requests_mock.POST,
455 "http://localhost:8086/write",
456 status_code=204)
457
458 cli = DataFrameClient(database='db')
459
460 colnames = [
461 "first_tag",
462 "second_tag",
463 "third_tag",
464 "comment",
465 "first",
466 "second",
467 "third"
468 ]
469 cli.write_points(dataframe.loc[:, colnames], 'foo',
470 tag_columns=[
471 "first_tag",
472 "second_tag",
473 "third_tag"])
474
475 self.assertEqual(m.last_request.body, expected)
476
•477 @unittest.skip("See #902470")
478 def test_write_points_from_dataframe_with_numeric_precision(self):
479 """Test write points from df with numeric precision."""
480 now = pd.Timestamp('1970-01-01 00:00+00:00')
481 # df with numeric column names
482 dataframe = pd.DataFrame(data=[["1", 1, 1.1111111111111],
483 ["2", 2, 2.2222222222222]],
484 index=[now, now + timedelta(hours=1)])
485
486 if np.lib.NumpyVersion(np.__version__) <= '1.13.3':
487 expected_default_precision = (
488 b'foo,hello=there 0=\"1\",1=1i,2=1.11111111111 0\n'
489 b'foo,hello=there 0=\"2\",1=2i,2=2.22222222222 3600000000000\n'
490 )
491 else:
492 expected_default_precision = (
493 b'foo,hello=there 0=\"1\",1=1i,2=1.1111111111111 0\n'
494 b'foo,hello=there 0=\"2\",1=2i,2=2.2222222222222 3600000000000\n' # noqa E501 line too long
495 )
496
497 expected_specified_precision = (
498 b'foo,hello=there 0=\"1\",1=1i,2=1.1111 0\n'
499 b'foo,hello=there 0=\"2\",1=2i,2=2.2222 3600000000000\n'
500 )
501
502 expected_full_precision = (
503 b'foo,hello=there 0=\"1\",1=1i,2=1.1111111111111 0\n'
504 b'foo,hello=there 0=\"2\",1=2i,2=2.2222222222222 3600000000000\n'
505 )
506
507 with requests_mock.Mocker() as m:
508 m.register_uri(requests_mock.POST,
509 "http://localhost:8086/write",
510 status_code=204)
511
512 cli = DataFrameClient(database='db')
513 cli.write_points(dataframe, "foo", {"hello": "there"})
514
515 print(expected_default_precision)
516 print(m.last_request.body)
517
518 self.assertEqual(m.last_request.body, expected_default_precision)
519
520 cli = DataFrameClient(database='db')
521 cli.write_points(dataframe, "foo", {"hello": "there"},
522 numeric_precision=4)
523
524 self.assertEqual(m.last_request.body, expected_specified_precision)
525
526 cli = DataFrameClient(database='db')
527 cli.write_points(dataframe, "foo", {"hello": "there"},
528 numeric_precision='full')
529
530 self.assertEqual(m.last_request.body, expected_full_precision)
531
532 def test_write_points_from_dataframe_with_period_index(self):
533 """Test write points from df with period index."""
534 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
535 index=[pd.Period('1970-01-01'),
536 pd.Period('1970-01-02')],
537 columns=["column_one", "column_two",
538 "column_three"])
539
540 expected = (
541 b"foo column_one=\"1\",column_two=1i,column_three=1.0 0\n"
542 b"foo column_one=\"2\",column_two=2i,column_three=2.0 "
543 b"86400000000000\n"
544 )
545
546 with requests_mock.Mocker() as m:
547 m.register_uri(requests_mock.POST,
548 "http://localhost:8086/write",
549 status_code=204)
550
551 cli = DataFrameClient(database='db')
552 cli.write_points(dataframe, "foo")
553
554 self.assertEqual(m.last_request.body, expected)
555
556 def test_write_points_from_dataframe_with_time_precision(self):
557 """Test write points from df with time precision."""
558 now = pd.Timestamp('1970-01-01 00:00+00:00')
559 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
560 index=[now, now + timedelta(hours=1)],
561 columns=["column_one", "column_two",
562 "column_three"])
563
564 with requests_mock.Mocker() as m:
565 m.register_uri(requests_mock.POST,
566 "http://localhost:8086/write",
567 status_code=204)
568
569 cli = DataFrameClient(database='db')
570 measurement = "foo"
571
572 cli.write_points(dataframe, measurement, time_precision='h')
573 self.assertEqual(m.last_request.qs['precision'], ['h'])
574 self.assertEqual(
575 b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo '
576 b'column_one="2",column_two=2i,column_three=2.0 1\n',
577 m.last_request.body,
578 )
579
580 cli.write_points(dataframe, measurement, time_precision='m')
581 self.assertEqual(m.last_request.qs['precision'], ['m'])
582 self.assertEqual(
583 b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo '
584 b'column_one="2",column_two=2i,column_three=2.0 60\n',
585 m.last_request.body,
586 )
587
588 cli.write_points(dataframe, measurement, time_precision='s')
589 self.assertEqual(m.last_request.qs['precision'], ['s'])
590 self.assertEqual(
591 b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo '
592 b'column_one="2",column_two=2i,column_three=2.0 3600\n',
593 m.last_request.body,
594 )
595
596 cli.write_points(dataframe, measurement, time_precision='ms')
597 self.assertEqual(m.last_request.qs['precision'], ['ms'])
598 self.assertEqual(
599 b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo '
600 b'column_one="2",column_two=2i,column_three=2.0 3600000\n',
601 m.last_request.body,
602 )
603
604 cli.write_points(dataframe, measurement, time_precision='u')
605 self.assertEqual(m.last_request.qs['precision'], ['u'])
606 self.assertEqual(
607 b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo '
608 b'column_one="2",column_two=2i,column_three=2.0 3600000000\n',
609 m.last_request.body,
610 )
611
612 cli.write_points(dataframe, measurement, time_precision='n')
613 self.assertEqual(m.last_request.qs['precision'], ['n'])
614 self.assertEqual(
615 b'foo column_one="1",column_two=1i,column_three=1.0 0\n'
616 b'foo column_one="2",column_two=2i,column_three=2.0 '
617 b'3600000000000\n',
618 m.last_request.body,
619 )
620
621 @raises(TypeError)
622 def test_write_points_from_dataframe_fails_without_time_index(self):
623 """Test failed write points from df without time index."""
624 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
625 columns=["column_one", "column_two",
626 "column_three"])
627
628 with requests_mock.Mocker() as m:
629 m.register_uri(requests_mock.POST,
630 "http://localhost:8086/db/db/series",
631 status_code=204)
632
633 cli = DataFrameClient(database='db')
634 cli.write_points(dataframe, "foo")
635
636 @raises(TypeError)
637 def test_write_points_from_dataframe_fails_with_series(self):
638 """Test failed write points from df with series."""
639 now = pd.Timestamp('1970-01-01 00:00+00:00')
640 dataframe = pd.Series(data=[1.0, 2.0],
641 index=[now, now + timedelta(hours=1)])
642
643 with requests_mock.Mocker() as m:
644 m.register_uri(requests_mock.POST,
645 "http://localhost:8086/db/db/series",
646 status_code=204)
647
648 cli = DataFrameClient(database='db')
649 cli.write_points(dataframe, "foo")
650
651 def test_create_database(self):
652 """Test create database for TestInfluxDBClient object."""
653 cli = DataFrameClient(database='db')
654 with requests_mock.Mocker() as m:
655 m.register_uri(
656 requests_mock.POST,
657 "http://localhost:8086/query",
658 text='{"results":[{}]}'
659 )
660 cli.create_database('new_db')
661 self.assertEqual(
662 m.last_request.qs['q'][0],
663 'create database "new_db"'
664 )
665
666 def test_create_numeric_named_database(self):
667 """Test create db w/numeric name for TestInfluxDBClient object."""
668 cli = DataFrameClient(database='db')
669 with requests_mock.Mocker() as m:
670 m.register_uri(
671 requests_mock.POST,
672 "http://localhost:8086/query",
673 text='{"results":[{}]}'
674 )
675 cli.create_database('123')
676 self.assertEqual(
677 m.last_request.qs['q'][0],
678 'create database "123"'
679 )
680
681 @raises(Exception)
682 def test_create_database_fails(self):
683 """Test create database fail for TestInfluxDBClient object."""
684 cli = DataFrameClient(database='db')
685 with _mocked_session(cli, 'post', 401):
686 cli.create_database('new_db')
687
688 def test_drop_database(self):
689 """Test drop database for TestInfluxDBClient object."""
690 cli = DataFrameClient(database='db')
691 with requests_mock.Mocker() as m:
692 m.register_uri(
693 requests_mock.POST,
694 "http://localhost:8086/query",
695 text='{"results":[{}]}'
696 )
697 cli.drop_database('new_db')
698 self.assertEqual(
699 m.last_request.qs['q'][0],
700 'drop database "new_db"'
701 )
702
703 def test_drop_measurement(self):
704 """Test drop measurement for TestInfluxDBClient object."""
705 cli = DataFrameClient(database='db')
706 with requests_mock.Mocker() as m:
707 m.register_uri(
708 requests_mock.POST,
709 "http://localhost:8086/query",
710 text='{"results":[{}]}'
711 )
712 cli.drop_measurement('new_measurement')
713 self.assertEqual(
714 m.last_request.qs['q'][0],
715 'drop measurement "new_measurement"'
716 )
717
718 def test_drop_numeric_named_database(self):
719 """Test drop numeric db for TestInfluxDBClient object."""
720 cli = DataFrameClient(database='db')
721 with requests_mock.Mocker() as m:
722 m.register_uri(
723 requests_mock.POST,
724 "http://localhost:8086/query",
725 text='{"results":[{}]}'
726 )
727 cli.drop_database('123')
728 self.assertEqual(
729 m.last_request.qs['q'][0],
730 'drop database "123"'
731 )
732
733 @raises(Exception)
734 def test_get_list_database_fails(self):
735 """Test get list of dbs fail for TestInfluxDBClient object."""
736 cli = DataFrameClient('host', 8086, 'username', 'password')
737 with _mocked_session(cli, 'get', 401):
738 cli.get_list_database()
739
740 def test_get_list_measurements(self):
741 """Test get list of measurements for TestInfluxDBClient object."""
742 cli = DataFrameClient(database='db')
743 data = {
744 "results": [{
745 "series": [
746 {"name": "measurements",
747 "columns": ["name"],
748 "values": [["cpu"], ["disk"]
749 ]}]}
750 ]
751 }
752
753 with _mocked_session(cli, 'get', 200, json.dumps(data)):
754 self.assertListEqual(
755 cli.get_list_measurements(),
756 [{'name': 'cpu'}, {'name': 'disk'}]
757 )
758
759 def test_create_retention_policy_default(self):
760 """Test create default ret policy for TestInfluxDBClient object."""
761 cli = DataFrameClient(database='db')
762 example_response = '{"results":[{}]}'
763
764 with requests_mock.Mocker() as m:
765 m.register_uri(
766 requests_mock.POST,
767 "http://localhost:8086/query",
768 text=example_response
769 )
770 cli.create_retention_policy(
771 'somename', '1d', 4, default=True, database='db'
772 )
773
774 self.assertEqual(
775 m.last_request.qs['q'][0],
776 'create retention policy "somename" on '
777 '"db" duration 1d replication 4 shard duration 0s default'
778 )
779
780 def test_create_retention_policy(self):
781 """Test create retention policy for TestInfluxDBClient object."""
782 cli = DataFrameClient(database='db')
783 example_response = '{"results":[{}]}'
784
785 with requests_mock.Mocker() as m:
786 m.register_uri(
787 requests_mock.POST,
788 "http://localhost:8086/query",
789 text=example_response
790 )
791 cli.create_retention_policy(
792 'somename', '1d', 4, database='db'
793 )
794
795 self.assertEqual(
796 m.last_request.qs['q'][0],
797 'create retention policy "somename" on '
798 '"db" duration 1d replication 4 shard duration 0s'
799 )
800
801 def test_alter_retention_policy(self):
802 """Test alter retention policy for TestInfluxDBClient object."""
803 cli = DataFrameClient(database='db')
804 example_response = '{"results":[{}]}'
805
806 with requests_mock.Mocker() as m:
807 m.register_uri(
808 requests_mock.POST,
809 "http://localhost:8086/query",
810 text=example_response
811 )
812 # Test alter duration
813 cli.alter_retention_policy('somename', 'db',
814 duration='4d')
815 self.assertEqual(
816 m.last_request.qs['q'][0],
817 'alter retention policy "somename" on "db" duration 4d'
818 )
819 # Test alter replication
820 cli.alter_retention_policy('somename', 'db',
821 replication=4)
822 self.assertEqual(
823 m.last_request.qs['q'][0],
824 'alter retention policy "somename" on "db" replication 4'
825 )
826
827 # Test alter shard duration
828 cli.alter_retention_policy('somename', 'db',
829 shard_duration='1h')
830 self.assertEqual(
831 m.last_request.qs['q'][0],
832 'alter retention policy "somename" on "db" shard duration 1h'
833 )
834
835 # Test alter default
836 cli.alter_retention_policy('somename', 'db',
837 default=True)
838 self.assertEqual(
839 m.last_request.qs['q'][0],
840 'alter retention policy "somename" on "db" default'
841 )
842
843 @raises(Exception)
844 def test_alter_retention_policy_invalid(self):
845 """Test invalid alter ret policy for TestInfluxDBClient object."""
846 cli = DataFrameClient('host', 8086, 'username', 'password')
847 with _mocked_session(cli, 'get', 400):
848 cli.alter_retention_policy('somename', 'db')
849
850 def test_drop_retention_policy(self):
851 """Test drop retention policy for TestInfluxDBClient object."""
852 cli = DataFrameClient(database='db')
853 example_response = '{"results":[{}]}'
854
855 with requests_mock.Mocker() as m:
856 m.register_uri(
857 requests_mock.POST,
858 "http://localhost:8086/query",
859 text=example_response
860 )
861 cli.drop_retention_policy('somename', 'db')
862 self.assertEqual(
863 m.last_request.qs['q'][0],
864 'drop retention policy "somename" on "db"'
865 )
866
867 @raises(Exception)
868 def test_drop_retention_policy_fails(self):
869 """Test failed drop ret policy for TestInfluxDBClient object."""
870 cli = DataFrameClient('host', 8086, 'username', 'password')
871 with _mocked_session(cli, 'delete', 401):
872 cli.drop_retention_policy('default', 'db')
873
874 def test_get_list_retention_policies(self):
875 """Test get retention policies for TestInfluxDBClient object."""
876 cli = DataFrameClient(database='db')
877 example_response = \
878 '{"results": [{"series": [{"values": [["fsfdsdf", "24h0m0s", 2]],'\
879 ' "columns": ["name", "duration", "replicaN"]}]}]}'
880
881 with requests_mock.Mocker() as m:
882 m.register_uri(
883 requests_mock.GET,
884 "http://localhost:8086/query",
885 text=example_response
886 )
887 self.assertListEqual(
888 cli.get_list_retention_policies("db"),
889 [{'duration': '24h0m0s',
890 'name': 'fsfdsdf', 'replicaN': 2}]
891 )
892
893 def test_query_into_dataframe(self):
894 """Test query into df for TestDataFrameClient object."""
895 data = {
896 "results": [{
897 "series": [
898 {"measurement": "network",
899 "tags": {"direction": ""},
900 "columns": ["time", "value"],
901 "values": [["2009-11-10T23:00:00Z", 23422]]
902 },
903 {"measurement": "network",
904 "tags": {"direction": "in"},
905 "columns": ["time", "value"],
906 "values": [["2009-11-10T23:00:00Z", 23422],
907 ["2009-11-10T23:00:00Z", 23422],
908 ["2009-11-10T23:00:00Z", 23422]]
909 }
910 ]
911 }]
912 }
913
914 pd1 = pd.DataFrame(
915 [[23422]], columns=['value'],
916 index=pd.to_datetime(["2009-11-10T23:00:00Z"]))
917 if pd1.index.tzinfo is None:
918 pd1.index = pd1.index.tz_localize('UTC')
919 pd2 = pd.DataFrame(
920 [[23422], [23422], [23422]], columns=['value'],
921 index=pd.to_datetime(["2009-11-10T23:00:00Z",
922 "2009-11-10T23:00:00Z",
•923 "2009-11-10T23:00:00Z"], format='ISO8601'))
924 if pd2.index.tzinfo is None:
925 pd2.index = pd2.index.tz_localize('UTC')
926 expected = {
927 ('network', (('direction', ''),)): pd1,
928 ('network', (('direction', 'in'),)): pd2
929 }
930
931 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
932 with _mocked_session(cli, 'GET', 200, data):
933 result = cli.query('select value from network group by direction;')
934 for k in expected:
935 assert_frame_equal(expected[k], result[k])
936
937 def test_multiquery_into_dataframe(self):
938 """Test multiquery into df for TestDataFrameClient object."""
939 data = {
940 "results": [
941 {
942 "series": [
943 {
944 "name": "cpu_load_short",
945 "columns": ["time", "value"],
946 "values": [
947 ["2015-01-29T21:55:43.702900257Z", 0.55],
948 ["2015-01-29T21:55:43.702900257Z", 23422],
•949 ["2015-06-11T20:46:02.000000000Z", 0.64]
950 ]
951 }
952 ]
953 }, {
954 "series": [
955 {
956 "name": "cpu_load_short",
957 "columns": ["time", "count"],
958 "values": [
959 ["1970-01-01T00:00:00Z", 3]
960 ]
961 }
962 ]
963 }
964 ]
965 }
966
967 pd1 = pd.DataFrame(
968 [[0.55], [23422.0], [0.64]], columns=['value'],
969 index=pd.to_datetime([
970 "2015-01-29 21:55:43.702900257+0000",
971 "2015-01-29 21:55:43.702900257+0000",
•972 "2015-06-11 20:46:02.000000000+0000"]))
973 if pd1.index.tzinfo is None:
974 pd1.index = pd1.index.tz_localize('UTC')
975 pd2 = pd.DataFrame(
976 [[3]], columns=['count'],
977 index=pd.to_datetime(["1970-01-01 00:00:00+00:00"]))
978 if pd2.index.tzinfo is None:
979 pd2.index = pd2.index.tz_localize('UTC')
980 expected = [{'cpu_load_short': pd1}, {'cpu_load_short': pd2}]
981
982 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
983 iql = "SELECT value FROM cpu_load_short WHERE region=$region;"\
984 "SELECT count(value) FROM cpu_load_short WHERE region=$region"
985 bind_params = {'region': 'us-west'}
986 with _mocked_session(cli, 'GET', 200, data):
987 result = cli.query(iql, bind_params=bind_params)
988 for r, e in zip(result, expected):
989 for k in e:
990 assert_frame_equal(e[k], r[k])
991
992 def test_multiquery_into_dataframe_dropna(self):
993 """Test multiquery into df for TestDataFrameClient object."""
994 data = {
995 "results": [
996 {
997 "series": [
998 {
999 "name": "cpu_load_short",
1000 "columns": ["time", "value", "value2", "value3"],
1001 "values": [
1002 ["2015-01-29T21:55:43.702900257Z",
1003 0.55, 0.254, np.NaN],
1004 ["2015-01-29T21:55:43.702900257Z",
1005 23422, 122878, np.NaN],
•1006 ["2015-06-11T20:46:02.000000000Z",
1007 0.64, 0.5434, np.NaN]
1008 ]
1009 }
1010 ]
1011 }, {
1012 "series": [
1013 {
1014 "name": "cpu_load_short",
1015 "columns": ["time", "count"],
1016 "values": [
1017 ["1970-01-01T00:00:00Z", 3]
1018 ]
1019 }
1020 ]
1021 }
1022 ]
1023 }
1024
1025 pd1 = pd.DataFrame(
1026 [[0.55, 0.254, np.NaN],
1027 [23422.0, 122878, np.NaN],
1028 [0.64, 0.5434, np.NaN]],
1029 columns=['value', 'value2', 'value3'],
1030 index=pd.to_datetime([
1031 "2015-01-29 21:55:43.702900257+0000",
1032 "2015-01-29 21:55:43.702900257+0000",
•1033 "2015-06-11 20:46:02.000000000+0000"]))
1034
1035 if pd1.index.tzinfo is None:
1036 pd1.index = pd1.index.tz_localize('UTC')
1037
1038 pd1_dropna = pd.DataFrame(
1039 [[0.55, 0.254], [23422.0, 122878], [0.64, 0.5434]],
1040 columns=['value', 'value2'],
1041 index=pd.to_datetime([
1042 "2015-01-29 21:55:43.702900257+0000",
1043 "2015-01-29 21:55:43.702900257+0000",
•1044 "2015-06-11 20:46:02.000000000+0000"]))
1045
1046 if pd1_dropna.index.tzinfo is None:
1047 pd1_dropna.index = pd1_dropna.index.tz_localize('UTC')
1048
1049 pd2 = pd.DataFrame(
1050 [[3]], columns=['count'],
1051 index=pd.to_datetime(["1970-01-01 00:00:00+00:00"]))
1052
1053 if pd2.index.tzinfo is None:
1054 pd2.index = pd2.index.tz_localize('UTC')
1055
1056 expected_dropna_true = [
1057 {'cpu_load_short': pd1_dropna},
1058 {'cpu_load_short': pd2}]
1059 expected_dropna_false = [
1060 {'cpu_load_short': pd1},
1061 {'cpu_load_short': pd2}]
1062
1063 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
1064 iql = "SELECT value FROM cpu_load_short WHERE region=$region;" \
1065 "SELECT count(value) FROM cpu_load_short WHERE region=$region"
1066 bind_params = {'region': 'us-west'}
1067
1068 for dropna in [True, False]:
1069 with _mocked_session(cli, 'GET', 200, data):
1070 result = cli.query(iql, bind_params=bind_params, dropna=dropna)
1071 expected = \
1072 expected_dropna_true if dropna else expected_dropna_false
1073 for r, e in zip(result, expected):
1074 for k in e:
1075 assert_frame_equal(e[k], r[k])
1076
1077 # test default value (dropna = True)
1078 with _mocked_session(cli, 'GET', 200, data):
1079 result = cli.query(iql, bind_params=bind_params)
1080 for r, e in zip(result, expected_dropna_true):
1081 for k in e:
1082 assert_frame_equal(e[k], r[k])
1083
1084 def test_query_with_empty_result(self):
1085 """Test query with empty results in TestDataFrameClient object."""
1086 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
1087 with _mocked_session(cli, 'GET', 200, {"results": [{}]}):
1088 result = cli.query('select column_one from foo;')
1089 self.assertEqual(result, {})
1090
1091 def test_get_list_database(self):
1092 """Test get list of databases in TestDataFrameClient object."""
1093 data = {'results': [
1094 {'series': [
1095 {'measurement': 'databases',
1096 'values': [
1097 ['new_db_1'],
1098 ['new_db_2']],
1099 'columns': ['name']}]}
1100 ]}
1101
1102 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
1103 with _mocked_session(cli, 'get', 200, json.dumps(data)):
1104 self.assertListEqual(
1105 cli.get_list_database(),
1106 [{'name': 'new_db_1'}, {'name': 'new_db_2'}]
1107 )
1108
1109 def test_datetime_to_epoch(self):
1110 """Test convert datetime to epoch in TestDataFrameClient object."""
1111 timestamp = pd.Timestamp('2013-01-01 00:00:00.000+00:00')
1112 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
1113
1114 self.assertEqual(
1115 cli._datetime_to_epoch(timestamp),
1116 1356998400.0
1117 )
1118 self.assertEqual(
1119 cli._datetime_to_epoch(timestamp, time_precision='h'),
1120 1356998400.0 / 3600
1121 )
1122 self.assertEqual(
1123 cli._datetime_to_epoch(timestamp, time_precision='m'),
1124 1356998400.0 / 60
1125 )
1126 self.assertEqual(
1127 cli._datetime_to_epoch(timestamp, time_precision='s'),
1128 1356998400.0
1129 )
1130 self.assertEqual(
1131 cli._datetime_to_epoch(timestamp, time_precision='ms'),
1132 1356998400000.0
1133 )
1134 self.assertEqual(
1135 cli._datetime_to_epoch(timestamp, time_precision='u'),
1136 1356998400000000.0
1137 )
1138 self.assertEqual(
1139 cli._datetime_to_epoch(timestamp, time_precision='n'),
1140 1356998400000000000.0
1141 )
1142
1143 def test_dsn_constructor(self):
1144 """Test data source name deconstructor in TestDataFrameClient."""
1145 client = DataFrameClient.from_dsn('influxdb://localhost:8086')
1146 self.assertIsInstance(client, DataFrameClient)
1147 self.assertEqual('http://localhost:8086', client._baseurl)
1148
1149 def test_write_points_from_dataframe_with_nan_line(self):
1150 """Test write points from dataframe with Nan lines."""
1151 now = pd.Timestamp('1970-01-01 00:00+00:00')
1152 dataframe = pd.DataFrame(data=[["1", 1, np.inf], ["2", 2, np.nan]],
1153 index=[now, now + timedelta(hours=1)],
1154 columns=["column_one", "column_two",
1155 "column_three"])
1156 expected = (
1157 b"foo column_one=\"1\",column_two=1i 0\n"
1158 b"foo column_one=\"2\",column_two=2i "
1159 b"3600000000000\n"
1160 )
1161
1162 with requests_mock.Mocker() as m:
1163 m.register_uri(requests_mock.POST,
1164 "http://localhost:8086/write",
1165 status_code=204)
1166
1167 cli = DataFrameClient(database='db')
1168
1169 cli.write_points(dataframe, 'foo', protocol='line')
1170 self.assertEqual(m.last_request.body, expected)
1171
1172 cli.write_points(dataframe, 'foo', tags=None, protocol='line')
1173 self.assertEqual(m.last_request.body, expected)
1174
1175 def test_write_points_from_dataframe_with_nan_json(self):
1176 """Test write points from json with NaN lines."""
1177 now = pd.Timestamp('1970-01-01 00:00+00:00')
1178 dataframe = pd.DataFrame(data=[["1", 1, np.inf], ["2", 2, np.nan]],
1179 index=[now, now + timedelta(hours=1)],
1180 columns=["column_one", "column_two",
1181 "column_three"])
1182 expected = (
1183 b"foo column_one=\"1\",column_two=1i 0\n"
1184 b"foo column_one=\"2\",column_two=2i "
1185 b"3600000000000\n"
1186 )
1187
1188 with requests_mock.Mocker() as m:
1189 m.register_uri(requests_mock.POST,
1190 "http://localhost:8086/write",
1191 status_code=204)
1192
1193 cli = DataFrameClient(database='db')
1194
1195 cli.write_points(dataframe, 'foo', protocol='json')
1196 self.assertEqual(m.last_request.body, expected)
1197
1198 cli.write_points(dataframe, 'foo', tags=None, protocol='json')
1199 self.assertEqual(m.last_request.body, expected)
1200
1201 def test_write_points_from_dataframe_with_tags_and_nan_line(self):
1202 """Test write points from dataframe with NaN lines and tags."""
1203 now = pd.Timestamp('1970-01-01 00:00+00:00')
1204 dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, np.inf],
1205 ['red', 0, "2", 2, np.nan]],
1206 index=[now, now + timedelta(hours=1)],
1207 columns=["tag_one", "tag_two", "column_one",
1208 "column_two", "column_three"])
1209 expected = (
1210 b"foo,tag_one=blue,tag_two=1 "
1211 b"column_one=\"1\",column_two=1i "
1212 b"0\n"
1213 b"foo,tag_one=red,tag_two=0 "
1214 b"column_one=\"2\",column_two=2i "
1215 b"3600000000000\n"
1216 )
1217
1218 with requests_mock.Mocker() as m:
1219 m.register_uri(requests_mock.POST,
1220 "http://localhost:8086/write",
1221 status_code=204)
1222
1223 cli = DataFrameClient(database='db')
1224
1225 cli.write_points(dataframe, 'foo', protocol='line',
1226 tag_columns=['tag_one', 'tag_two'])
1227 self.assertEqual(m.last_request.body, expected)
1228
1229 cli.write_points(dataframe, 'foo', tags=None, protocol='line',
1230 tag_columns=['tag_one', 'tag_two'])
1231 self.assertEqual(m.last_request.body, expected)
1232
1233 def test_query_custom_index(self):
1234 """Test query with custom indexes."""
1235 data = {
1236 "results": [
1237 {
1238 "series": [
1239 {
1240 "name": "cpu_load_short",
1241 "columns": ["time", "value", "host"],
1242 "values": [
1243 [1, 0.55, "local"],
1244 [2, 23422, "local"],
1245 [3, 0.64, "local"]
1246 ]
1247 }
1248 ]
1249 }
1250 ]
1251 }
1252
1253 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
1254 iql = "SELECT value FROM cpu_load_short WHERE region=$region;" \
1255 "SELECT count(value) FROM cpu_load_short WHERE region=$region"
1256 bind_params = {'region': 'us-west'}
1257 with _mocked_session(cli, 'GET', 200, data):
1258 result = cli.query(iql, bind_params=bind_params,
1259 data_frame_index=["time", "host"])
1260
1261 _data_frame = result['cpu_load_short']
1262 print(_data_frame)
1263
1264 self.assertListEqual(["time", "host"],
1265 list(_data_frame.index.names))
1266
1267 def test_dataframe_nanosecond_precision(self):
1268 """Test nanosecond precision."""
1269 for_df_dict = {
1270 "nanFloats": [1.1, float('nan'), 3.3, 4.4],
1271 "onlyFloats": [1.1, 2.2, 3.3, 4.4],
1272 "strings": ['one_one', 'two_two', 'three_three', 'four_four']
1273 }
1274 df = pd.DataFrame.from_dict(for_df_dict)
1275 df['time'] = ['2019-10-04 06:27:19.850557111+00:00',
1276 '2019-10-04 06:27:19.850557184+00:00',
1277 '2019-10-04 06:27:42.251396864+00:00',
1278 '2019-10-04 06:27:42.251396974+00:00']
1279 df['time'] = pd.to_datetime(df['time'], unit='ns')
1280 df = df.set_index('time')
1281
1282 expected = (
1283 b'foo nanFloats=1.1,onlyFloats=1.1,strings="one_one" 1570170439850557111\n' # noqa E501 line too long
1284 b'foo onlyFloats=2.2,strings="two_two" 1570170439850557184\n' # noqa E501 line too long
1285 b'foo nanFloats=3.3,onlyFloats=3.3,strings="three_three" 1570170462251396864\n' # noqa E501 line too long
1286 b'foo nanFloats=4.4,onlyFloats=4.4,strings="four_four" 1570170462251396974\n' # noqa E501 line too long
1287 )
1288
1289 with requests_mock.Mocker() as m:
1290 m.register_uri(
1291 requests_mock.POST,
1292 "http://localhost:8086/write",
1293 status_code=204
1294 )
1295
1296 cli = DataFrameClient(database='db')
1297 cli.write_points(df, 'foo', time_precision='n')
1298
1299 self.assertEqual(m.last_request.body, expected)
1300
1301 def test_dataframe_nanosecond_precision_one_microsecond(self):
1302 """Test nanosecond precision within one microsecond."""
1303 # 1 microsecond = 1000 nanoseconds
1304 start = np.datetime64('2019-10-04T06:27:19.850557000')
1305 end = np.datetime64('2019-10-04T06:27:19.850558000')
1306
1307 # generate timestamps with nanosecond precision
1308 timestamps = np.arange(
1309 start,
1310 end + np.timedelta64(1, 'ns'),
1311 np.timedelta64(1, 'ns')
1312 )
1313 # generate values
1314 values = np.arange(0.0, len(timestamps))
1315
1316 df = pd.DataFrame({'value': values}, index=timestamps)
1317 with requests_mock.Mocker() as m:
1318 m.register_uri(
1319 requests_mock.POST,
1320 "http://localhost:8086/write",
1321 status_code=204
1322 )
1323
1324 cli = DataFrameClient(database='db')
1325 cli.write_points(df, 'foo', time_precision='n')
1326
1327 lines = m.last_request.body.decode('utf-8').split('\n')
1328 self.assertEqual(len(lines), 1002)
1329
1330 for index, line in enumerate(lines):
1331 if index == 1001:
1332 self.assertEqual(line, '')
1333 continue
1334 self.assertEqual(
1335 line,
1336 f"foo value={index}.0 157017043985055{7000 + index:04}"
1337 )