dataframe_client_test.py 50 KB

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