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.
 
 
 

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