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.
 
 
 

262 lines
9.4 KiB

  1. import nilmdb.server
  2. from nose.tools import *
  3. from nose.tools import assert_raises
  4. import distutils.version
  5. import simplejson as json
  6. import itertools
  7. import os
  8. import sys
  9. import threading
  10. import urllib.request, urllib.error, urllib.parse
  11. from urllib.request import urlopen
  12. from urllib.error import HTTPError
  13. import io
  14. import time
  15. import requests
  16. from nilmdb.utils import serializer_proxy
  17. testdb = "tests/testdb"
  18. #@atexit.register
  19. #def cleanup():
  20. # os.unlink(testdb)
  21. from testutil.helpers import *
  22. class Test00Nilmdb(object): # named 00 so it runs first
  23. def test_NilmDB(self):
  24. recursive_unlink(testdb)
  25. db = nilmdb.server.NilmDB(testdb)
  26. db.close()
  27. db = nilmdb.server.NilmDB(testdb)
  28. db.close()
  29. # test timer, just to get coverage
  30. capture = io.StringIO()
  31. old = sys.stdout
  32. sys.stdout = capture
  33. with nilmdb.utils.Timer("test"):
  34. time.sleep(0.01)
  35. sys.stdout = old
  36. in_("test: ", capture.getvalue())
  37. def test_stream(self):
  38. db = nilmdb.server.NilmDB(testdb)
  39. eq_(db.stream_list(), [])
  40. # Bad path
  41. with assert_raises(ValueError):
  42. db.stream_create("foo/bar/baz", "float32_8")
  43. with assert_raises(ValueError):
  44. db.stream_create("/foo", "float32_8")
  45. # Bad layout type
  46. with assert_raises(ValueError):
  47. db.stream_create("/newton/prep", "NoSuchLayout")
  48. db.stream_create("/newton/prep", "float32_8")
  49. db.stream_create("/newton/raw", "uint16_6")
  50. db.stream_create("/newton/zzz/rawnotch", "uint16_9")
  51. # Verify we got 3 streams
  52. eq_(db.stream_list(), [ ["/newton/prep", "float32_8"],
  53. ["/newton/raw", "uint16_6"],
  54. ["/newton/zzz/rawnotch", "uint16_9"]
  55. ])
  56. # Match just one type or one path
  57. eq_(db.stream_list(layout="uint16_6"), [ ["/newton/raw", "uint16_6"] ])
  58. eq_(db.stream_list(path="/newton/raw"), [ ["/newton/raw", "uint16_6"] ])
  59. # Verify that columns were made right (pytables specific)
  60. if "h5file" in db.data.__dict__:
  61. h5file = db.data.h5file
  62. eq_(len(h5file.getNode("/newton/prep").cols), 9)
  63. eq_(len(h5file.getNode("/newton/raw").cols), 7)
  64. eq_(len(h5file.getNode("/newton/zzz/rawnotch").cols), 10)
  65. assert(not h5file.getNode("/newton/prep").colindexed["timestamp"])
  66. assert(not h5file.getNode("/newton/prep").colindexed["c1"])
  67. # Set / get metadata
  68. eq_(db.stream_get_metadata("/newton/prep"), {})
  69. eq_(db.stream_get_metadata("/newton/raw"), {})
  70. meta1 = { "description": "The Data",
  71. "v_scale": "1.234" }
  72. meta2 = { "description": "The Data" }
  73. meta3 = { "v_scale": "1.234" }
  74. db.stream_set_metadata("/newton/prep", meta1)
  75. db.stream_update_metadata("/newton/prep", {})
  76. db.stream_update_metadata("/newton/raw", meta2)
  77. db.stream_update_metadata("/newton/raw", meta3)
  78. eq_(db.stream_get_metadata("/newton/prep"), meta1)
  79. eq_(db.stream_get_metadata("/newton/raw"), meta1)
  80. # fill in some misc. test coverage
  81. with assert_raises(nilmdb.server.NilmDBError):
  82. db.stream_remove("/newton/prep", 0, 0)
  83. with assert_raises(nilmdb.server.NilmDBError):
  84. db.stream_remove("/newton/prep", 1, 0)
  85. db.stream_remove("/newton/prep", 0, 1)
  86. with assert_raises(nilmdb.server.NilmDBError):
  87. db.stream_extract("/newton/prep", count = True, binary = True)
  88. db.close()
  89. class TestBlockingServer(object):
  90. def setUp(self):
  91. self.db = serializer_proxy(nilmdb.server.NilmDB)(testdb)
  92. def tearDown(self):
  93. self.db.close()
  94. def test_blocking_server(self):
  95. # Server should fail if the database doesn't have a "_thread_safe"
  96. # property.
  97. with assert_raises(KeyError):
  98. nilmdb.server.Server(object())
  99. # Start web app on a custom port
  100. self.server = nilmdb.server.Server(self.db, host = "127.0.0.1",
  101. port = 32180, stoppable = True)
  102. # Run it
  103. event = threading.Event()
  104. def run_server():
  105. self.server.start(blocking = True, event = event)
  106. thread = threading.Thread(target = run_server)
  107. thread.start()
  108. if not event.wait(timeout = 10):
  109. raise AssertionError("server didn't start in 10 seconds")
  110. # Send request to exit.
  111. req = urlopen("http://127.0.0.1:32180/exit/", timeout = 1)
  112. # Wait for it
  113. thread.join()
  114. def geturl(path):
  115. resp = urlopen("http://127.0.0.1:32180" + path, timeout = 10)
  116. body = resp.read()
  117. return body.decode(resp.headers.get_content_charset() or 'utf-8')
  118. def getjson(path):
  119. return json.loads(geturl(path))
  120. class TestServer(object):
  121. def setUp(self):
  122. # Start web app on a custom port
  123. self.db = serializer_proxy(nilmdb.server.NilmDB)(testdb)
  124. self.server = nilmdb.server.Server(self.db, host = "127.0.0.1",
  125. port = 32180, stoppable = False)
  126. self.server.start(blocking = False)
  127. def tearDown(self):
  128. # Close web app
  129. self.server.stop()
  130. self.db.close()
  131. def test_server(self):
  132. # Make sure we can't force an exit, and test other 404 errors
  133. for url in [ "/exit", "/favicon.ico" ]:
  134. with assert_raises(HTTPError) as e:
  135. geturl(url)
  136. eq_(e.exception.code, 404)
  137. # Root page
  138. in_("This is NilmDB", geturl("/"))
  139. # Check version
  140. eq_(distutils.version.LooseVersion(getjson("/version")),
  141. distutils.version.LooseVersion(nilmdb.__version__))
  142. def test_stream_list(self):
  143. # Known streams that got populated by an earlier test (test_nilmdb)
  144. streams = getjson("/stream/list")
  145. eq_(streams, [
  146. ['/newton/prep', 'float32_8'],
  147. ['/newton/raw', 'uint16_6'],
  148. ['/newton/zzz/rawnotch', 'uint16_9'],
  149. ])
  150. streams = getjson("/stream/list?layout=uint16_6")
  151. eq_(streams, [['/newton/raw', 'uint16_6']])
  152. streams = getjson("/stream/list?layout=NoSuchLayout")
  153. eq_(streams, [])
  154. def test_stream_metadata(self):
  155. with assert_raises(HTTPError) as e:
  156. getjson("/stream/get_metadata?path=foo")
  157. eq_(e.exception.code, 404)
  158. data = getjson("/stream/get_metadata?path=/newton/prep")
  159. eq_(data, {'description': 'The Data', 'v_scale': '1.234'})
  160. data = getjson("/stream/get_metadata?path=/newton/prep"
  161. "&key=v_scale")
  162. eq_(data, {'v_scale': '1.234'})
  163. data = getjson("/stream/get_metadata?path=/newton/prep"
  164. "&key=v_scale&key=description")
  165. eq_(data, {'description': 'The Data', 'v_scale': '1.234'})
  166. data = getjson("/stream/get_metadata?path=/newton/prep"
  167. "&key=v_scale&key=foo")
  168. eq_(data, {'foo': None, 'v_scale': '1.234'})
  169. data = getjson("/stream/get_metadata?path=/newton/prep"
  170. "&key=foo")
  171. eq_(data, {'foo': None})
  172. def test_cors_headers(self):
  173. # Test that CORS headers are being set correctly
  174. # Normal GET should send simple response
  175. url = "http://127.0.0.1:32180/stream/list"
  176. r = requests.get(url, headers = { "Origin": "http://google.com/" })
  177. eq_(r.status_code, 200)
  178. if "access-control-allow-origin" not in r.headers:
  179. raise AssertionError("No Access-Control-Allow-Origin (CORS) "
  180. "header in response:\n", r.headers)
  181. eq_(r.headers["access-control-allow-origin"], "http://google.com/")
  182. # OPTIONS without CORS preflight headers should result in 405
  183. r = requests.options(url, headers = {
  184. "Origin": "http://google.com/",
  185. })
  186. eq_(r.status_code, 405)
  187. # OPTIONS with preflight headers should give preflight response
  188. r = requests.options(url, headers = {
  189. "Origin": "http://google.com/",
  190. "Access-Control-Request-Method": "POST",
  191. "Access-Control-Request-Headers": "X-Custom",
  192. })
  193. eq_(r.status_code, 200)
  194. if "access-control-allow-origin" not in r.headers:
  195. raise AssertionError("No Access-Control-Allow-Origin (CORS) "
  196. "header in response:\n", r.headers)
  197. eq_(r.headers["access-control-allow-methods"], "GET, HEAD")
  198. eq_(r.headers["access-control-allow-headers"], "X-Custom")
  199. def test_post_bodies(self):
  200. # Test JSON post bodies
  201. r = requests.post("http://127.0.0.1:32180/stream/set_metadata",
  202. headers = { "Content-Type": "application/json" },
  203. data = '{"hello": 1}')
  204. eq_(r.status_code, 404) # wrong parameters
  205. r = requests.post("http://127.0.0.1:32180/stream/set_metadata",
  206. headers = { "Content-Type": "application/json" },
  207. data = '["hello"]')
  208. eq_(r.status_code, 415) # not a dict
  209. r = requests.post("http://127.0.0.1:32180/stream/set_metadata",
  210. headers = { "Content-Type": "application/json" },
  211. data = '[hello]')
  212. eq_(r.status_code, 400) # badly formatted JSON