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.

test_client.py 30 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. # Now do the real load
  248. data = timestamper.TimestamperRate(testfile, start, 120)
  249. result = client.stream_insert("/newton/prep", data,
  250. start, start + 119999777)
  251. # Verify the intervals. Should be just one, even if the data
  252. # was inserted in chunks, due to nilmdb interval concatenation.
  253. intervals = list(client.stream_intervals("/newton/prep"))
  254. eq_(intervals, [[start, start + 119999777]])
  255. # Try some overlapping data -- just insert it again
  256. data = timestamper.TimestamperRate(testfile, start, 120)
  257. with assert_raises(ClientError) as e:
  258. result = client.stream_insert("/newton/prep", data)
  259. in_("400 Bad Request", str(e.exception))
  260. in_("verlap", str(e.exception))
  261. nilmdb.client.client.StreamInserter._max_data = old_max_data
  262. client.close()
  263. def test_client_05_extractremove(self):
  264. # Misc tests for extract and remove. Most of them are in test_cmdline.
  265. client = nilmdb.client.Client(url = testurl)
  266. for x in client.stream_extract("/newton/prep",
  267. 999123000000, 999124000000):
  268. raise AssertionError("shouldn't be any data for this request")
  269. with assert_raises(ClientError) as e:
  270. client.stream_remove("/newton/prep", 123000000, 120000000)
  271. # Test count
  272. eq_(client.stream_count("/newton/prep"), 14400)
  273. # Test binary output
  274. with assert_raises(ClientError) as e:
  275. list(client.stream_extract("/newton/prep",
  276. markup = True, binary = True))
  277. with assert_raises(ClientError) as e:
  278. list(client.stream_extract("/newton/prep",
  279. count = True, binary = True))
  280. data = b"".join(client.stream_extract("/newton/prep", binary = True))
  281. # Quick check using struct
  282. unpacker = struct.Struct("<qffffffff")
  283. out = []
  284. for i in range(14400):
  285. out.append(unpacker.unpack_from(data, i * unpacker.size))
  286. eq_(out[0], (1332511200000000, 266568.0, 224029.0, 5161.39990234375,
  287. 2525.169921875, 8350.83984375, 3724.699951171875,
  288. 1355.3399658203125, 2039.0))
  289. # Just get some coverage
  290. with assert_raises(ClientError) as e:
  291. client.http.post("/stream/remove", { "path": "/none" })
  292. client.close()
  293. def test_client_06_generators(self):
  294. # A lot of the client functionality is already tested by test_cmdline,
  295. # but this gets a bit more coverage that cmdline misses.
  296. client = nilmdb.client.Client(url = testurl)
  297. # Trigger a client error in generator
  298. start = nilmdb.utils.time.parse_time("20120323T2000")
  299. end = nilmdb.utils.time.parse_time("20120323T1000")
  300. for function in [ client.stream_intervals, client.stream_extract ]:
  301. with assert_raises(ClientError) as e:
  302. next(function("/newton/prep", start, end))
  303. in_("400 Bad Request", str(e.exception))
  304. in_("start must precede end", str(e.exception))
  305. # Trigger a curl error in generator
  306. with assert_raises(ServerError) as e:
  307. next(client.http.get_gen("http://nosuchurl.example.com./"))
  308. # Check 404 for missing streams
  309. for function in [ client.stream_intervals, client.stream_extract ]:
  310. with assert_raises(ClientError) as e:
  311. next(function("/no/such/stream"))
  312. in_("404 Not Found", str(e.exception))
  313. in_("No such stream", str(e.exception))
  314. client.close()
  315. def test_client_07_headers(self):
  316. # Make sure that /stream/intervals and /stream/extract
  317. # properly return streaming, chunked, text/plain response.
  318. # Pokes around in client.http internals a bit to look at the
  319. # response headers.
  320. client = nilmdb.client.Client(url = testurl)
  321. http = client.http
  322. # Use a warning rather than returning a test failure for the
  323. # transfer-encoding, so that we can still disable chunked
  324. # responses for debugging.
  325. def headers():
  326. h = ""
  327. for (k, v) in list(http._last_response.headers.items()):
  328. h += k + ": " + v + "\n"
  329. return h.lower()
  330. # Intervals
  331. x = http.get("stream/intervals", { "path": "/newton/prep" })
  332. if "transfer-encoding: chunked" not in headers():
  333. warnings.warn("Non-chunked HTTP response for /stream/intervals")
  334. if "content-type: application/x-json-stream" not in headers():
  335. raise AssertionError("/stream/intervals content type "
  336. "is not application/x-json-stream:\n" +
  337. headers())
  338. # Extract
  339. x = http.get("stream/extract", { "path": "/newton/prep",
  340. "start": "123", "end": "124" })
  341. if "transfer-encoding: chunked" not in headers():
  342. warnings.warn("Non-chunked HTTP response for /stream/extract")
  343. if "content-type: text/plain;charset=utf-8" not in headers():
  344. raise AssertionError("/stream/extract is not text/plain:\n" +
  345. headers())
  346. x = http.get("stream/extract", { "path": "/newton/prep",
  347. "start": "123", "end": "124",
  348. "binary": "1" })
  349. if "transfer-encoding: chunked" not in headers():
  350. warnings.warn("Non-chunked HTTP response for /stream/extract")
  351. if "content-type: application/octet-stream" not in headers():
  352. raise AssertionError("/stream/extract is not binary:\n" +
  353. headers())
  354. # Make sure a binary of "0" is really off
  355. x = http.get("stream/extract", { "path": "/newton/prep",
  356. "start": "123", "end": "124",
  357. "binary": "0" })
  358. if "content-type: application/octet-stream" in headers():
  359. raise AssertionError("/stream/extract is not text:\n" +
  360. headers())
  361. # Invalid parameters
  362. with assert_raises(ClientError) as e:
  363. x = http.get("stream/extract", { "path": "/newton/prep",
  364. "start": "123", "end": "124",
  365. "binary": "asdfasfd" })
  366. in_("can't parse parameter", str(e.exception))
  367. client.close()
  368. def test_client_08_unicode(self):
  369. # Try both with and without posting JSON
  370. for post_json in (False, True):
  371. # Basic Unicode tests
  372. client = nilmdb.client.Client(url = testurl, post_json = post_json)
  373. # Delete streams that exist
  374. for stream in client.stream_list():
  375. client.stream_remove(stream[0])
  376. client.stream_destroy(stream[0])
  377. # Database is empty
  378. eq_(client.stream_list(), [])
  379. # Create Unicode stream, match it
  380. raw = [ "/düsseldorf/raw", "uint16_6" ]
  381. prep = [ "/düsseldorf/prep", "uint16_6" ]
  382. client.stream_create(*raw)
  383. eq_(client.stream_list(), [raw])
  384. eq_(client.stream_list(layout=raw[1]), [raw])
  385. eq_(client.stream_list(path=raw[0]), [raw])
  386. client.stream_create(*prep)
  387. eq_(client.stream_list(), [prep, raw])
  388. # Set / get metadata with Unicode keys and values
  389. eq_(client.stream_get_metadata(raw[0]), {})
  390. eq_(client.stream_get_metadata(prep[0]), {})
  391. meta1 = { "alpha": "α",
  392. "β": "beta" }
  393. meta2 = { "alpha": "α" }
  394. meta3 = { "β": "beta" }
  395. client.stream_set_metadata(prep[0], meta1)
  396. client.stream_update_metadata(prep[0], {})
  397. client.stream_update_metadata(raw[0], meta2)
  398. client.stream_update_metadata(raw[0], meta3)
  399. eq_(client.stream_get_metadata(prep[0]), meta1)
  400. eq_(client.stream_get_metadata(raw[0]), meta1)
  401. eq_(client.stream_get_metadata(raw[0], [ "alpha" ]), meta2)
  402. eq_(client.stream_get_metadata(raw[0], [ "alpha", "β" ]), meta1)
  403. client.close()
  404. def test_client_09_closing(self):
  405. # Make sure we actually close sockets correctly. New
  406. # connections will block for a while if they're not, since the
  407. # server will stop accepting new connections.
  408. for test in [1, 2]:
  409. start = time.time()
  410. for i in range(50):
  411. if time.time() - start > 15:
  412. raise AssertionError("Connections seem to be blocking... "
  413. "probably not closing properly.")
  414. if test == 1:
  415. # explicit close
  416. client = nilmdb.client.Client(url = testurl)
  417. with assert_raises(ClientError) as e:
  418. client.stream_remove("/newton/prep", 123, 120)
  419. client.close() # remove this to see the failure
  420. elif test == 2:
  421. # use the context manager
  422. with nilmdb.client.Client(url = testurl) as c:
  423. with assert_raises(ClientError) as e:
  424. c.stream_remove("/newton/prep", 123, 120)
  425. def test_client_10_context(self):
  426. # Test using the client's stream insertion context manager to
  427. # insert data.
  428. client = nilmdb.client.Client(testurl)
  429. client.stream_create("/context/test", "uint16_1")
  430. with client.stream_insert_context("/context/test") as ctx:
  431. # override _max_data to trigger frequent server updates
  432. ctx._max_data = 15
  433. ctx.insert(b"1000 1\n")
  434. ctx.insert(b"1010 ")
  435. ctx.insert(b"1\n1020 1")
  436. ctx.insert(b"")
  437. ctx.insert(b"\n1030 1\n")
  438. ctx.insert(b"1040 1\n")
  439. ctx.insert(b"# hello\n")
  440. ctx.insert(b" # hello\n")
  441. ctx.insert(b" 1050 1\n")
  442. ctx.finalize()
  443. ctx.insert(b"1070 1\n")
  444. ctx.update_end(1080)
  445. ctx.finalize()
  446. ctx.update_start(1090)
  447. ctx.insert(b"1100 1\n")
  448. ctx.insert(b"1110 1\n")
  449. ctx.send()
  450. ctx.insert(b"1120 1\n")
  451. ctx.insert(b"1130 1\n")
  452. ctx.insert(b"1140 1\n")
  453. ctx.update_end(1160)
  454. ctx.insert(b"1150 1\n")
  455. ctx.update_end(1170)
  456. ctx.insert(b"1160 1\n")
  457. ctx.update_end(1180)
  458. ctx.insert(b"1170 1" +
  459. b" # this is super long" * 100 +
  460. b"\n")
  461. ctx.finalize()
  462. ctx.insert(b"# this is super long" * 100)
  463. with assert_raises(ClientError):
  464. with client.stream_insert_context("/context/test",
  465. 1000, 2000) as ctx:
  466. ctx.insert(b"1180 1\n")
  467. with assert_raises(ClientError):
  468. with client.stream_insert_context("/context/test",
  469. 2000, 3000) as ctx:
  470. ctx.insert(b"1180 1\n")
  471. with assert_raises(ClientError):
  472. with client.stream_insert_context("/context/test") as ctx:
  473. ctx.insert(b"bogus data\n")
  474. with client.stream_insert_context("/context/test", 2000, 3000) as ctx:
  475. # make sure our override wasn't permanent
  476. ne_(ctx._max_data, 15)
  477. ctx.insert(b"2250 1\n")
  478. ctx.finalize()
  479. with assert_raises(ClientError):
  480. with client.stream_insert_context("/context/test",
  481. 3000, 4000) as ctx:
  482. ctx.insert(b"3010 1\n")
  483. ctx.insert(b"3020 2\n")
  484. ctx.insert(b"3030 3\n")
  485. ctx.insert(b"3040 4\n")
  486. ctx.insert(b"3040 4\n") # non-monotonic after a few lines
  487. ctx.finalize()
  488. eq_(list(client.stream_intervals("/context/test")),
  489. [ [ 1000, 1051 ],
  490. [ 1070, 1080 ],
  491. [ 1090, 1180 ],
  492. [ 2000, 3000 ] ])
  493. # destroy stream (try without removing data first)
  494. with assert_raises(ClientError):
  495. client.stream_destroy("/context/test")
  496. client.stream_remove("/context/test")
  497. client.stream_destroy("/context/test")
  498. client.close()
  499. def test_client_11_emptyintervals(self):
  500. # Empty intervals are ok! If recording detection events
  501. # by inserting rows into the database, we want to be able to
  502. # have an interval where no events occurred. Test them here.
  503. client = nilmdb.client.Client(testurl)
  504. client.stream_create("/empty/test", "uint16_1")
  505. def info():
  506. result = []
  507. for interval in list(client.stream_intervals("/empty/test")):
  508. result.append((client.stream_count("/empty/test", *interval),
  509. interval))
  510. return result
  511. eq_(info(), [])
  512. # Insert a region with just a few points
  513. with client.stream_insert_context("/empty/test") as ctx:
  514. ctx.update_start(100)
  515. ctx.insert(b"140 1\n")
  516. ctx.insert(b"150 1\n")
  517. ctx.insert(b"160 1\n")
  518. ctx.update_end(200)
  519. ctx.finalize()
  520. eq_(info(), [(3, [100, 200])])
  521. # Delete chunk, which will leave one data point and two intervals
  522. client.stream_remove("/empty/test", 145, 175)
  523. eq_(info(), [(1, [100, 145]),
  524. (0, [175, 200])])
  525. # Try also creating a completely empty interval from scratch,
  526. # in a few different ways.
  527. client.stream_insert("/empty/test", b"", 300, 350)
  528. client.stream_insert("/empty/test", [], 400, 450)
  529. with client.stream_insert_context("/empty/test", 500, 550):
  530. pass
  531. # If enough timestamps aren't provided, empty streams won't be created.
  532. client.stream_insert("/empty/test", [])
  533. with client.stream_insert_context("/empty/test"):
  534. pass
  535. client.stream_insert("/empty/test", [], start = 600)
  536. with client.stream_insert_context("/empty/test", start = 700):
  537. pass
  538. client.stream_insert("/empty/test", [], end = 850)
  539. with client.stream_insert_context("/empty/test", end = 950):
  540. pass
  541. # Equal start and end is OK as long as there's no data
  542. with client.stream_insert_context("/empty/test", start=9, end=9):
  543. pass
  544. # Try various things that might cause problems
  545. with client.stream_insert_context("/empty/test", 1000, 1050) as ctx:
  546. ctx.finalize() # inserts [1000, 1050]
  547. ctx.finalize() # nothing
  548. ctx.finalize() # nothing
  549. ctx.insert(b"1100 1\n")
  550. ctx.finalize() # inserts [1100, 1101]
  551. ctx.update_start(1199)
  552. ctx.insert(b"1200 1\n")
  553. ctx.update_end(1250)
  554. ctx.finalize() # inserts [1199, 1250]
  555. ctx.update_start(1299)
  556. ctx.finalize() # nothing
  557. ctx.update_end(1350)
  558. ctx.finalize() # nothing
  559. ctx.update_start(1400)
  560. ctx.insert(b"# nothing!\n")
  561. ctx.update_end(1450)
  562. ctx.finalize()
  563. ctx.update_start(1500)
  564. ctx.insert(b"# nothing!")
  565. ctx.update_end(1550)
  566. ctx.finalize()
  567. ctx.insert(b"# nothing!\n" * 10)
  568. ctx.finalize()
  569. # implicit last finalize inserts [1400, 1450]
  570. # Check everything
  571. eq_(info(), [(1, [100, 145]),
  572. (0, [175, 200]),
  573. (0, [300, 350]),
  574. (0, [400, 450]),
  575. (0, [500, 550]),
  576. (0, [1000, 1050]),
  577. (1, [1100, 1101]),
  578. (1, [1199, 1250]),
  579. (0, [1400, 1450]),
  580. (0, [1500, 1550]),
  581. ])
  582. # Clean up
  583. client.stream_remove("/empty/test")
  584. client.stream_destroy("/empty/test")
  585. client.close()
  586. def test_client_12_persistent(self):
  587. # Check that connections are NOT persistent. Rather than trying
  588. # to verify this at the TCP level, just make sure that the response
  589. # contained a "Connection: close" header.
  590. with nilmdb.client.Client(url = testurl) as c:
  591. c.stream_create("/persist/test", "uint16_1")
  592. eq_(c.http._last_response.headers["Connection"], "close")
  593. c.stream_destroy("/persist/test")
  594. eq_(c.http._last_response.headers["Connection"], "close")
  595. def test_client_13_timestamp_rounding(self):
  596. # Test potentially bad timestamps (due to floating point
  597. # roundoff etc). The server will round floating point values
  598. # to the nearest int.
  599. client = nilmdb.client.Client(testurl)
  600. client.stream_create("/rounding/test", "uint16_1")
  601. with client.stream_insert_context("/rounding/test",
  602. 100000000, 200000000.1) as ctx:
  603. ctx.insert(b"100000000.1 1\n")
  604. ctx.insert(b"150000000.00003 1\n")
  605. ctx.insert(b"199999999.4 1\n")
  606. eq_(list(client.stream_intervals("/rounding/test")),
  607. [ [ 100000000, 200000000 ] ])
  608. with assert_raises(ClientError):
  609. with client.stream_insert_context("/rounding/test",
  610. 200000000, 300000000) as ctx:
  611. ctx.insert(b"200000000 1\n")
  612. ctx.insert(b"250000000 1\n")
  613. # Server will round this and give an error on finalize()
  614. ctx.insert(b"299999999.99 1\n")
  615. client.stream_remove("/rounding/test")
  616. client.stream_destroy("/rounding/test")
  617. client.close()