forked from Scifabric/pybossa
/
test_api.py
685 lines (588 loc) · 23.5 KB
/
test_api.py
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
import json
#import urllib
from flaskext.login import current_user
from base import web, model, Fixtures, db
from nose.tools import assert_equal
class TestAPI:
def setUp(self):
self.app = web.app.test_client()
model.rebuild_db()
Fixtures.create()
self.endpoints = ['app', 'task', 'taskrun']
def tearDown(self):
db.session.remove()
@classmethod
def teardown_class(cls):
model.rebuild_db()
# Helper functions
def register(self, method="POST", fullname="John Doe", username="johndoe",
password="p4ssw0rd", password2=None, email=None):
"""Helper function to register and sign in a user"""
if password2 is None:
password2 = password
if email is None:
email = username + '@example.com'
if method == "POST":
return self.app.post('/account/register', data={
'fullname': fullname,
'username': username,
'email_addr': email,
'password': password,
'confirm': password2,
}, follow_redirects=True)
else:
return self.app.get('/account/register', follow_redirects=True)
def signin(self, method="POST", username="johndoe", password="p4ssw0rd",
next=None):
"""Helper function to sign in current user"""
url = '/account/signin'
if next != None:
url = url + '?next=' + next
if method == "POST":
return self.app.post(url, data={
'username': username,
'password': password,
}, follow_redirects=True)
else:
return self.app.get(url, follow_redirects=True)
def signout(self):
"""Helper function to sign out current user"""
return self.app.get('/account/signout', follow_redirects=True)
def test_00_limits_query(self):
"""Test API GET limits works"""
for i in range(30):
app = model.App(name="name%s" % i,
short_name="short_name%s" % i,
description="desc",
owner_id=1)
info = dict(a=0)
task = model.Task(app_id=1, info=info)
taskrun = model.TaskRun(app_id=1, task_id=1)
db.session.add(app)
db.session.add(task)
db.session.add(taskrun)
db.session.commit()
res = self.app.get('/api/app')
data = json.loads(res.data)
assert len(data) == 20, len(data)
res = self.app.get('/api/app?limit=10')
data = json.loads(res.data)
assert len(data) == 10, len(data)
res = self.app.get('/api/app?limit=10&offset=10')
data = json.loads(res.data)
assert len(data) == 10, len(data)
assert data[0].get('name')=='name9'
res = self.app.get('/api/task')
data = json.loads(res.data)
assert len(data) == 20, len(data)
res = self.app.get('/api/taskrun')
data = json.loads(res.data)
assert len(data) == 20, len(data)
def test_01_app_query(self):
""" Test API App query"""
res = self.app.get('/api/app')
data = json.loads(res.data)
assert len(data) == 1, data
app = data[0]
assert app['info']['total'] == 150, data
# The output should have a mime-type: application/json
assert res.mimetype == 'application/json', res
def test_get_query_with_api_key(self):
""" Test API GET query with an API-KEY"""
for endpoint in self.endpoints:
res = self.app.get('/api/' + endpoint + '?api_key='\
+ Fixtures.api_key)
data = json.loads(res.data)
if endpoint == 'app':
assert len(data) == 1, data
app = data[0]
assert app['info']['total'] == 150, data
# The output should have a mime-type: application/json
assert res.mimetype == 'application/json', res
if endpoint == 'task':
assert len(data) == 10, data
task = data[0]
assert task['info']['url'] == 'my url', data
# The output should have a mime-type: application/json
assert res.mimetype == 'application/json', res
if endpoint == 'taskrun':
assert len(data) == 10, data
taskrun = data[0]
assert taskrun['info']['answer'] == 'annakarenina', data
# The output should have a mime-type: application/json
assert res.mimetype == 'application/json', res
def test_query_search_wrongfield(self):
""" Test API query search works"""
# Test first a non-existant field for all end-points
endpoints = ['app', 'task', 'taskrun']
for endpoint in endpoints:
res = self.app.get("/api/%s?wrongfield=value" % endpoint)
data = json.loads(res.data)
assert "no such column: wrongfield" in data['error'], data
def test_query_sql_injection(self):
"""Test API SQL Injection is not allowed works"""
q = '1%3D1;SELECT%20*%20FROM%20task%20WHERE%201=1'
res = self.app.get('/api/task?' + q)
data = json.loads(res.data)
assert "no such column: " in data['error'], data
q = 'app_id=1%3D1;SELECT%20*%20FROM%20task%20WHERE%201'
res = self.app.get('/api/task?' + q)
data = json.loads(res.data)
assert "invalid input syntax" in data['error'], data
def test_query_app(self):
"""Test API query for app endpoint works"""
# Test for real field
res = self.app.get("/api/app?short_name=test-app")
data = json.loads(res.data)
# Should return one result
assert len(data) == 1, data
# Correct result
assert data[0]['short_name'] == 'test-app', data
# Valid field but wrong value
res = self.app.get("/api/app?short_name=wrongvalue")
data = json.loads(res.data)
assert len(data) == 0, data
# Multiple fields
res = self.app.get('/api/app?short_name=test-app&name=My New App')
data = json.loads(res.data)
# One result
assert len(data) == 1, data
# Correct result
assert data[0]['short_name'] == 'test-app', data
assert data[0]['name'] == 'My New App', data
# Limits
res = self.app.get("/api/taskrun?app_id=1&limit=5")
print res.data
data = json.loads(res.data)
for item in data:
assert item['app_id'] == 1, item
assert len(data) == 5, data
def test_query_task(self):
"""Test API query for task endpoint works"""
# Test for real field
res = self.app.get("/api/task?app_id=1")
data = json.loads(res.data)
# Should return one result
assert len(data) == 10, data
# Correct result
assert data[0]['app_id'] == 1, data
# Valid field but wrong value
res = self.app.get("/api/task?app_id=99999999")
data = json.loads(res.data)
assert len(data) == 0, data
# Multiple fields
res = self.app.get('/api/task?app_id=1&state=0')
data = json.loads(res.data)
# One result
assert len(data) == 10, data
# Correct result
assert data[0]['app_id'] == 1, data
assert data[0]['state'] == '0', data
# Limits
res = self.app.get("/api/task?app_id=1&limit=5")
print res.data
data = json.loads(res.data)
for item in data:
assert item['app_id'] == 1, item
assert len(data) == 5, data
def test_query_taskrun(self):
"""Test API query for taskrun endpoint works"""
# Test for real field
res = self.app.get("/api/taskrun?app_id=1")
data = json.loads(res.data)
# Should return one result
assert len(data) == 10, data
# Correct result
assert data[0]['app_id'] == 1, data
# Valid field but wrong value
res = self.app.get("/api/taskrun?app_id=99999999")
data = json.loads(res.data)
assert len(data) == 0, data
# Multiple fields
res = self.app.get('/api/taskrun?app_id=1&task_id=1')
data = json.loads(res.data)
# One result
assert len(data) == 1, data
# Correct result
assert data[0]['app_id'] == 1, data
assert data[0]['task_id'] == 1, data
# Limits
res = self.app.get("/api/taskrun?app_id=1&limit=5")
print res.data
data = json.loads(res.data)
for item in data:
assert item['app_id'] == 1, item
assert len(data) == 5, data
def test_02_task_query(self):
""" Test API Task query"""
res = self.app.get('/api/task')
tasks = json.loads(res.data)
assert len(tasks) == 10, tasks
task = tasks[0]
assert task['info']['question'] == 'My random question', task
# The output should have a mime-type: application/json
assert res.mimetype == 'application/json', res
def test_03_taskrun_query(self):
"""Test API TaskRun query"""
res = self.app.get('/api/taskrun')
taskruns = json.loads(res.data)
assert len(taskruns) == 10, taskruns
taskrun = taskruns[0]
#print taskrun
assert taskrun['info']['answer'] == 'annakarenina', taskrun
# The output should have a mime-type: application/json
assert res.mimetype == 'application/json', res
def test_04_app_post(self):
"""Test API App creation and auth"""
name = u'XXXX Project'
data = dict(
name=name,
short_name='xxxx-project',
long_description=u'<div id="longdescription">\
Long Description</div>')
data = json.dumps(data)
# no api-key
res = self.app.post('/api/app',
data=data
)
assert_equal(res.status, '403 FORBIDDEN',
'Should not be allowed to create')
# now a real user
res = self.app.post('/api/app?api_key=' + Fixtures.api_key,
data=data,
)
out = db.session.query(model.App).filter_by(name=name).one()
assert out, out
assert_equal(out.short_name, 'xxxx-project'), out
assert_equal(out.owner.name, 'tester')
id_ = out.id
db.session.remove()
# test update
data = {
'name': 'My New Title'
}
datajson = json.dumps(data)
## anonymous
res = self.app.put('/api/app/%s' % id_,
data=data
)
assert_equal(res.status, '403 FORBIDDEN',
'Anonymous should not be allowed to update')
### real user but not allowed as not owner!
res = self.app.put('/api/app/%s?api_key=%s' %\
(id_, Fixtures.api_key_2), data=datajson)
assert_equal(res.status,\
'401 UNAUTHORIZED',\
'Should not be able to update apps of others')
res = self.app.put('/api/app/%s?api_key=%s' % (id_, Fixtures.api_key),
data=datajson
)
assert_equal(res.status, '200 OK', res.data)
out2 = db.session.query(model.App).get(id_)
assert_equal(out2.name, data['name'])
# test delete
## anonymous
res = self.app.delete('/api/app/%s' % id_,
data=data
)
assert_equal(res.status, '403 FORBIDDEN',\
'Anonymous should not be allowed to delete')
### real user but not allowed as not owner!
res = self.app.delete('/api/app/%s?api_key=%s' %\
(id_, Fixtures.api_key_2), data=datajson)
assert_equal(res.status, '401 UNAUTHORIZED',\
'Should not be able to delete apps of others')
res = self.app.delete('/api/app/%s?api_key=%s' %\
(id_, Fixtures.api_key), data=datajson)
assert_equal(res.status, '204 NO CONTENT', res.data)
def test_05_task_post(self):
'''Test API Task creation and auth'''
user = db.session.query(model.User)\
.filter_by(name=Fixtures.name)\
.one()
app = db.session.query(model.App)\
.filter_by(owner_id=user.id)\
.one()
data = dict(
app_id=app.id,
state='0',
info='my task data'
)
data = json.dumps(data)
########
# POST #
########
# anonymous user
# no api-key
res = self.app.post('/api/task',
data=data
)
assert_equal(res.status, '403 FORBIDDEN',\
'Should not be allowed to create')
### real user but not allowed as not owner!
res = self.app.post('/api/task?api_key=' + Fixtures.api_key_2,
data=data
)
#print res.status
assert_equal(res.status, '401 UNAUTHORIZED',\
'Should not be able to post tasks for apps of others')
# now a real user
res = self.app.post('/api/task?api_key=' + Fixtures.api_key,
data=data,
)
assert res.data, res
datajson = json.loads(res.data)
out = db.session.query(model.Task)\
.filter_by(id=datajson['id'])\
.one()
assert out, out
assert_equal(out.info, 'my task data'), out
assert_equal(out.app_id, app.id)
id_ = out.id
##########
# UPDATE #
##########
data = {
'state': '1'
}
datajson = json.dumps(data)
## anonymous
res = self.app.put('/api/task/%s' % id_,
data=data
)
assert_equal(res.status, '403 FORBIDDEN',\
'Anonymous should not be allowed to update')
### real user but not allowed as not owner!
res = self.app.put('/api/task/%s?api_key=%s' %\
(id_, Fixtures.api_key_2), data=datajson)
assert_equal(res.status, '401 UNAUTHORIZED',\
'Should not be able to update tasks of others')
### real user
res = self.app.put('/api/task/%s?api_key=%s' % (id_, Fixtures.api_key),
data=datajson
)
assert_equal(res.status, '200 OK', res.data)
out2 = db.session.query(model.Task).get(id_)
assert_equal(out2.state, data['state'])
##########
# DELETE #
##########
## anonymous
res = self.app.delete('/api/task/%s' % id_)
assert_equal(res.status, '403 FORBIDDEN',\
'Anonymous should not be allowed to update')
### real user but not allowed as not owner!
res = self.app.delete('/api/task/%s?api_key=%s' %\
(id_, Fixtures.api_key_2))
assert_equal(res.status, '401 UNAUTHORIZED',\
'Should not be able to update tasks of others')
#### real user
res = self.app.delete('/api/task/%s?api_key=%s' %\
(id_, Fixtures.api_key))
assert_equal(res.status, '204 NO CONTENT', res.data)
tasks = db.session.query(model.Task)\
.filter_by(app_id=app.id)\
.all()
assert tasks, tasks
def test_06_taskrun_post(self):
"""Test API TaskRun creation and auth"""
app = db.session.query(model.App)\
.filter_by(short_name=Fixtures.app_name)\
.one()
tasks = db.session.query(model.Task)\
.filter_by(app_id=app.id)
app_id = app.id
# Create taskrun
data = dict(
app_id=app_id,
task_id=tasks[0].id,
info='my task result'
)
datajson = json.dumps(data)
# anonymous user
# any user can create a TaskRun
res = self.app.post('/api/taskrun',
data=datajson)
taskrun = db.session.query(model.TaskRun)\
.filter_by(info=data['info'])\
.one()
_id_anonymous = taskrun.id
assert taskrun, taskrun
assert taskrun.created, taskrun
assert_equal(taskrun.app_id, app_id), taskrun
# create task run as authenticated user
res = self.app.post('/api/taskrun?api_key=%s' % Fixtures.api_key,
data=datajson
)
taskrun = db.session.query(model.TaskRun)\
.filter_by(app_id=app_id)\
.all()[-1]
_id = taskrun.id
assert taskrun.app_id == app_id, taskrun
assert taskrun.user.name == Fixtures.name, taskrun
##########
# UPDATE #
##########
data['info'] = 'another result, I had a typo in the previous one'
datajson = json.dumps(data)
# anonymous user
# No one can update anonymous TaskRuns
res = self.app.put('/api/taskrun/%s' %\
_id_anonymous, data=datajson)
taskrun = db.session.query(model.TaskRun)\
.filter_by(id=_id_anonymous)\
.one()
assert taskrun, taskrun
assert_equal(taskrun.user, None)
assert_equal(res.status, '403 FORBIDDEN',\
'Should not be allowed to update')
# real user but not allowed as not owner!
res = self.app.put('/api/taskrun/%s?api_key=%s' %\
(_id, Fixtures.api_key_2), data=datajson)
assert_equal(res.status, '401 UNAUTHORIZED',\
'Should not be able to update TaskRuns of others')
# real user
res = self.app.put('/api/taskrun/%s?api_key=%s' %\
(_id, Fixtures.api_key), data=datajson)
assert_equal(res.status, '200 OK', res.data)
out2 = db.session.query(model.TaskRun).get(_id)
assert_equal(out2.info, data['info'])
assert_equal(out2.user.name, Fixtures.name)
##########
# DELETE #
##########
## anonymous
res = self.app.delete('/api/taskrun/%s' % _id)
assert_equal(res.status, '403 FORBIDDEN',\
'Anonymous should not be allowed to delete')
### real user but not allowed to delete anonymous TaskRuns
res = self.app.delete('/api/taskrun/%s?api_key=%s' %\
(_id_anonymous, Fixtures.api_key))
assert_equal(res.status, '401 UNAUTHORIZED',\
'Anonymous should not be allowed to delete anonymous TaskRuns')
### real user but not allowed as not owner!
res = self.app.delete('/api/taskrun/%s?api_key=%s' %\
(_id, Fixtures.api_key_2))
assert_equal(res.status, '401 UNAUTHORIZED',\
'Should not be able to delete TaskRuns of others')
#### real user
res = self.app.delete('/api/taskrun/%s?api_key=%s' %\
(_id, Fixtures.api_key))
assert_equal(res.status, '204 NO CONTENT', res.data)
tasks = db.session.query(model.Task)\
.filter_by(app_id=app_id)\
.all()
assert tasks, tasks
def test_taskrun_newtask(self):
"""Test API App.new_task method and authentication"""
app = db.session.query(model.App)\
.filter_by(short_name=Fixtures.app_name)\
.one()
# anonymous
# test getting a new task
res = self.app.get('/api/app/%s/newtask' % app.id)
assert res, res
task = json.loads(res.data)
assert_equal(task['app_id'], app.id)
# The output should have a mime-type: application/json
assert res.mimetype == 'application/json', res
# as a real user
res = self.app.get('/api/app/%s/newtask?api_key=%s' %\
(app.id, Fixtures.api_key))
assert res, res
task = json.loads(res.data)
assert_equal(task['app_id'], app.id)
# test wit no TaskRun items in the db
db.session.query(model.TaskRun).delete()
db.session.commit()
# anonymous
# test getting a new task
res = self.app.get('/api/app/%s/newtask' % app.id)
assert res, res
task = json.loads(res.data)
assert_equal(task['app_id'], app.id)
# as a real user
res = self.app.get('/api/app/%s/newtask?api_key=%s' %\
(app.id, Fixtures.api_key))
assert res, res
task = json.loads(res.data)
assert_equal(task['app_id'], app.id)
def test_07_user_progress_anonymous(self):
"""Test API userprogress as anonymous works"""
self.signout()
app = db.session.query(model.App)\
.get(1)
tasks = db.session.query(model.Task)\
.filter(model.Task.app_id == app.id)\
.all()
taskruns = db.session.query(model.TaskRun)\
.filter(model.TaskRun.app_id == app.id)\
.filter(model.TaskRun.user_id == 1)\
.all()
res = self.app.get('/api/app/1/userprogress', follow_redirects=True)
data = json.loads(res.data)
assert len(tasks) == data['total'],\
"The reported total number of tasks is wrong"
assert len(taskruns) == data['done'],\
"The reported number of done tasks is wrong"
res = self.app.get('/api/app/1/newtask')
data = json.loads(res.data)
print data
# Add a new TaskRun and check again
tr = model.TaskRun(
app_id=1,
task_id=data['id'],
user_id=1,
info={'answer': u'annakarenina'}
)
db.session.add(tr)
db.session.commit()
res = self.app.get('/api/app/1/userprogress', follow_redirects=True)
data = json.loads(res.data)
assert len(tasks) == data['total'],\
"The reported total number of tasks is wrong"
assert len(taskruns) + 1 == data['done'],\
"The reported number of done tasks is wrong: %s" %\
len(taskruns)
def test_08_user_progress_authenticated_user(self):
"""Test API userprogress as an authenticated user works"""
self.register()
self.signin()
user = db.session.query(model.User)\
.filter(model.User.name == 'johndoe')\
.first()
app = db.session.query(model.App)\
.get(1)
tasks = db.session.query(model.Task)\
.filter(model.Task.app_id == app.id)\
.all()
taskruns = db.session.query(model.TaskRun)\
.filter(model.TaskRun.app_id == app.id)\
.filter(model.TaskRun.user_id == user.id)\
.all()
res = self.app.get('/api/app/1/userprogress', follow_redirects=True)
data = json.loads(res.data)
assert len(tasks) == data['total'],\
"The reported total number of tasks is wrong"
assert len(taskruns) == data['done'],\
"The reported number of done tasks is wrong"
res = self.app.get('/api/app/1/newtask')
data = json.loads(res.data)
print data
# Add a new TaskRun and check again
tr = model.TaskRun(
app_id=1,
task_id=data['id'],
user_id=user.id,
info={'answer': u'annakarenina'}
)
db.session.add(tr)
db.session.commit()
res = self.app.get('/api/app/1/userprogress', follow_redirects=True)
data = json.loads(res.data)
assert len(tasks) == data['total'],\
"The reported total number of tasks is wrong"
assert len(taskruns) + 1 == data['done'],\
"The reported number of done tasks is wrong: %s" %\
len(taskruns)
self.signout()