You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

674 lines
26 KiB

  1. # -*- coding: utf-8 -*-
  2. import nilmdb.server
  3. import nilmdb.client
  4. from nilmdb.utils.printf import *
  5. from nilmdb.utils import timestamper
  6. from nilmdb.client import ClientError, ServerError
  7. from nilmdb.utils import datetime_tz
  8. from nose.plugins.skip import SkipTest
  9. from nose.tools import *
  10. from nose.tools import assert_raises
  11. import itertools
  12. import distutils.version
  13. import os
  14. import sys
  15. import threading
  16. import cStringIO
  17. import simplejson as json
  18. import unittest
  19. import warnings
  20. import resource
  21. import time
  22. import re
  23. from testutil.helpers import *
  24. testdb = "tests/client-testdb"
  25. testurl = "http://localhost:32180/"
  26. def setup_module():
  27. global test_server, test_db
  28. # Clear out DB
  29. recursive_unlink(testdb)
  30. # Start web app on a custom port
  31. test_db = nilmdb.utils.serializer_proxy(nilmdb.server.NilmDB)(testdb)
  32. test_server = nilmdb.server.Server(test_db, host = "127.0.0.1",
  33. port = 32180, stoppable = False,
  34. fast_shutdown = True,
  35. force_traceback = True)
  36. test_server.start(blocking = False)
  37. def teardown_module():
  38. global test_server, test_db
  39. # Close web app
  40. test_server.stop()
  41. test_db.close()
  42. class TestClient(object):
  43. def test_client_01_basic(self):
  44. # Test a fake host
  45. client = nilmdb.client.Client(url = "http://localhost:1/")
  46. with assert_raises(nilmdb.client.ServerError):
  47. client.version()
  48. client.close()
  49. # Then a fake URL on a real host
  50. client = nilmdb.client.Client(url = "http://localhost:32180/fake/")
  51. with assert_raises(nilmdb.client.ClientError):
  52. client.version()
  53. client.close()
  54. # Now a real URL with no http:// prefix
  55. client = nilmdb.client.Client(url = "localhost:32180")
  56. version = client.version()
  57. client.close()
  58. # Now use the real URL
  59. client = nilmdb.client.Client(url = testurl)
  60. version = client.version()
  61. eq_(distutils.version.LooseVersion(version),
  62. distutils.version.LooseVersion(test_server.version))
  63. # Bad URLs should give 404, not 500
  64. with assert_raises(ClientError):
  65. client.http.get("/stream/create")
  66. client.close()
  67. def test_client_02_createlist(self):
  68. # Basic stream tests, like those in test_nilmdb:test_stream
  69. client = nilmdb.client.Client(url = testurl)
  70. # Database starts empty
  71. eq_(client.stream_list(), [])
  72. # Bad path
  73. with assert_raises(ClientError):
  74. client.stream_create("foo/bar/baz", "float32_8")
  75. with assert_raises(ClientError):
  76. client.stream_create("/foo", "float32_8")
  77. # Bad layout type
  78. with assert_raises(ClientError):
  79. client.stream_create("/newton/prep", "NoSuchLayout")
  80. # Bad method types
  81. with assert_raises(ClientError):
  82. client.http.put("/stream/list","")
  83. # Try a bunch of times to make sure the request body is getting consumed
  84. for x in range(10):
  85. with assert_raises(ClientError):
  86. client.http.post("/stream/list")
  87. client = nilmdb.client.Client(url = testurl)
  88. # Create three streams
  89. client.stream_create("/newton/prep", "float32_8")
  90. client.stream_create("/newton/raw", "uint16_6")
  91. client.stream_create("/newton/zzz/rawnotch", "uint16_9")
  92. # Verify we got 3 streams
  93. eq_(client.stream_list(), [ ["/newton/prep", "float32_8"],
  94. ["/newton/raw", "uint16_6"],
  95. ["/newton/zzz/rawnotch", "uint16_9"]
  96. ])
  97. # Match just one type or one path
  98. eq_(client.stream_list(layout="uint16_6"),
  99. [ ["/newton/raw", "uint16_6"] ])
  100. eq_(client.stream_list(path="/newton/raw"),
  101. [ ["/newton/raw", "uint16_6"] ])
  102. # Try messing with resource limits to trigger errors and get
  103. # more coverage. Here, make it so we can only create files 1
  104. # byte in size, which will trigger an IOError in the server when
  105. # we create a table.
  106. limit = resource.getrlimit(resource.RLIMIT_FSIZE)
  107. resource.setrlimit(resource.RLIMIT_FSIZE, (1, limit[1]))
  108. with assert_raises(ServerError) as e:
  109. client.stream_create("/newton/hello", "uint16_6")
  110. resource.setrlimit(resource.RLIMIT_FSIZE, limit)
  111. client.close()
  112. def test_client_03_metadata(self):
  113. client = nilmdb.client.Client(url = testurl)
  114. # Set / get metadata
  115. eq_(client.stream_get_metadata("/newton/prep"), {})
  116. eq_(client.stream_get_metadata("/newton/raw"), {})
  117. meta1 = { "description": "The Data",
  118. "v_scale": "1.234" }
  119. meta2 = { "description": "The Data" }
  120. meta3 = { "v_scale": "1.234" }
  121. client.stream_set_metadata("/newton/prep", meta1)
  122. client.stream_update_metadata("/newton/prep", {})
  123. client.stream_update_metadata("/newton/raw", meta2)
  124. client.stream_update_metadata("/newton/raw", meta3)
  125. eq_(client.stream_get_metadata("/newton/prep"), meta1)
  126. eq_(client.stream_get_metadata("/newton/raw"), meta1)
  127. eq_(client.stream_get_metadata("/newton/raw",
  128. [ "description" ] ), meta2)
  129. eq_(client.stream_get_metadata("/newton/raw",
  130. [ "description", "v_scale" ] ), meta1)
  131. # missing key
  132. eq_(client.stream_get_metadata("/newton/raw", "descr"),
  133. { "descr": None })
  134. eq_(client.stream_get_metadata("/newton/raw", [ "descr" ]),
  135. { "descr": None })
  136. # test wrong types (list instead of dict)
  137. with assert_raises(ClientError):
  138. client.stream_set_metadata("/newton/prep", [1,2,3])
  139. with assert_raises(ClientError):
  140. client.stream_update_metadata("/newton/prep", [1,2,3])
  141. # test wrong types (dict of non-strings)
  142. # numbers are OK; they'll get converted to strings
  143. client.stream_set_metadata("/newton/prep", { "hello": 1234 })
  144. # anything else is not
  145. with assert_raises(ClientError):
  146. client.stream_set_metadata("/newton/prep", { "world": { 1: 2 } })
  147. with assert_raises(ClientError):
  148. client.stream_set_metadata("/newton/prep", { "world": [ 1, 2 ] })
  149. client.close()
  150. def test_client_04_insert(self):
  151. client = nilmdb.client.Client(url = testurl)
  152. # Limit _max_data to 1 MB, since our test file is 1.5 MB
  153. old_max_data = nilmdb.client.client.StreamInserter._max_data
  154. nilmdb.client.client.StreamInserter._max_data = 1 * 1024 * 1024
  155. datetime_tz.localtz_set("America/New_York")
  156. testfile = "tests/data/prep-20120323T1000"
  157. start = nilmdb.utils.time.parse_time("20120323T1000")
  158. rate = 120
  159. # First try a nonexistent path
  160. data = timestamper.TimestamperRate(testfile, start, 120)
  161. with assert_raises(ClientError) as e:
  162. result = client.stream_insert("/newton/no-such-path", data)
  163. in_("404 Not Found", str(e.exception))
  164. # Now try reversed timestamps
  165. data = timestamper.TimestamperRate(testfile, start, 120)
  166. data = reversed(list(data))
  167. with assert_raises(ClientError) as e:
  168. result = client.stream_insert("/newton/prep", data)
  169. in_("400 Bad Request", str(e.exception))
  170. in2_("timestamp is not monotonically increasing",
  171. "start must precede end", str(e.exception))
  172. # Now try empty data (no server request made)
  173. empty = cStringIO.StringIO("")
  174. data = timestamper.TimestamperRate(empty, start, 120)
  175. result = client.stream_insert("/newton/prep", data)
  176. eq_(result, None)
  177. # It's OK to insert an empty interval
  178. client.http.put("stream/insert", "", { "path": "/newton/prep",
  179. "start": 1, "end": 2 })
  180. eq_(list(client.stream_intervals("/newton/prep")), [[1, 2]])
  181. client.stream_remove("/newton/prep")
  182. eq_(list(client.stream_intervals("/newton/prep")), [])
  183. # Timestamps can be negative too
  184. client.http.put("stream/insert", "", { "path": "/newton/prep",
  185. "start": -2, "end": -1 })
  186. eq_(list(client.stream_intervals("/newton/prep")), [[-2, -1]])
  187. client.stream_remove("/newton/prep")
  188. eq_(list(client.stream_intervals("/newton/prep")), [])
  189. # Intervals that end at zero shouldn't be any different
  190. client.http.put("stream/insert", "", { "path": "/newton/prep",
  191. "start": -1, "end": 0 })
  192. eq_(list(client.stream_intervals("/newton/prep")), [[-1, 0]])
  193. client.stream_remove("/newton/prep")
  194. eq_(list(client.stream_intervals("/newton/prep")), [])
  195. # Try forcing a server request with equal start and end
  196. with assert_raises(ClientError) as e:
  197. client.http.put("stream/insert", "", { "path": "/newton/prep",
  198. "start": 0, "end": 0 })
  199. in_("400 Bad Request", str(e.exception))
  200. in_("start must precede end", str(e.exception))
  201. # Specify start/end (starts too late)
  202. data = timestamper.TimestamperRate(testfile, start, 120)
  203. with assert_raises(ClientError) as e:
  204. result = client.stream_insert("/newton/prep", data,
  205. start + 5000000, start + 120000000)
  206. in_("400 Bad Request", str(e.exception))
  207. in_("Data timestamp 1332511200000000 < start time 1332511205000000",
  208. str(e.exception))
  209. # Specify start/end (ends too early)
  210. data = timestamper.TimestamperRate(testfile, start, 120)
  211. with assert_raises(ClientError) as e:
  212. result = client.stream_insert("/newton/prep", data,
  213. start, start + 1000000)
  214. in_("400 Bad Request", str(e.exception))
  215. # Client chunks the input, so the exact timestamp here might change
  216. # if the chunk positions change.
  217. assert(re.search("Data timestamp 13325[0-9]+ "
  218. ">= end time 1332511201000000", str(e.exception))
  219. is not None)
  220. # Now do the real load
  221. data = timestamper.TimestamperRate(testfile, start, 120)
  222. result = client.stream_insert("/newton/prep", data,
  223. start, start + 119999777)
  224. # Verify the intervals. Should be just one, even if the data
  225. # was inserted in chunks, due to nilmdb interval concatenation.
  226. intervals = list(client.stream_intervals("/newton/prep"))
  227. eq_(intervals, [[start, start + 119999777]])
  228. # Try some overlapping data -- just insert it again
  229. data = timestamper.TimestamperRate(testfile, start, 120)
  230. with assert_raises(ClientError) as e:
  231. result = client.stream_insert("/newton/prep", data)
  232. in_("400 Bad Request", str(e.exception))
  233. in_("verlap", str(e.exception))
  234. nilmdb.client.client.StreamInserter._max_data = old_max_data
  235. client.close()
  236. def test_client_05_extractremove(self):
  237. # Misc tests for extract and remove. Most of them are in test_cmdline.
  238. client = nilmdb.client.Client(url = testurl)
  239. for x in client.stream_extract("/newton/prep",
  240. 999123000000, 999124000000):
  241. raise AssertionError("shouldn't be any data for this request")
  242. with assert_raises(ClientError) as e:
  243. client.stream_remove("/newton/prep", 123000000, 120000000)
  244. # Test count
  245. eq_(client.stream_count("/newton/prep"), 14400)
  246. client.close()
  247. def test_client_06_generators(self):
  248. # A lot of the client functionality is already tested by test_cmdline,
  249. # but this gets a bit more coverage that cmdline misses.
  250. client = nilmdb.client.Client(url = testurl)
  251. # Trigger a client error in generator
  252. start = nilmdb.utils.time.parse_time("20120323T2000")
  253. end = nilmdb.utils.time.parse_time("20120323T1000")
  254. for function in [ client.stream_intervals, client.stream_extract ]:
  255. with assert_raises(ClientError) as e:
  256. function("/newton/prep", start, end).next()
  257. in_("400 Bad Request", str(e.exception))
  258. in_("start must precede end", str(e.exception))
  259. # Trigger a curl error in generator
  260. with assert_raises(ServerError) as e:
  261. client.http.get_gen("http://nosuchurl/").next()
  262. # Trigger a curl error in generator
  263. with assert_raises(ServerError) as e:
  264. client.http.get_gen("http://nosuchurl/").next()
  265. # Check 404 for missing streams
  266. for function in [ client.stream_intervals, client.stream_extract ]:
  267. with assert_raises(ClientError) as e:
  268. function("/no/such/stream").next()
  269. in_("404 Not Found", str(e.exception))
  270. in_("No such stream", str(e.exception))
  271. client.close()
  272. def test_client_07_headers(self):
  273. # Make sure that /stream/intervals and /stream/extract
  274. # properly return streaming, chunked, text/plain response.
  275. # Pokes around in client.http internals a bit to look at the
  276. # response headers.
  277. client = nilmdb.client.Client(url = testurl)
  278. http = client.http
  279. # Use a warning rather than returning a test failure for the
  280. # transfer-encoding, so that we can still disable chunked
  281. # responses for debugging.
  282. def headers():
  283. h = ""
  284. for (k, v) in http._last_response.headers.items():
  285. h += k + ": " + v + "\n"
  286. return h.lower()
  287. # Intervals
  288. x = http.get("stream/intervals", { "path": "/newton/prep" })
  289. if "transfer-encoding: chunked" not in headers():
  290. warnings.warn("Non-chunked HTTP response for /stream/intervals")
  291. if "content-type: application/x-json-stream" not in headers():
  292. raise AssertionError("/stream/intervals content type "
  293. "is not application/x-json-stream:\n" +
  294. headers())
  295. # Extract
  296. x = http.get("stream/extract",
  297. { "path": "/newton/prep",
  298. "start": "123",
  299. "end": "124" })
  300. if "transfer-encoding: chunked" not in headers():
  301. warnings.warn("Non-chunked HTTP response for /stream/extract")
  302. if "content-type: text/plain;charset=utf-8" not in headers():
  303. raise AssertionError("/stream/extract is not text/plain:\n" +
  304. headers())
  305. client.close()
  306. def test_client_08_unicode(self):
  307. # Try both with and without posting JSON
  308. for post_json in (False, True):
  309. # Basic Unicode tests
  310. client = nilmdb.client.Client(url = testurl, post_json = post_json)
  311. # Delete streams that exist
  312. for stream in client.stream_list():
  313. client.stream_remove(stream[0])
  314. client.stream_destroy(stream[0])
  315. # Database is empty
  316. eq_(client.stream_list(), [])
  317. # Create Unicode stream, match it
  318. raw = [ u"/düsseldorf/raw", u"uint16_6" ]
  319. prep = [ u"/düsseldorf/prep", u"uint16_6" ]
  320. client.stream_create(*raw)
  321. eq_(client.stream_list(), [raw])
  322. eq_(client.stream_list(layout=raw[1]), [raw])
  323. eq_(client.stream_list(path=raw[0]), [raw])
  324. client.stream_create(*prep)
  325. eq_(client.stream_list(), [prep, raw])
  326. # Set / get metadata with Unicode keys and values
  327. eq_(client.stream_get_metadata(raw[0]), {})
  328. eq_(client.stream_get_metadata(prep[0]), {})
  329. meta1 = { u"alpha": u"α",
  330. u"β": u"beta" }
  331. meta2 = { u"alpha": u"α" }
  332. meta3 = { u"β": u"beta" }
  333. client.stream_set_metadata(prep[0], meta1)
  334. client.stream_update_metadata(prep[0], {})
  335. client.stream_update_metadata(raw[0], meta2)
  336. client.stream_update_metadata(raw[0], meta3)
  337. eq_(client.stream_get_metadata(prep[0]), meta1)
  338. eq_(client.stream_get_metadata(raw[0]), meta1)
  339. eq_(client.stream_get_metadata(raw[0], [ "alpha" ]), meta2)
  340. eq_(client.stream_get_metadata(raw[0], [ "alpha", "β" ]), meta1)
  341. client.close()
  342. def test_client_09_closing(self):
  343. # Make sure we actually close sockets correctly. New
  344. # connections will block for a while if they're not, since the
  345. # server will stop accepting new connections.
  346. for test in [1, 2]:
  347. start = time.time()
  348. for i in range(50):
  349. if time.time() - start > 15:
  350. raise AssertionError("Connections seem to be blocking... "
  351. "probably not closing properly.")
  352. if test == 1:
  353. # explicit close
  354. client = nilmdb.client.Client(url = testurl)
  355. with assert_raises(ClientError) as e:
  356. client.stream_remove("/newton/prep", 123, 120)
  357. client.close() # remove this to see the failure
  358. elif test == 2:
  359. # use the context manager
  360. with nilmdb.client.Client(url = testurl) as c:
  361. with assert_raises(ClientError) as e:
  362. c.stream_remove("/newton/prep", 123, 120)
  363. def test_client_10_context(self):
  364. # Test using the client's stream insertion context manager to
  365. # insert data.
  366. client = nilmdb.client.Client(testurl)
  367. client.stream_create("/context/test", "uint16_1")
  368. with client.stream_insert_context("/context/test") as ctx:
  369. # override _max_data to trigger frequent server updates
  370. ctx._max_data = 15
  371. ctx.insert("100 1\n")
  372. ctx.insert("101 ")
  373. ctx.insert("1\n102 1")
  374. ctx.insert("")
  375. ctx.insert("\n103 1\n")
  376. ctx.insert("104 1\n")
  377. ctx.insert("# hello\n")
  378. ctx.insert(" # hello\n")
  379. ctx.insert(" 105 1\n")
  380. ctx.finalize()
  381. ctx.insert("107 1\n")
  382. ctx.update_end(108)
  383. ctx.finalize()
  384. ctx.update_start(109)
  385. ctx.insert("110 1\n")
  386. ctx.insert("111 1\n")
  387. ctx.insert("112 1\n")
  388. ctx.insert("113 1\n")
  389. ctx.insert("114 1\n")
  390. ctx.update_end(116)
  391. ctx.insert("115 1\n")
  392. ctx.update_end(117)
  393. ctx.insert("116 1\n")
  394. ctx.update_end(118)
  395. ctx.insert("117 1" +
  396. " # this is super long" * 100 +
  397. "\n")
  398. ctx.finalize()
  399. ctx.insert("# this is super long" * 100)
  400. with assert_raises(ClientError):
  401. with client.stream_insert_context("/context/test", 100, 200) as ctx:
  402. ctx.insert("118 1\n")
  403. with assert_raises(ClientError):
  404. with client.stream_insert_context("/context/test", 200, 300) as ctx:
  405. ctx.insert("118 1\n")
  406. with assert_raises(ClientError):
  407. with client.stream_insert_context("/context/test") as ctx:
  408. ctx.insert("bogus data\n")
  409. with client.stream_insert_context("/context/test", 200, 300) as ctx:
  410. # make sure our override wasn't permanent
  411. ne_(ctx._max_data, 15)
  412. ctx.insert("225 1\n")
  413. ctx.finalize()
  414. with assert_raises(ClientError):
  415. with client.stream_insert_context("/context/test", 300, 400) as ctx:
  416. ctx.insert("301 1\n")
  417. ctx.insert("302 2\n")
  418. ctx.insert("303 3\n")
  419. ctx.insert("304 4\n")
  420. ctx.insert("304 4\n") # non-monotonic after a few lines
  421. ctx.finalize()
  422. eq_(list(client.stream_intervals("/context/test")),
  423. [ [ 100, 106 ],
  424. [ 107, 108 ],
  425. [ 109, 118 ],
  426. [ 200, 300 ] ])
  427. # destroy stream (try without removing data first)
  428. with assert_raises(ClientError):
  429. client.stream_destroy("/context/test")
  430. client.stream_remove("/context/test")
  431. client.stream_destroy("/context/test")
  432. client.close()
  433. def test_client_11_emptyintervals(self):
  434. # Empty intervals are ok! If recording detection events
  435. # by inserting rows into the database, we want to be able to
  436. # have an interval where no events occurred. Test them here.
  437. client = nilmdb.client.Client(testurl)
  438. client.stream_create("/empty/test", "uint16_1")
  439. def info():
  440. result = []
  441. for interval in list(client.stream_intervals("/empty/test")):
  442. result.append((client.stream_count("/empty/test", *interval),
  443. interval))
  444. return result
  445. eq_(info(), [])
  446. # Insert a region with just a few points
  447. with client.stream_insert_context("/empty/test") as ctx:
  448. ctx.update_start(100)
  449. ctx.insert("140 1\n")
  450. ctx.insert("150 1\n")
  451. ctx.insert("160 1\n")
  452. ctx.update_end(200)
  453. ctx.finalize()
  454. eq_(info(), [(3, [100, 200])])
  455. # Delete chunk, which will leave one data point and two intervals
  456. client.stream_remove("/empty/test", 145, 175)
  457. eq_(info(), [(1, [100, 145]),
  458. (0, [175, 200])])
  459. # Try also creating a completely empty interval from scratch,
  460. # in a few different ways.
  461. client.stream_insert("/empty/test", "", 300, 350)
  462. client.stream_insert("/empty/test", [], 400, 450)
  463. with client.stream_insert_context("/empty/test", 500, 550):
  464. pass
  465. # If enough timestamps aren't provided, empty streams won't be created.
  466. client.stream_insert("/empty/test", [])
  467. with client.stream_insert_context("/empty/test"):
  468. pass
  469. client.stream_insert("/empty/test", [], start = 600)
  470. with client.stream_insert_context("/empty/test", start = 700):
  471. pass
  472. client.stream_insert("/empty/test", [], end = 850)
  473. with client.stream_insert_context("/empty/test", end = 950):
  474. pass
  475. # Try various things that might cause problems
  476. with client.stream_insert_context("/empty/test", 1000, 1050):
  477. ctx.finalize() # inserts [1000, 1050]
  478. ctx.finalize() # nothing
  479. ctx.finalize() # nothing
  480. ctx.insert("1100 1\n")
  481. ctx.finalize() # inserts [1100, 1101]
  482. ctx.update_start(1199)
  483. ctx.insert("1200 1\n")
  484. ctx.update_end(1250)
  485. ctx.finalize() # inserts [1199, 1250]
  486. ctx.update_start(1299)
  487. ctx.finalize() # nothing
  488. ctx.update_end(1350)
  489. ctx.finalize() # nothing
  490. ctx.update_start(1400)
  491. ctx.insert("# nothing!\n")
  492. ctx.update_end(1450)
  493. ctx.finalize()
  494. ctx.update_start(1500)
  495. ctx.insert("# nothing!")
  496. ctx.update_end(1550)
  497. ctx.finalize()
  498. ctx.insert("# nothing!\n" * 10)
  499. ctx.finalize()
  500. # implicit last finalize inserts [1400, 1450]
  501. # Check everything
  502. eq_(info(), [(1, [100, 145]),
  503. (0, [175, 200]),
  504. (0, [300, 350]),
  505. (0, [400, 450]),
  506. (0, [500, 550]),
  507. (0, [1000, 1050]),
  508. (1, [1100, 1101]),
  509. (1, [1199, 1250]),
  510. (0, [1400, 1450]),
  511. (0, [1500, 1550]),
  512. ])
  513. # Clean up
  514. client.stream_remove("/empty/test")
  515. client.stream_destroy("/empty/test")
  516. client.close()
  517. def test_client_12_persistent(self):
  518. # Check that connections are persistent when they should be.
  519. # This is pretty hard to test; we have to poke deep into
  520. # the Requests library.
  521. with nilmdb.client.Client(url = testurl) as c:
  522. def connections():
  523. try:
  524. poolmanager = c.http._last_response.connection.poolmanager
  525. pool = poolmanager.pools[('http','localhost',32180)]
  526. return (pool.num_connections, pool.num_requests)
  527. except:
  528. raise SkipTest("can't get connection info")
  529. # First request makes a connection
  530. c.stream_create("/persist/test", "uint16_1")
  531. eq_(connections(), (1, 1))
  532. # Non-generator
  533. c.stream_list("/persist/test")
  534. eq_(connections(), (1, 2))
  535. c.stream_list("/persist/test")
  536. eq_(connections(), (1, 3))
  537. # Generators
  538. for x in c.stream_intervals("/persist/test"):
  539. pass
  540. eq_(connections(), (1, 4))
  541. for x in c.stream_intervals("/persist/test"):
  542. pass
  543. eq_(connections(), (1, 5))
  544. # Clean up
  545. c.stream_remove("/persist/test")
  546. c.stream_destroy("/persist/test")
  547. eq_(connections(), (1, 7))
  548. def test_client_13_timestamp_rounding(self):
  549. # Test potentially bad timestamps (due to floating point
  550. # roundoff etc). The server will round floating point values
  551. # to the nearest int.
  552. client = nilmdb.client.Client(testurl)
  553. client.stream_create("/rounding/test", "uint16_1")
  554. with client.stream_insert_context("/rounding/test",
  555. 100000000, 200000000.1) as ctx:
  556. ctx.insert("100000000.1 1\n")
  557. ctx.insert("150000000.00003 1\n")
  558. ctx.insert("199999999.4 1\n")
  559. eq_(list(client.stream_intervals("/rounding/test")),
  560. [ [ 100000000, 200000000 ] ])
  561. with assert_raises(ClientError):
  562. with client.stream_insert_context("/rounding/test",
  563. 200000000, 300000000) as ctx:
  564. ctx.insert("200000000 1\n")
  565. ctx.insert("250000000 1\n")
  566. # Server will round this and give an error on finalize()
  567. ctx.insert("299999999.99 1\n")
  568. client.stream_remove("/rounding/test")
  569. client.stream_destroy("/rounding/test")
  570. client.close()