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.
 
 
 

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