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.
 
 
 

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