Debian Codegraph @

influxdb/tests/influxdb08/dataframe_client_test.py

raw ◀ ▶
2 Debian patches touch this file
1 # -*- coding: utf-8 -*-
2 """Unit tests for misc module."""
3
4 from datetime import timedelta
5
6 import copy
7 import json
8 import unittest
9 import warnings
10
11 import requests_mock
12
•13 from functools import wraps
14
15 def raises(*exceptions):
16 valid = ' or '.join([e.__name__ for e in exceptions])
17
18 def decorate(func):
19 name = func.__name__
20 def newfunc(*arg, **kw):
21 try:
22 func(*arg, **kw)
23 except exceptions:
24 pass
25 except:
26 raise
27 else:
28 message = "%s() did not raise %s" % (name, valid)
29 raise AssertionError(message)
30 newfunc = wraps(func)(newfunc)
31 return newfunc
32 return decorate
33
34 from influxdb.tests import skip_if_pypy, using_pypy
35
36 from .client_test import _mocked_session
37
38 if not using_pypy:
39 import pandas as pd
•40 from pandas.testing import assert_frame_equal
41 from influxdb.influxdb08 import DataFrameClient
42
43
44 @skip_if_pypy
45 class TestDataFrameClient(unittest.TestCase):
46 """Define the DataFramClient test object."""
47
48 def setUp(self):
49 """Set up an instance of TestDataFrameClient object."""
50 # By default, raise exceptions on warnings
51 warnings.simplefilter('error', FutureWarning)
52
53 def test_write_points_from_dataframe(self):
54 """Test write points from dataframe."""
55 now = pd.Timestamp('1970-01-01 00:00+00:00')
56 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
57 index=[now, now + timedelta(hours=1)],
58 columns=["column_one", "column_two",
59 "column_three"])
60 points = [
61 {
62 "points": [
63 ["1", 1, 1.0, 0],
64 ["2", 2, 2.0, 3600]
65 ],
66 "name": "foo",
67 "columns": ["column_one", "column_two", "column_three", "time"]
68 }
69 ]
70
71 with requests_mock.Mocker() as m:
72 m.register_uri(requests_mock.POST,
73 "http://localhost:8086/db/db/series")
74
75 cli = DataFrameClient(database='db')
76 cli.write_points({"foo": dataframe})
77
78 self.assertListEqual(json.loads(m.last_request.body), points)
79
80 def test_write_points_from_dataframe_with_float_nan(self):
81 """Test write points from dataframe with NaN float."""
82 now = pd.Timestamp('1970-01-01 00:00+00:00')
83 dataframe = pd.DataFrame(data=[[1, float("NaN"), 1.0], [2, 2, 2.0]],
84 index=[now, now + timedelta(hours=1)],
85 columns=["column_one", "column_two",
86 "column_three"])
87 points = [
88 {
89 "points": [
90 [1, None, 1.0, 0],
91 [2, 2, 2.0, 3600]
92 ],
93 "name": "foo",
94 "columns": ["column_one", "column_two", "column_three", "time"]
95 }
96 ]
97
98 with requests_mock.Mocker() as m:
99 m.register_uri(requests_mock.POST,
100 "http://localhost:8086/db/db/series")
101
102 cli = DataFrameClient(database='db')
103 cli.write_points({"foo": dataframe})
104
105 self.assertListEqual(json.loads(m.last_request.body), points)
106
107 def test_write_points_from_dataframe_in_batches(self):
108 """Test write points from dataframe in batches."""
109 now = pd.Timestamp('1970-01-01 00:00+00:00')
110 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
111 index=[now, now + timedelta(hours=1)],
112 columns=["column_one", "column_two",
113 "column_three"])
114 with requests_mock.Mocker() as m:
115 m.register_uri(requests_mock.POST,
116 "http://localhost:8086/db/db/series")
117
118 cli = DataFrameClient(database='db')
119 self.assertTrue(cli.write_points({"foo": dataframe}, batch_size=1))
120
121 def test_write_points_from_dataframe_with_numeric_column_names(self):
122 """Test write points from dataframe with numeric columns."""
123 now = pd.Timestamp('1970-01-01 00:00+00:00')
124 # df with numeric column names
125 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
126 index=[now, now + timedelta(hours=1)])
127 points = [
128 {
129 "points": [
130 ["1", 1, 1.0, 0],
131 ["2", 2, 2.0, 3600]
132 ],
133 "name": "foo",
134 "columns": ['0', '1', '2', "time"]
135 }
136 ]
137
138 with requests_mock.Mocker() as m:
139 m.register_uri(requests_mock.POST,
140 "http://localhost:8086/db/db/series")
141
142 cli = DataFrameClient(database='db')
143 cli.write_points({"foo": dataframe})
144
145 self.assertListEqual(json.loads(m.last_request.body), points)
146
147 def test_write_points_from_dataframe_with_period_index(self):
148 """Test write points from dataframe with period index."""
149 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
150 index=[pd.Period('1970-01-01'),
151 pd.Period('1970-01-02')],
152 columns=["column_one", "column_two",
153 "column_three"])
154 points = [
155 {
156 "points": [
157 ["1", 1, 1.0, 0],
158 ["2", 2, 2.0, 86400]
159 ],
160 "name": "foo",
161 "columns": ["column_one", "column_two", "column_three", "time"]
162 }
163 ]
164
165 with requests_mock.Mocker() as m:
166 m.register_uri(requests_mock.POST,
167 "http://localhost:8086/db/db/series")
168
169 cli = DataFrameClient(database='db')
170 cli.write_points({"foo": dataframe})
171
172 self.assertListEqual(json.loads(m.last_request.body), points)
173
174 def test_write_points_from_dataframe_with_time_precision(self):
175 """Test write points from dataframe with time precision."""
176 now = pd.Timestamp('1970-01-01 00:00+00:00')
177 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
178 index=[now, now + timedelta(hours=1)],
179 columns=["column_one", "column_two",
180 "column_three"])
181 points = [
182 {
183 "points": [
184 ["1", 1, 1.0, 0],
185 ["2", 2, 2.0, 3600]
186 ],
187 "name": "foo",
188 "columns": ["column_one", "column_two", "column_three", "time"]
189 }
190 ]
191
192 points_ms = copy.deepcopy(points)
193 points_ms[0]["points"][1][-1] = 3600 * 1000
194
195 points_us = copy.deepcopy(points)
196 points_us[0]["points"][1][-1] = 3600 * 1000000
197
198 with requests_mock.Mocker() as m:
199 m.register_uri(requests_mock.POST,
200 "http://localhost:8086/db/db/series")
201
202 cli = DataFrameClient(database='db')
203
204 cli.write_points({"foo": dataframe}, time_precision='s')
205 self.assertListEqual(json.loads(m.last_request.body), points)
206
207 cli.write_points({"foo": dataframe}, time_precision='m')
208 self.assertListEqual(json.loads(m.last_request.body), points_ms)
209
210 cli.write_points({"foo": dataframe}, time_precision='u')
211 self.assertListEqual(json.loads(m.last_request.body), points_us)
212
213 @raises(TypeError)
214 def test_write_points_from_dataframe_fails_without_time_index(self):
215 """Test write points from dataframe that fails without time index."""
216 dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
217 columns=["column_one", "column_two",
218 "column_three"])
219
220 with requests_mock.Mocker() as m:
221 m.register_uri(requests_mock.POST,
222 "http://localhost:8086/db/db/series")
223
224 cli = DataFrameClient(database='db')
225 cli.write_points({"foo": dataframe})
226
227 @raises(TypeError)
228 def test_write_points_from_dataframe_fails_with_series(self):
229 """Test failed write points from dataframe with series."""
230 now = pd.Timestamp('1970-01-01 00:00+00:00')
231 dataframe = pd.Series(data=[1.0, 2.0],
232 index=[now, now + timedelta(hours=1)])
233
234 with requests_mock.Mocker() as m:
235 m.register_uri(requests_mock.POST,
236 "http://localhost:8086/db/db/series")
237
238 cli = DataFrameClient(database='db')
239 cli.write_points({"foo": dataframe})
240
241 def test_query_into_dataframe(self):
242 """Test query into a dataframe."""
243 data = [
244 {
245 "name": "foo",
246 "columns": ["time", "sequence_number", "column_one"],
247 "points": [
248 [3600, 16, 2], [3600, 15, 1],
249 [0, 14, 2], [0, 13, 1]
250 ]
251 }
252 ]
253 # dataframe sorted ascending by time first, then sequence_number
254 dataframe = pd.DataFrame(data=[[13, 1], [14, 2], [15, 1], [16, 2]],
255 index=pd.to_datetime([0, 0,
256 3600, 3600],
257 unit='s', utc=True),
258 columns=['sequence_number', 'column_one'])
259 with _mocked_session('get', 200, data):
260 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
261 result = cli.query('select column_one from foo;')
262 assert_frame_equal(dataframe, result)
263
264 def test_query_multiple_time_series(self):
265 """Test query for multiple time series."""
266 data = [
267 {
268 "name": "series1",
269 "columns": ["time", "mean", "min", "max", "stddev"],
270 "points": [[0, 323048, 323048, 323048, 0]]
271 },
272 {
273 "name": "series2",
274 "columns": ["time", "mean", "min", "max", "stddev"],
275 "points": [[0, -2.8233, -2.8503, -2.7832, 0.0173]]
276 },
277 {
278 "name": "series3",
279 "columns": ["time", "mean", "min", "max", "stddev"],
280 "points": [[0, -0.01220, -0.01220, -0.01220, 0]]
281 }
282 ]
283 dataframes = {
284 'series1': pd.DataFrame(data=[[323048, 323048, 323048, 0]],
285 index=pd.to_datetime([0], unit='s',
286 utc=True),
287 columns=['mean', 'min', 'max', 'stddev']),
288 'series2': pd.DataFrame(data=[[-2.8233, -2.8503, -2.7832, 0.0173]],
289 index=pd.to_datetime([0], unit='s',
290 utc=True),
291 columns=['mean', 'min', 'max', 'stddev']),
292 'series3': pd.DataFrame(data=[[-0.01220, -0.01220, -0.01220, 0]],
293 index=pd.to_datetime([0], unit='s',
294 utc=True),
295 columns=['mean', 'min', 'max', 'stddev'])
296 }
297 with _mocked_session('get', 200, data):
298 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
299 result = cli.query("""select mean(value), min(value), max(value),
300 stddev(value) from series1, series2, series3""")
301 self.assertEqual(dataframes.keys(), result.keys())
302 for key in dataframes.keys():
303 assert_frame_equal(dataframes[key], result[key])
304
305 def test_query_with_empty_result(self):
306 """Test query with empty results."""
307 with _mocked_session('get', 200, []):
308 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
309 result = cli.query('select column_one from foo;')
310 self.assertEqual(result, [])
311
312 def test_list_series(self):
313 """Test list of series for dataframe object."""
314 response = [
315 {
316 'columns': ['time', 'name'],
317 'name': 'list_series_result',
318 'points': [[0, 'seriesA'], [0, 'seriesB']]
319 }
320 ]
321 with _mocked_session('get', 200, response):
322 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
323 series_list = cli.get_list_series()
324 self.assertEqual(series_list, ['seriesA', 'seriesB'])
325
326 def test_datetime_to_epoch(self):
327 """Test convert datetime to epoch."""
328 timestamp = pd.Timestamp('2013-01-01 00:00:00.000+00:00')
329 cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
330
331 self.assertEqual(
332 cli._datetime_to_epoch(timestamp),
333 1356998400.0
334 )
335 self.assertEqual(
336 cli._datetime_to_epoch(timestamp, time_precision='s'),
337 1356998400.0
338 )
339 self.assertEqual(
340 cli._datetime_to_epoch(timestamp, time_precision='m'),
341 1356998400000.0
342 )
343 self.assertEqual(
344 cli._datetime_to_epoch(timestamp, time_precision='ms'),
345 1356998400000.0
346 )
347 self.assertEqual(
348 cli._datetime_to_epoch(timestamp, time_precision='u'),
349 1356998400000000.0
350 )