test_rest_api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import json
  2. import os
  3. import unittest
  4. from flask import Flask
  5. from flask_testing import LiveServerTestCase
  6. from mock import mock
  7. from kalliope._version import version_str
  8. from kalliope.core import LIFOBuffer, LifoManager
  9. from kalliope.core.ConfigurationManager import BrainLoader
  10. from kalliope.core.ConfigurationManager import SettingLoader
  11. from kalliope.core.Models import Singleton
  12. from kalliope.core.RestAPI.FlaskAPI import FlaskAPI
  13. class TestRestAPI(LiveServerTestCase):
  14. def tearDown(self):
  15. Singleton._instances = {}
  16. # clean the lifo
  17. LifoManager.clean_saved_lifo()
  18. def create_app(self):
  19. """
  20. executed once at the beginning of the test
  21. """
  22. # be sure that the singleton haven't been loaded before
  23. Singleton._instances = {}
  24. current_path = os.getcwd()
  25. if "/Tests" in os.getcwd():
  26. full_path_brain_to_test = current_path + os.sep + "brains/brain_test_api.yml"
  27. self.audio_file = "files/bonjour.wav"
  28. else:
  29. full_path_brain_to_test = current_path + os.sep + "Tests/brains/brain_test_api.yml"
  30. self.audio_file = "Tests/files/bonjour.wav"
  31. # rest api config
  32. sl = SettingLoader()
  33. sl.settings.rest_api.password_protected = False
  34. sl.settings.active = True
  35. sl.settings.port = 5000
  36. sl.settings.allowed_cors_origin = "*"
  37. sl.settings.default_synapse = None
  38. sl.settings.hooks["on_order_not_found"] = "order-not-found-synapse"
  39. # prepare a test brain
  40. brain_to_test = full_path_brain_to_test
  41. brain_loader = BrainLoader(file_path=brain_to_test)
  42. brain = brain_loader.brain
  43. self.app = Flask(__name__)
  44. self.app.config['TESTING'] = True
  45. self.flask_api = FlaskAPI(self.app, port=5000, brain=brain)
  46. self.client = self.app.test_client()
  47. return self.flask_api.app
  48. def test_server_is_up_and_running(self):
  49. # response = urllib2.urlopen(self.get_server_url())
  50. response = self.client.get(self.get_server_url())
  51. self.assertEqual(response.status_code, 200)
  52. def test_get_main_page(self):
  53. url = self.get_server_url() + "/"
  54. response = self.client.get(url)
  55. expected_content = {
  56. "Kalliope version": "%s" % version_str
  57. }
  58. self.assertEqual(json.dumps(expected_content, sort_keys=True),
  59. json.dumps(json.loads(response.get_data().decode('utf-8')), sort_keys=True))
  60. def test_get_all_synapses(self):
  61. url = self.get_server_url()+"/synapses"
  62. response = self.client.get(url)
  63. expected_content = {
  64. "synapses": [
  65. {"signals": [{"name": "order", "parameters": "test_order"}],
  66. "neurons": [{"name": "say", "parameters": {"message": ["test message"]}}],
  67. "name": "test"},
  68. {"signals": [{"name": "order", "parameters": "bonjour"}],
  69. "neurons": [{"name": "say", "parameters": {"message": ["test message"]}}],
  70. "name": "test2"},
  71. {"signals": [{"name": "order", "parameters": "test_order_with_parameter"}],
  72. "neurons": [{"name": "say", "parameters": {"message": ["test message {{parameter1}}"]}}],
  73. "name": "test4"},
  74. {"signals": [],
  75. "neurons": [{"name": "say", "parameters": {"message": "order not found"}}],
  76. "name": "order-not-found-synapse"},
  77. {"signals": [{"name": "order", "parameters": "test_order_3"}],
  78. "neurons": [{"name": "say", "parameters": {"message": ["test message"]}}],
  79. "name": "test3"}]}
  80. # a lot of char ti process
  81. self.maxDiff = None
  82. self.assertEqual(response.status_code, 200)
  83. self.assertEqual(json.dumps(expected_content, sort_keys=True),
  84. json.dumps(json.loads(response.get_data().decode('utf-8')), sort_keys=True))
  85. def test_get_one_synapse(self):
  86. url = self.get_server_url() + "/synapses/test"
  87. response = self.client.get(url)
  88. expected_content = {
  89. "synapses": {
  90. "name": "test",
  91. "neurons": [
  92. {
  93. "name": "say",
  94. "parameters": {
  95. "message": [
  96. "test message"
  97. ]
  98. }
  99. }
  100. ],
  101. "signals": [
  102. {
  103. "name": "order",
  104. "parameters": "test_order"
  105. }
  106. ]
  107. }
  108. }
  109. self.assertEqual(json.dumps(expected_content, sort_keys=True),
  110. json.dumps(json.loads(response.get_data().decode('utf-8')), sort_keys=True))
  111. def test_get_synapse_not_found(self):
  112. url = self.get_server_url() + "/synapses/test-none"
  113. result = self.client.get(url)
  114. expected_content = {
  115. "error": {
  116. "synapse name not found": "test-none"
  117. }
  118. }
  119. self.assertEqual(expected_content, json.loads(result.get_data().decode('utf-8')))
  120. self.assertEqual(result.status_code, 404)
  121. def test_run_synapse_by_name(self):
  122. url = self.get_server_url() + "/synapses/start/id/test"
  123. result = self.client.post(url)
  124. expected_content = {'status': 'complete',
  125. 'matched_synapses':
  126. [{'matched_order': None,
  127. 'neuron_module_list':
  128. [{'generated_message': 'test message', 'neuron_name': 'Say'}],
  129. 'synapse_name': 'test'}],
  130. 'user_order': None
  131. }
  132. self.assertEqual(json.dumps(expected_content, sort_keys=True),
  133. json.dumps(json.loads(result.get_data().decode('utf-8')), sort_keys=True))
  134. self.assertEqual(result.status_code, 201)
  135. # run a synapse by its name with parameter
  136. url = self.get_server_url() + "/synapses/start/id/test4"
  137. headers = {"Content-Type": "application/json"}
  138. data = {"parameters": {"parameter1": "replaced_value"}}
  139. result = self.client.post(url, headers=headers, data=json.dumps(data))
  140. expected_content = {
  141. "matched_synapses": [
  142. {
  143. "matched_order": None,
  144. "neuron_module_list": [
  145. {
  146. "generated_message": "test message replaced_value",
  147. "neuron_name": "Say"
  148. }
  149. ],
  150. "synapse_name": "test4"
  151. }
  152. ],
  153. "status": "complete",
  154. "user_order": None
  155. }
  156. self.assertEqual(json.dumps(expected_content, sort_keys=True),
  157. json.dumps(json.loads(result.get_data().decode('utf-8')), sort_keys=True))
  158. self.assertEqual(result.status_code, 201)
  159. def test_post_synapse_not_found(self):
  160. url = self.get_server_url() + "/synapses/start/id/test-none"
  161. result = self.client.post(url)
  162. expected_content = {
  163. "error": {
  164. "synapse name not found": "test-none"
  165. }
  166. }
  167. self.assertEqual(json.dumps(expected_content, sort_keys=True),
  168. json.dumps(json.loads(result.get_data().decode('utf-8')), sort_keys=True))
  169. self.assertEqual(result.status_code, 404)
  170. def test_run_synapse_with_order(self):
  171. url = self.get_server_url() + "/synapses/start/order"
  172. headers = {"Content-Type": "application/json"}
  173. data = {"order": "test_order"}
  174. result = self.client.post(url, headers=headers, data=json.dumps(data))
  175. expected_content = {'status': 'complete',
  176. 'matched_synapses':
  177. [
  178. {
  179. 'matched_order': "test_order",
  180. 'neuron_module_list':
  181. [
  182. {
  183. 'generated_message': 'test message', 'neuron_name': 'Say'
  184. }
  185. ],
  186. 'synapse_name': 'test'
  187. }
  188. ],
  189. 'user_order': "test_order"
  190. }
  191. self.assertEqual(json.dumps(expected_content, sort_keys=True),
  192. json.dumps(json.loads(result.get_data().decode('utf-8')), sort_keys=True))
  193. self.assertEqual(result.status_code, 201)
  194. def test_post_synapse_by_order_not_found(self):
  195. url = self.get_server_url() + "/synapses/start/order"
  196. data = {"order": "non existing order"}
  197. headers = {"Content-Type": "application/json"}
  198. result = self.client.post(url,
  199. headers=headers,
  200. data=json.dumps(data))
  201. expected_content = {"matched_synapses": [{"matched_order": None,
  202. "neuron_module_list": [
  203. {"generated_message": "order not found",
  204. "neuron_name": "Say"}
  205. ],
  206. "synapse_name": "order-not-found-synapse"}],
  207. "status": "complete",
  208. "user_order": None}
  209. self.assertEqual(json.dumps(expected_content, sort_keys=True),
  210. json.dumps(json.loads(result.get_data().decode('utf-8')), sort_keys=True))
  211. self.assertEqual(result.status_code, 201)
  212. # TODO this doesn't work on travis but works locally with python -m unittest discover
  213. # def test_post_synapse_by_audio(self):
  214. # url = self.get_server_url() + "/synapses/start/audio"
  215. # with open(os.path.join(self.audio_file), 'rb') as fp:
  216. # file = FileStorage(fp)
  217. # data = {
  218. # 'file': file
  219. # }
  220. # result = self.client.post(url, data=data, content_type='multipart/form-data')
  221. #
  222. # expected_content = {
  223. # "synapses": [
  224. # {
  225. # "name": "test2",
  226. # "neurons": [
  227. # {
  228. # "name": "say",
  229. # "parameters": {
  230. # "message": [
  231. # "test message"
  232. # ]
  233. # }
  234. # }
  235. # ],
  236. # "signals": [
  237. # {
  238. # "order": "bonjour"
  239. # }
  240. # ]
  241. # }
  242. # ]
  243. # }
  244. #
  245. # self.assertEqual(json.dumps(expected_content), json.dumps(json.loads(result.get_data())))
  246. # self.assertEqual(result.status_code, 201)
  247. def test_convert_to_wav(self):
  248. """
  249. Test the api function to convert incoming sound file to wave.
  250. """
  251. with mock.patch("os.system") as mock_os_system:
  252. # Scenario 1 : input wav file
  253. temp_file = "/tmp/kalliope/tempfile.wav" # tempfile.NamedTemporaryFile(suffix=".wav")
  254. result_file = FlaskAPI._convert_to_wav(temp_file)
  255. self.assertEqual(temp_file, result_file)
  256. mock_os_system.assert_not_called()
  257. # Scenario 2 : input not a wav file
  258. temp_file = "/tmp/kalliope/tempfile.amr" # tempfile.NamedTemporaryFile(suffix=".wav")
  259. expected_result = "/tmp/kalliope/tempfile.wav"
  260. result_file = FlaskAPI._convert_to_wav(temp_file)
  261. self.assertEqual(expected_result, result_file)
  262. mock_os_system.assert_called_once_with("avconv -y -i " + temp_file + " " + expected_result)
  263. if __name__ == '__main__':
  264. unittest.main()
  265. # suite = unittest.TestSuite()
  266. # suite.addTest(TestRestAPI("test_get_all_synapses"))
  267. # runner = unittest.TextTestRunner()
  268. # runner.run(suite)