test_result.py
12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2015 SciFabric LTD.
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.
import json
from default import db, with_context
from nose.tools import assert_equal
from test_api import TestAPI
from mock import patch, call
from pybossa.core import project_repo, task_repo, result_repo
from factories import ProjectFactory, TaskFactory, TaskRunFactory, UserFactory
from pybossa.repositories import ResultRepository
class TestResultAPI(TestAPI):
def setUp(self):
super(TestResultAPI, self).setUp()
self.result_repo = ResultRepository(db)
def create_result(self, n_results=1, n_answers=1, owner=None,
filter_by=False):
if owner:
owner = owner
else:
owner = UserFactory.create()
project = ProjectFactory.create(owner=owner)
tasks = []
for i in range(n_results):
tasks.append(TaskFactory.create(n_answers=n_answers,
project=project))
for i in range(n_answers):
for task in tasks:
TaskRunFactory.create(task=task, project=project)
if filter_by:
return self.result_repo.filter_by(project_id=1)
else:
return self.result_repo.get_by(project_id=1)
@with_context
def test_result_query_without_params(self):
""" Test API Result query"""
result = self.create_result(n_answers=10)
res = self.app.get('/api/result')
results = json.loads(res.data)
assert len(results) == 1, results
result = results[0]
assert result['info'] is None, result
assert len(result['task_run_ids']) == 10, result
assert result['task_run_ids'] == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], result
assert result['project_id'] == 1, result
assert result['task_id'] == 1, result
assert result['created'] is not None, result
# The output should have a mime-type: application/json
assert res.mimetype == 'application/json', res
@with_context
def test_result_query_with_params(self):
"""Test API query for result with params works"""
results = self.create_result(n_results=10, filter_by=True)
# Test for real field
res = self.app.get("/api/result?project_id=1")
data = json.loads(res.data)
# Should return one result
assert len(data) == 10, data
# Correct result
assert data[0]['project_id'] == 1, data
# Valid field but wrong value
res = self.app.get("/api/result?project_id=99999999")
data = json.loads(res.data)
assert len(data) == 0, data
# Multiple fields
res = self.app.get('/api/result?project_id=1&task_id=1')
data = json.loads(res.data)
# One result
assert len(data) == 1, data
# Correct result
assert data[0]['project_id'] == 1, data
assert data[0]['task_id'] == 1, data
# Limits
res = self.app.get("/api/result?project_id=1&limit=5")
data = json.loads(res.data)
for item in data:
assert item['project_id'] == 1, item
assert len(data) == 5, len(data)
# Keyset pagination
url = "/api/result?project_id=1&limit=5&last_id=1"
res = self.app.get(url)
data = json.loads(res.data)
for item in data:
assert item['project_id'] == 1, item
assert len(data) == 5, data
assert data[0]['id'] == 2, data[0]
@with_context
def test_result_post(self):
"""Test API Result creation"""
admin = UserFactory.create()
user = UserFactory.create()
non_owner = UserFactory.create()
project = ProjectFactory.create(owner=user)
data = dict(info='final result')
# anonymous user
# no api-key
res = self.app.post('/api/result', data=json.dumps(data))
error_msg = 'Should not be allowed to create'
assert_equal(res.status, '401 UNAUTHORIZED', error_msg)
### real user but not allowed as not owner!
res = self.app.post('/api/result?api_key=' + non_owner.api_key,
data=json.dumps(data))
error_msg = 'Should not be able to post tasks for projects of others'
assert_equal(res.status, '403 FORBIDDEN', error_msg)
# now a real user
res = self.app.post('/api/result?api_key=' + user.api_key,
data=json.dumps(data))
assert_equal(res.status, '403 FORBIDDEN', error_msg)
# now the root user
res = self.app.post('/api/result?api_key=' + admin.api_key,
data=json.dumps(data))
assert_equal(res.status, '403 FORBIDDEN', error_msg)
# POST with not JSON data
url = '/api/result?api_key=%s' % user.api_key
res = self.app.post(url, data=data)
err = json.loads(res.data)
assert res.status_code == 415, err
assert err['status'] == 'failed', err
assert err['target'] == 'result', err
assert err['action'] == 'POST', err
assert err['exception_cls'] == 'ValueError', err
# POST with not allowed args
res = self.app.post(url + '&foo=bar', data=json.dumps(data))
err = json.loads(res.data)
assert res.status_code == 415, err
assert err['status'] == 'failed', err
assert err['target'] == 'result', err
assert err['action'] == 'POST', err
assert err['exception_cls'] == 'AttributeError', err
# POST with fake data
data['wrongfield'] = 13
res = self.app.post(url, data=json.dumps(data))
err = json.loads(res.data)
assert res.status_code == 415, err
assert err['status'] == 'failed', err
assert err['target'] == 'result', err
assert err['action'] == 'POST', err
assert err['exception_cls'] == 'TypeError', err
def test_result_post_with_reserved_fields_returns_error(self):
user = UserFactory.create()
project = ProjectFactory.create(owner=user)
data = {'created': 'today',
'id': 222, 'project_id': project.id}
res = self.app.post('/api/result?api_key=' + user.api_key,
data=json.dumps(data))
assert res.status_code == 400, res.status_code
error = json.loads(res.data)
assert error['exception_msg'] == "Reserved keys in payload", error
def test_result_put_with_reserved_fields_returns_error(self):
user = UserFactory.create()
result = self.create_result(owner=user)
print result
url = '/api/result/%s?api_key=%s' % (result.id, user.api_key)
data = {'created': 'today',
'project_id': 1,
'id': 222}
res = self.app.put(url, data=json.dumps(data))
assert res.status_code == 400, res.status_code
error = json.loads(res.data)
assert error['exception_msg'] == "Reserved keys in payload", error
@with_context
def test_result_update(self):
"""Test API result update"""
admin = UserFactory.create()
user = UserFactory.create()
non_owner = UserFactory.create()
data = dict(info=dict(foo='bar'))
datajson = json.dumps(data)
result = self.create_result(owner=user)
## anonymous
res = self.app.put('/api/result/%s' % result.id, data=datajson)
assert_equal(res.status, '401 UNAUTHORIZED', res.status)
### real user but not allowed as not owner!
url = '/api/result/%s?api_key=%s' % (result.id, non_owner.api_key)
res = self.app.put(url, data=datajson)
assert_equal(res.status, '403 FORBIDDEN', res.status)
### real user
url = '/api/result/%s?api_key=%s' % (result.id, user.api_key)
res = self.app.put(url, data=datajson)
out = json.loads(res.data)
assert_equal(res.status, '200 OK', res.data)
assert_equal(result.info['foo'], data['info']['foo'])
assert result.id == out['id'], out
### root
res = self.app.put('/api/result/%s?api_key=%s' % (result.id, admin.api_key),
data=datajson)
assert_equal(res.status, '403 FORBIDDEN', res.status)
# PUT with not JSON data
res = self.app.put(url, data=None)
err = json.loads(res.data)
assert res.status_code == 415, err
assert err['status'] == 'failed', err
assert err['target'] == 'result', err
assert err['action'] == 'PUT', err
assert err['exception_cls'] == 'ValueError', err
# PUT with not allowed args
res = self.app.put(url + "&foo=bar", data=json.dumps(data))
err = json.loads(res.data)
assert res.status_code == 415, err
assert err['status'] == 'failed', err
assert err['target'] == 'result', err
assert err['action'] == 'PUT', err
assert err['exception_cls'] == 'AttributeError', err
# PUT with fake data
data['wrongfield'] = 13
res = self.app.put(url, data=json.dumps(data))
err = json.loads(res.data)
assert res.status_code == 415, err
assert err['status'] == 'failed', err
assert err['target'] == 'result', err
assert err['action'] == 'PUT', err
assert err['exception_cls'] == 'TypeError', err
@with_context
def test_result_delete(self):
"""Test API result delete"""
admin = UserFactory.create()
user = UserFactory.create()
non_owner = UserFactory.create()
result = self.create_result(owner=user)
## anonymous
res = self.app.delete('/api/result/%s' % result.id)
error_msg = 'Anonymous should not be allowed to update'
assert_equal(res.status, '401 UNAUTHORIZED', error_msg)
### real user but not allowed as not owner!
url = '/api/result/%s?api_key=%s' % (result.id, non_owner.api_key)
res = self.app.delete(url)
error_msg = 'Should not be able to update tasks of others'
assert_equal(res.status, '403 FORBIDDEN', error_msg)
#### real user
# DELETE with not allowed args
res = self.app.delete(url + "&foo=bar")
err = json.loads(res.data)
assert res.status_code == 415, err
assert err['status'] == 'failed', err
assert err['target'] == 'result', err
assert err['action'] == 'DELETE', err
assert err['exception_cls'] == 'AttributeError', err
# DELETE returns 403
url = '/api/result/%s?api_key=%s' % (result.id, user.api_key)
res = self.app.delete(url)
assert_equal(res.status, '403 FORBIDDEN', res.data)
#### root user
url = '/api/result/%s?api_key=%s' % (result.id, admin.api_key)
res = self.app.delete(url)
assert_equal(res.status, '403 FORBIDDEN', res.data)
@with_context
def test_get_last_version(self):
"""Test API result returns always latest version."""
result = self.create_result()
project = project_repo.get(result.project_id)
task = task_repo.get_task(result.task_id)
task.n_answers = 2
TaskRunFactory.create(task=task, project=project)
result = result_repo.get_by(project_id=project.id)
assert result.last_version is True, result.last_version
result_id = result.id
results = result_repo.filter_by(project_id=project.id, last_version=False)
assert len(results) == 2, len(results)
for r in results:
if r.id == result_id:
assert r.last_version is True, r.last_version
else:
assert r.last_version is False, r.last_version