test_pagure_flask_api.py 11 KB

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