Debian Codegraph @

influxdb/tests/dataframe_client_test.py

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