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.
 
 
 

360 lines
15 KiB

  1. # -*- coding: utf-8 -*-
  2. import nilmdb
  3. from nilmdb.utils.printf import *
  4. from nilmdb.utils import timestamper
  5. from nilmdb.client import ClientError, ServerError
  6. import datetime_tz
  7. from nose.tools import *
  8. from nose.tools import assert_raises
  9. import itertools
  10. import distutils.version
  11. import os
  12. import sys
  13. import threading
  14. import cStringIO
  15. import simplejson as json
  16. import unittest
  17. import warnings
  18. import resource
  19. from testutil.helpers import *
  20. testdb = "tests/client-testdb"
  21. def setup_module():
  22. global test_server, test_db
  23. # Clear out DB
  24. recursive_unlink(testdb)
  25. # Start web app on a custom port
  26. test_db = nilmdb.NilmDB(testdb, sync = False)
  27. test_server = nilmdb.Server(test_db, host = "127.0.0.1",
  28. port = 12380, stoppable = False,
  29. fast_shutdown = True,
  30. force_traceback = False)
  31. test_server.start(blocking = False)
  32. def teardown_module():
  33. global test_server, test_db
  34. # Close web app
  35. test_server.stop()
  36. test_db.close()
  37. class TestClient(object):
  38. def test_client_1_basic(self):
  39. # Test a fake host
  40. client = nilmdb.Client(url = "http://localhost:1/")
  41. with assert_raises(nilmdb.client.ServerError):
  42. client.version()
  43. # Trigger same error with a PUT request
  44. client = nilmdb.Client(url = "http://localhost:1/")
  45. with assert_raises(nilmdb.client.ServerError):
  46. client.version()
  47. # Then a fake URL on a real host
  48. client = nilmdb.Client(url = "http://localhost:12380/fake/")
  49. with assert_raises(nilmdb.client.ClientError):
  50. client.version()
  51. # Now a real URL with no http:// prefix
  52. client = nilmdb.Client(url = "localhost:12380")
  53. version = client.version()
  54. # Now use the real URL
  55. client = nilmdb.Client(url = "http://localhost:12380/")
  56. version = client.version()
  57. eq_(distutils.version.StrictVersion(version),
  58. distutils.version.StrictVersion(test_server.version))
  59. # Bad URLs should give 404, not 500
  60. with assert_raises(ClientError):
  61. client.http.get("/stream/create")
  62. def test_client_2_createlist(self):
  63. # Basic stream tests, like those in test_nilmdb:test_stream
  64. client = nilmdb.Client(url = "http://localhost:12380/")
  65. # Database starts empty
  66. eq_(client.stream_list(), [])
  67. # Bad path
  68. with assert_raises(ClientError):
  69. client.stream_create("foo/bar/baz", "PrepData")
  70. with assert_raises(ClientError):
  71. client.stream_create("/foo", "PrepData")
  72. # Bad layout type
  73. with assert_raises(ClientError):
  74. client.stream_create("/newton/prep", "NoSuchLayout")
  75. # Create three streams
  76. client.stream_create("/newton/prep", "PrepData")
  77. client.stream_create("/newton/raw", "RawData")
  78. client.stream_create("/newton/zzz/rawnotch", "RawNotchedData")
  79. # Verify we got 3 streams
  80. eq_(client.stream_list(), [ ["/newton/prep", "PrepData"],
  81. ["/newton/raw", "RawData"],
  82. ["/newton/zzz/rawnotch", "RawNotchedData"]
  83. ])
  84. # Match just one type or one path
  85. eq_(client.stream_list(layout="RawData"), [ ["/newton/raw", "RawData"] ])
  86. eq_(client.stream_list(path="/newton/raw"), [ ["/newton/raw", "RawData"] ])
  87. # Try messing with resource limits to trigger errors and get
  88. # more coverage. Here, make it so we can only create files 1
  89. # byte in size, which will trigger an IOError in the server when
  90. # we create a table.
  91. limit = resource.getrlimit(resource.RLIMIT_FSIZE)
  92. resource.setrlimit(resource.RLIMIT_FSIZE, (1, limit[1]))
  93. with assert_raises(ServerError) as e:
  94. client.stream_create("/newton/hello", "RawData")
  95. resource.setrlimit(resource.RLIMIT_FSIZE, limit)
  96. def test_client_3_metadata(self):
  97. client = nilmdb.Client(url = "http://localhost:12380/")
  98. # Set / get metadata
  99. eq_(client.stream_get_metadata("/newton/prep"), {})
  100. eq_(client.stream_get_metadata("/newton/raw"), {})
  101. meta1 = { "description": "The Data",
  102. "v_scale": "1.234" }
  103. meta2 = { "description": "The Data" }
  104. meta3 = { "v_scale": "1.234" }
  105. client.stream_set_metadata("/newton/prep", meta1)
  106. client.stream_update_metadata("/newton/prep", {})
  107. client.stream_update_metadata("/newton/raw", meta2)
  108. client.stream_update_metadata("/newton/raw", meta3)
  109. eq_(client.stream_get_metadata("/newton/prep"), meta1)
  110. eq_(client.stream_get_metadata("/newton/raw"), meta1)
  111. eq_(client.stream_get_metadata("/newton/raw", [ "description" ] ), meta2)
  112. eq_(client.stream_get_metadata("/newton/raw", [ "description",
  113. "v_scale" ] ), meta1)
  114. # missing key
  115. eq_(client.stream_get_metadata("/newton/raw", "descr"),
  116. { "descr": None })
  117. eq_(client.stream_get_metadata("/newton/raw", [ "descr" ]),
  118. { "descr": None })
  119. # test wrong types (list instead of dict)
  120. with assert_raises(ClientError):
  121. client.stream_set_metadata("/newton/prep", [1,2,3])
  122. with assert_raises(ClientError):
  123. client.stream_update_metadata("/newton/prep", [1,2,3])
  124. def test_client_4_insert(self):
  125. client = nilmdb.Client(url = "http://localhost:12380/")
  126. datetime_tz.localtz_set("America/New_York")
  127. testfile = "tests/data/prep-20120323T1000"
  128. start = datetime_tz.datetime_tz.smartparse("20120323T1000")
  129. start = start.totimestamp()
  130. rate = 120
  131. # First try a nonexistent path
  132. data = timestamper.TimestamperRate(testfile, start, 120)
  133. with assert_raises(ClientError) as e:
  134. result = client.stream_insert("/newton/no-such-path", data)
  135. in_("404 Not Found", str(e.exception))
  136. # Now try reversed timestamps
  137. data = timestamper.TimestamperRate(testfile, start, 120)
  138. data = reversed(list(data))
  139. with assert_raises(ClientError) as e:
  140. result = client.stream_insert("/newton/prep", data)
  141. in_("400 Bad Request", str(e.exception))
  142. in_("timestamp is not monotonically increasing", str(e.exception))
  143. # Now try empty data (no server request made)
  144. empty = cStringIO.StringIO("")
  145. data = timestamper.TimestamperRate(empty, start, 120)
  146. result = client.stream_insert("/newton/prep", data)
  147. eq_(result, None)
  148. # Try forcing a server request with empty data
  149. with assert_raises(ClientError) as e:
  150. client.http.put("stream/insert", "", { "path": "/newton/prep",
  151. "start": 0, "end": 0 })
  152. in_("400 Bad Request", str(e.exception))
  153. in_("no data provided", str(e.exception))
  154. # Specify start/end (starts too late)
  155. data = timestamper.TimestamperRate(testfile, start, 120)
  156. with assert_raises(ClientError) as e:
  157. result = client.stream_insert("/newton/prep", data,
  158. start + 5, start + 120)
  159. in_("400 Bad Request", str(e.exception))
  160. in_("Data timestamp 1332511200.0 < start time 1332511205.0",
  161. str(e.exception))
  162. # Specify start/end (ends too early)
  163. data = timestamper.TimestamperRate(testfile, start, 120)
  164. with assert_raises(ClientError) as e:
  165. result = client.stream_insert("/newton/prep", data,
  166. start, start + 1)
  167. in_("400 Bad Request", str(e.exception))
  168. # Client chunks the input, so the exact timestamp here might change
  169. # if the chunk positions change.
  170. in_("Data timestamp 1332511271.016667 >= end time 1332511201.0",
  171. str(e.exception))
  172. # Now do the real load
  173. data = timestamper.TimestamperRate(testfile, start, 120)
  174. result = client.stream_insert("/newton/prep", data,
  175. start, start + 119.999777)
  176. eq_(result, "ok")
  177. # Verify the intervals. Should be just one, even if the data
  178. # was inserted in chunks, due to nilmdb interval concatenation.
  179. intervals = list(client.stream_intervals("/newton/prep"))
  180. eq_(intervals, [[start, start + 119.999777]])
  181. # Try some overlapping data -- just insert it again
  182. data = timestamper.TimestamperRate(testfile, start, 120)
  183. with assert_raises(ClientError) as e:
  184. result = client.stream_insert("/newton/prep", data)
  185. in_("400 Bad Request", str(e.exception))
  186. in_("verlap", str(e.exception))
  187. def test_client_5_extractremove(self):
  188. # Misc tests for extract and remove. Most of them are in test_cmdline.
  189. client = nilmdb.Client(url = "http://localhost:12380/")
  190. for x in client.stream_extract("/newton/prep", 123, 123):
  191. raise AssertionError("shouldn't be any data for this request")
  192. with assert_raises(ClientError) as e:
  193. client.stream_remove("/newton/prep", 123, 120)
  194. def test_client_6_generators(self):
  195. # A lot of the client functionality is already tested by test_cmdline,
  196. # but this gets a bit more coverage that cmdline misses.
  197. client = nilmdb.Client(url = "http://localhost:12380/")
  198. # Trigger a client error in generator
  199. start = datetime_tz.datetime_tz.smartparse("20120323T2000")
  200. end = datetime_tz.datetime_tz.smartparse("20120323T1000")
  201. for function in [ client.stream_intervals, client.stream_extract ]:
  202. with assert_raises(ClientError) as e:
  203. function("/newton/prep",
  204. start.totimestamp(),
  205. end.totimestamp()).next()
  206. in_("400 Bad Request", str(e.exception))
  207. in_("end before start", str(e.exception))
  208. # Trigger a curl error in generator
  209. with assert_raises(ServerError) as e:
  210. client.http.get_gen("http://nosuchurl/").next()
  211. # Trigger a curl error in generator
  212. with assert_raises(ServerError) as e:
  213. client.http.get_gen("http://nosuchurl/").next()
  214. # Check non-json version of string output
  215. eq_(json.loads(client.http.get("/stream/list",retjson=False)),
  216. client.http.get("/stream/list",retjson=True))
  217. # Check non-json version of generator output
  218. for (a, b) in itertools.izip(
  219. client.http.get_gen("/stream/list",retjson=False),
  220. client.http.get_gen("/stream/list",retjson=True)):
  221. eq_(json.loads(a), b)
  222. # Check PUT with generator out
  223. with assert_raises(ClientError) as e:
  224. client.http.put_gen("stream/insert", "",
  225. { "path": "/newton/prep",
  226. "start": 0, "end": 0 }).next()
  227. in_("400 Bad Request", str(e.exception))
  228. in_("no data provided", str(e.exception))
  229. # Check 404 for missing streams
  230. for function in [ client.stream_intervals, client.stream_extract ]:
  231. with assert_raises(ClientError) as e:
  232. function("/no/such/stream").next()
  233. in_("404 Not Found", str(e.exception))
  234. in_("No such stream", str(e.exception))
  235. def test_client_7_headers(self):
  236. # Make sure that /stream/intervals and /stream/extract
  237. # properly return streaming, chunked, text/plain response.
  238. # Pokes around in client.http internals a bit to look at the
  239. # response headers.
  240. client = nilmdb.Client(url = "http://localhost:12380/")
  241. http = client.http
  242. # Use a warning rather than returning a test failure, so that we can
  243. # still disable chunked responses for debugging.
  244. # Intervals
  245. x = http.get("stream/intervals", { "path": "/newton/prep" },
  246. retjson=False)
  247. lines_(x, 1)
  248. if "Transfer-Encoding: chunked" not in http._headers:
  249. warnings.warn("Non-chunked HTTP response for /stream/intervals")
  250. if "Content-Type: text/plain;charset=utf-8" not in http._headers:
  251. raise AssertionError("/stream/intervals is not text/plain:\n" +
  252. http._headers)
  253. # Extract
  254. x = http.get("stream/extract",
  255. { "path": "/newton/prep",
  256. "start": "123",
  257. "end": "123" }, retjson=False)
  258. if "Transfer-Encoding: chunked" not in http._headers:
  259. warnings.warn("Non-chunked HTTP response for /stream/extract")
  260. if "Content-Type: text/plain;charset=utf-8" not in http._headers:
  261. raise AssertionError("/stream/extract is not text/plain:\n" +
  262. http._headers)
  263. # Make sure Access-Control-Allow-Origin gets set
  264. if "Access-Control-Allow-Origin: " not in http._headers:
  265. raise AssertionError("No Access-Control-Allow-Origin (CORS) "
  266. "header in /stream/extract response:\n" +
  267. http._headers)
  268. def test_client_8_unicode(self):
  269. # Basic Unicode tests
  270. client = nilmdb.Client(url = "http://localhost:12380/")
  271. # Delete streams that exist
  272. for stream in client.stream_list():
  273. client.stream_destroy(stream[0])
  274. # Database is empty
  275. eq_(client.stream_list(), [])
  276. # Create Unicode stream, match it
  277. raw = [ u"/düsseldorf/raw", u"uint16_6" ]
  278. prep = [ u"/düsseldorf/prep", u"uint16_6" ]
  279. client.stream_create(*raw)
  280. eq_(client.stream_list(), [raw])
  281. eq_(client.stream_list(layout=raw[1]), [raw])
  282. eq_(client.stream_list(path=raw[0]), [raw])
  283. client.stream_create(*prep)
  284. eq_(client.stream_list(), [prep, raw])
  285. # Set / get metadata with Unicode keys and values
  286. eq_(client.stream_get_metadata(raw[0]), {})
  287. eq_(client.stream_get_metadata(prep[0]), {})
  288. meta1 = { u"alpha": u"α",
  289. u"β": u"beta" }
  290. meta2 = { u"alpha": u"α" }
  291. meta3 = { u"β": u"beta" }
  292. client.stream_set_metadata(prep[0], meta1)
  293. client.stream_update_metadata(prep[0], {})
  294. client.stream_update_metadata(raw[0], meta2)
  295. client.stream_update_metadata(raw[0], meta3)
  296. eq_(client.stream_get_metadata(prep[0]), meta1)
  297. eq_(client.stream_get_metadata(raw[0]), meta1)
  298. eq_(client.stream_get_metadata(raw[0], [ "alpha" ]), meta2)
  299. eq_(client.stream_get_metadata(raw[0], [ "alpha", "β" ]), meta1)