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.
 
 
 

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