test_pagure_flask_api.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # -*- coding: utf-8 -*-
  2. """
  3. (c) 2015 - Copyright Red Hat Inc
  4. Authors:
  5. Pierre-Yves Chibon <pingou@pingoured.fr>
  6. """
  7. from __future__ import unicode_literals, absolute_import
  8. import unittest
  9. import shutil
  10. import sys
  11. import os
  12. import json
  13. from mock import patch, MagicMock
  14. sys.path.insert(0, os.path.join(os.path.dirname(
  15. os.path.abspath(__file__)), '..'))
  16. import pagure.api
  17. import pagure.flask_app
  18. import pagure.lib.query
  19. import tests
  20. class PagureFlaskApitests(tests.SimplePagureTest):
  21. """ Tests for flask API controller of pagure """
  22. maxDiff = None
  23. def test_api_doc(self):
  24. """ Test the API documentation page. """
  25. print(dir(self.app))
  26. output = self.app.get('/api/0/')
  27. output_text = output.get_data(as_text=True)
  28. self.assertIn(
  29. '<title> API | pagure - Pagure</title>\n', output_text)
  30. self.assertIn(
  31. '&nbsp; Pagure API Reference\n </h2>\n', output_text)
  32. def test_api_doc_authenticated(self):
  33. """ Test the API documentation page. """
  34. user = tests.FakeUser(username='foo')
  35. with tests.user_set(self.app.application, user):
  36. output = self.app.get('/api/0/')
  37. output_text = output.get_data(as_text=True)
  38. self.assertIn(
  39. '<title> API | pagure - Pagure</title>\n', output_text)
  40. self.assertIn(
  41. '&nbsp; Pagure API Reference\n </h2>\n', output_text)
  42. def test_api_get_request_data(self):
  43. data = {'foo': 'bar'}
  44. # test_request_context doesn't set flask.g, but some teardown
  45. # functions try to use that, so let's exclude them
  46. self._app.teardown_request_funcs = {}
  47. with self._app.test_request_context(
  48. '/api/0/version', method="POST", data=data):
  49. self.assertEqual(pagure.api.get_request_data()['foo'], 'bar')
  50. data = json.dumps(data)
  51. with self._app.test_request_context('/api/0/version', data=data,
  52. content_type='application/json'):
  53. self.assertEqual(pagure.api.get_request_data()['foo'], 'bar')
  54. def test_api_version_old_url(self):
  55. """ Test the api_version function. """
  56. output = self.app.get('/api/0/version')
  57. self.assertEqual(output.status_code, 200)
  58. data = json.loads(output.get_data(as_text=True))
  59. self.assertEqual(data['version'], pagure.__api_version__)
  60. self.assertEqual(sorted(data.keys()), ['version'])
  61. def test_api_version_new_url(self):
  62. """ Test the api_version function at its new url. """
  63. output = self.app.get('/api/0/-/version')
  64. self.assertEqual(output.status_code, 200)
  65. data = json.loads(output.get_data(as_text=True))
  66. self.assertEqual(data['version'], pagure.__api_version__)
  67. self.assertEqual(sorted(data.keys()), ['version'])
  68. def test_api_project_tags(self):
  69. """ Test the api_project_tags function. """
  70. tests.create_projects(self.session)
  71. output = self.app.get('/api/0/foo/tags/')
  72. self.assertEqual(output.status_code, 404)
  73. data = json.loads(output.get_data(as_text=True))
  74. self.assertEqual(set(data.keys()), set(['output', 'error']))
  75. self.assertEqual(data['output'], 'notok')
  76. self.assertEqual(data['error'], 'Project not found')
  77. output = self.app.get('/api/0/test/tags/')
  78. self.assertEqual(output.status_code, 200)
  79. data = json.loads(output.get_data(as_text=True))
  80. self.assertEqual(sorted(data.keys()), ['tags', 'total_tags'])
  81. self.assertEqual(data['tags'], [])
  82. self.assertEqual(data['total_tags'], 0)
  83. # Add an issue and tag it so that we can list them
  84. item = pagure.lib.model.Issue(
  85. id=1,
  86. uid='foobar',
  87. project_id=1,
  88. title='issue',
  89. content='a bug report',
  90. user_id=1, # pingou
  91. )
  92. self.session.add(item)
  93. self.session.commit()
  94. item = pagure.lib.model.TagColored(
  95. tag='tag1', tag_color='DeepBlueSky', project_id=1,
  96. )
  97. self.session.add(item)
  98. self.session.commit()
  99. item = pagure.lib.model.TagIssueColored(
  100. issue_uid='foobar',
  101. tag_id=item.id
  102. )
  103. self.session.add(item)
  104. self.session.commit()
  105. output = self.app.get('/api/0/test/tags/')
  106. self.assertEqual(output.status_code, 200)
  107. data = json.loads(output.get_data(as_text=True))
  108. self.assertEqual(sorted(data.keys()), ['tags', 'total_tags'])
  109. self.assertEqual(data['tags'], ['tag1'])
  110. self.assertEqual(data['total_tags'], 1)
  111. output = self.app.get('/api/0/test/tags/?pattern=t')
  112. self.assertEqual(output.status_code, 200)
  113. data = json.loads(output.get_data(as_text=True))
  114. self.assertEqual(sorted(data.keys()), ['tags', 'total_tags'])
  115. self.assertEqual(data['tags'], ['tag1'])
  116. self.assertEqual(data['total_tags'], 1)
  117. output = self.app.get('/api/0/test/tags/?pattern=p')
  118. self.assertEqual(output.status_code, 200)
  119. data = json.loads(output.get_data(as_text=True))
  120. self.assertEqual(sorted(data.keys()), ['tags', 'total_tags'])
  121. self.assertEqual(data['tags'], [])
  122. self.assertEqual(data['total_tags'], 0)
  123. def test_api_groups(self):
  124. """ Test the api_groups function. """
  125. # Add a couple of groups so that we can list them
  126. item = pagure.lib.model.PagureGroup(
  127. group_name='group1',
  128. group_type='user',
  129. display_name='User group',
  130. user_id=1, # pingou
  131. )
  132. self.session.add(item)
  133. item = pagure.lib.model.PagureGroup(
  134. group_name='rel-eng',
  135. group_type='user',
  136. display_name='Release engineering group',
  137. user_id=1, # pingou
  138. )
  139. self.session.add(item)
  140. self.session.commit()
  141. output = self.app.get('/api/0/groups')
  142. self.assertEqual(output.status_code, 200)
  143. data = json.loads(output.get_data(as_text=True))
  144. self.assertEqual(data['groups'], ['group1', 'rel-eng'])
  145. self.assertEqual(
  146. sorted(data.keys()),
  147. ['groups', 'pagination', 'total_groups'])
  148. self.assertEqual(data['total_groups'], 2)
  149. output = self.app.get('/api/0/groups?pattern=re')
  150. self.assertEqual(output.status_code, 200)
  151. data = json.loads(output.get_data(as_text=True))
  152. self.assertEqual(data['groups'], ['rel-eng'])
  153. self.assertEqual(
  154. sorted(data.keys()),
  155. ['groups', 'pagination', 'total_groups'])
  156. self.assertEqual(data['total_groups'], 1)
  157. def test_api_whoami_unauth(self):
  158. """ Test the api_whoami function. """
  159. output = self.app.post('/api/0/-/whoami')
  160. self.assertEqual(output.status_code, 401)
  161. data = json.loads(output.get_data(as_text=True))
  162. self.assertEqual(
  163. data,
  164. {
  165. u'error': u'Invalid or expired token. Please visit '
  166. 'http://localhost.localdomain/settings#api-keys to get or '
  167. 'renew your API token.',
  168. u'error_code': u'EINVALIDTOK'
  169. }
  170. )
  171. def test_api_whoami_invalid_auth(self):
  172. """ Test the api_whoami function with an invalid token. """
  173. tests.create_projects(self.session)
  174. tests.create_tokens(self.session)
  175. headers = {'Authorization': 'token invalid'}
  176. output = self.app.post('/api/0/-/whoami', headers=headers)
  177. self.assertEqual(output.status_code, 401)
  178. data = json.loads(output.get_data(as_text=True))
  179. self.assertEqual(
  180. data,
  181. {
  182. u'error': u'Invalid or expired token. Please visit '
  183. 'http://localhost.localdomain/settings#api-keys to get or '
  184. 'renew your API token.',
  185. u'error_code': u'EINVALIDTOK'
  186. }
  187. )
  188. def test_api_whoami_auth(self):
  189. """ Test the api_whoami function with a valid token. """
  190. tests.create_projects(self.session)
  191. tests.create_tokens(self.session)
  192. headers = {'Authorization': 'token aaabbbcccddd'}
  193. output = self.app.post('/api/0/-/whoami', headers=headers)
  194. self.assertEqual(output.status_code, 200)
  195. data = json.loads(output.get_data(as_text=True))
  196. self.assertEqual(data, {u'username': u'pingou'})
  197. def test_api_error_codes(self):
  198. """ Test the api_error_codes endpoint. """
  199. output = self.app.get('/api/0/-/error_codes')
  200. self.assertEqual(output.status_code, 200)
  201. data = json.loads(output.get_data(as_text=True))
  202. self.assertEqual(len(data), 34)
  203. self.assertEqual(
  204. sorted(data.keys()),
  205. [
  206. u'EDATETIME', u'EDBERROR', u'EGITERROR',
  207. u'EINVALIDISSUEFIELD', u'EINVALIDISSUEFIELD_LINK',
  208. u'EINVALIDPERPAGEVALUE', u'EINVALIDPRIORITY', u'EINVALIDREQ',
  209. u'EINVALIDTOK', u'EISSUENOTALLOWED',
  210. u'EMODIFYPROJECTNOTALLOWED', u'ENEWPROJECTDISABLED',
  211. u'ENOCODE', u'ENOCOMMENT', u'ENOCOMMIT', u'ENOGROUP',
  212. u'ENOISSUE', u'ENOPRCLOSE', u'ENOPROJECT', u'ENOPROJECTS',
  213. u'ENOPRSTATS', u'ENOREQ', u'ENOSIGNEDOFF', u'ENOTASSIGNED',
  214. u'ENOTASSIGNEE', u'ENOTHIGHENOUGH', u'ENOTMAINADMIN',
  215. u'ENOUSER', u'EPRCONFLICTS', u'EPRSCORE',
  216. u'EPULLREQUESTSDISABLED', u'ETIMESTAMP', u'ETRACKERDISABLED',
  217. u'ETRACKERREADONLY'
  218. ]
  219. )
  220. @patch("pagure.lib.tasks.get_result")
  221. def test_api_task_status(self, get_result):
  222. async_result = MagicMock()
  223. async_result.status = "running"
  224. async_result.ready.return_value = False
  225. get_result.return_value = async_result
  226. output = self.app.get("/api/0/task/123abc/status/")
  227. self.assertEqual(output.status_code, 200)
  228. data = json.loads(output.get_data(as_text=True))
  229. self.assertEqual(data, {"ready": False, "status": "running"})
  230. async_result = MagicMock()
  231. async_result.status = "finished"
  232. async_result.ready.return_value = True
  233. async_result.successful.return_value = True
  234. get_result.return_value = async_result
  235. output = self.app.get("/api/0/task/123abc/status/")
  236. self.assertEqual(output.status_code, 200)
  237. data = json.loads(output.get_data(as_text=True))
  238. self.assertEqual(
  239. data,
  240. {"ready": True, "status": "finished", "successful": True}
  241. )
  242. if __name__ == '__main__':
  243. unittest.main(verbosity=2)