-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathrest_common.py
More file actions
5100 lines (4602 loc) · 211 KB
/
rest_common.py
File metadata and controls
5100 lines (4602 loc) · 211 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
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pytest
import unittest
import shutil
import sys
import errno
import logging
from time import sleep
from datetime import datetime, timedelta
from roundup.anypy.cgi_ import cgi
from roundup.anypy.datetime_ import utcnow
from roundup.date import Date
from roundup.exceptions import UsageError
from roundup.test.tx_Source_detector import init as tx_Source_init
try:
from datetime import timezone
myutc = timezone.utc
except ImportError:
# python 2
from datetime import tzinfo
ZERO = timedelta(0)
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
myutc = UTC()
from roundup.cgi.exceptions import *
from roundup.hyperdb import HyperdbValueError
from roundup.exceptions import *
from roundup import password, hyperdb
from roundup.rest import RestfulInstance, calculate_etag
from roundup.cgi import client
from roundup.anypy.strings import b2s, s2b, us2u
import random
from roundup.backends.sessions_dbm import OneTimeKeys
from roundup.anypy.dbm_ import whichdb
from .db_test_base import setupTracker
from roundup.test.mocknull import MockNull
from io import BytesIO
import json
from copy import copy
try:
import jwt
skip_jwt = lambda func, *args, **kwargs: func
except ImportError:
from .pytest_patcher import mark_class
jwt = None
skip_jwt = mark_class(pytest.mark.skip(
reason='Skipping JWT tests: jwt library not available'))
if sys.version_info[0] > 2:
skip_on_py2 = lambda func, *args, **kwargs: func
else:
from .pytest_patcher import mark_class
skip_on_py2 =mark_class(pytest.mark.skip(
reason='Skipping test on Python 2'))
NEEDS_INSTANCE = 1
class TestCase():
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog):
self._caplog = caplog
backend = None
url_pfx = 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/'
def setUp(self):
from packaging import version
self.dirname = '_test_rest'
# set up and open a tracker
# Set optimize=True as code under test (Client.main()::determine_user)
# will close and re-open the database on user changes. This wipes
# out additions to the schema needed for testing.
self.instance = setupTracker(self.dirname, self.backend, optimize=True)
# open the database
self.db = self.instance.open('admin')
# Create the Otk db.
# This allows a test later on to open the existing db and
# set a class attribute to test the open retry loop
# just as though this process was using a pre-existing db
# rather then the new one we create.
otk = OneTimeKeys(self.db)
otk.set('key', key="value")
# Get user id (user4 maybe). Used later to get data from db.
self.joeid = self.db.user.create(
username='joe',
password=password.Password('random'),
address='random@home.org',
realname='Joe Random',
roles='User'
)
self.db.user.set('1', address="admin@admin.com")
self.db.user.set('2', address="anon@admin.com")
# set up some more stuff for testing
self.db.msg.create(
author="1",
date=Date(),
summary="stuff",
content="abcdefghi\njklmnop",
type="text/markdown"
)
self.db.msg.create(
author="1",
date=Date(),
summary="stuff",
content="abcdefghi\njklmnop",
)
self.db.file.create(
name="afile",
content="PNG\x01abcdefghi\njklmnop",
type="image/png"
)
self.db.commit()
self.db.close()
self.db = self.instance.open('joe')
# Allow joe to retire
p = self.db.security.addPermission(name='Retire', klass='issue')
self.db.security.addPermissionToRole('User', p)
# add set of roles for testing jwt's.
self.db.security.addRole(name="User:email",
description="allow email by jwt")
# allow the jwt to access everybody's email addresses.
# this makes it easier to differentiate between User and
# User:email roles by accessing the /rest/data/user
# endpoint
jwt_perms = self.db.security.addPermission(
name='View',
klass='user',
properties=('id', 'realname', 'address', 'username'),
description="Allow jwt access to email",
props_only=False)
self.db.security.addPermissionToRole("User:email", jwt_perms)
self.db.security.addPermissionToRole("User:email", "Rest Access")
# add set of roles for testing jwt's.
# this is like the user:email role, but it missing access to the rest endpoint.
self.db.security.addRole(name="User:emailnorest",
description="allow email by jwt")
jwt_perms = self.db.security.addPermission(
name='View',
klass='user',
properties=('id', 'realname', 'address', 'username'),
description="Allow jwt access to email but forget to allow rest",
props_only=False)
self.db.security.addPermissionToRole("User:emailnorest", jwt_perms)
if jwt:
# must be 32 chars in length minimum (I think this is at least
# 256 bits of data)
self.old_secret = "TestingTheJwtSecretTestingTheJwtSecret"
self.new_secret = "TestingTheNEW JwtSecretTestingTheNEWJwtSecret"
self.db.config['WEB_JWT_SECRET'] = self.old_secret
# generate all timestamps in UTC.
base_datetime = datetime(1970, 1, 1, tzinfo=myutc)
# A UTC timestamp for now.
dt = datetime.now(myutc)
now_ts = int((dt - base_datetime).total_seconds())
# one good for a minute
dt = dt + timedelta(seconds=60)
plus1min_ts = int((dt - base_datetime).total_seconds())
# one that expired a minute ago
dt = dt - timedelta(seconds=120)
expired_ts = int((dt - base_datetime).total_seconds())
# claims match what cgi/client.py::determine_user
# is looking for
claim = {'sub': self.db.getuid(),
'iss': self.db.config.TRACKER_WEB,
'aud': self.db.config.TRACKER_WEB,
'roles': ['User'],
'iat': now_ts,
'exp': plus1min_ts}
# in version 2.0.0 and newer jwt.encode returns string
# not bytestring. So we have to skip b2s conversion
if version.parse(jwt.__version__) >= version.parse('2.0.0'):
tostr = lambda x: x
else:
tostr = b2s
self.jwt = {}
self.claim = {}
# generate invalid claim with expired timestamp
self.claim['expired'] = copy(claim)
self.claim['expired']['exp'] = expired_ts
self.jwt['expired'] = tostr(jwt.encode(
self.claim['expired'], self.old_secret,
algorithm='HS256'))
# generate valid claim with user role
self.claim['user'] = copy(claim)
self.claim['user']['exp'] = plus1min_ts
self.jwt['user'] = tostr(jwt.encode(
self.claim['user'], self.old_secret,
algorithm='HS256'))
# generate valid claim with user role and new secret
self.claim['user_new_secret'] = copy(claim)
self.claim['user_new_secret']['exp'] = plus1min_ts
self.jwt['user_new_secret'] = tostr(jwt.encode(
self.claim['user'], self.new_secret,
algorithm='HS256'))
# generate invalid claim bad issuer
self.claim['badiss'] = copy(claim)
self.claim['badiss']['iss'] = "http://someissuer/bugs"
self.jwt['badiss'] = tostr(jwt.encode(
self.claim['badiss'], self.old_secret,
algorithm='HS256'))
# generate invalid claim bad aud(ience)
self.claim['badaud'] = copy(claim)
self.claim['badaud']['aud'] = "http://someaudience/bugs"
self.jwt['badaud'] = tostr(jwt.encode(
self.claim['badaud'], self.old_secret,
algorithm='HS256'))
# generate invalid claim bad sub(ject)
self.claim['badsub'] = copy(claim)
self.claim['badsub']['sub'] = str("99")
self.jwt['badsub'] = tostr(
jwt.encode(self.claim['badsub'], self.old_secret,
algorithm='HS256'))
# generate invalid claim bad roles
self.claim['badroles'] = copy(claim)
self.claim['badroles']['roles'] = ["badrole1", "badrole2"]
self.jwt['badroles'] = tostr(jwt.encode(
self.claim['badroles'], self.old_secret,
algorithm='HS256'))
# generate valid claim with limited user:email role
self.claim['user:email'] = copy(claim)
self.claim['user:email']['roles'] = ["user:email"]
self.jwt['user:email'] = tostr(jwt.encode(
self.claim['user:email'], self.old_secret,
algorithm='HS256'))
# generate valid claim with limited user:emailnorest role
self.claim['user:emailnorest'] = copy(claim)
self.claim['user:emailnorest']['roles'] = ["user:emailnorest"]
self.jwt['user:emailnorest'] = tostr(jwt.encode(
self.claim['user:emailnorest'], self.old_secret,
algorithm='HS256'))
self.db.tx_Source = 'web'
self.db.issue.addprop(tx_Source=hyperdb.String())
self.db.issue.addprop(anint=hyperdb.Integer())
self.db.issue.addprop(afloat=hyperdb.Number())
self.db.issue.addprop(abool=hyperdb.Boolean())
self.db.issue.addprop(requireme=hyperdb.String(required=True))
self.db.user.addprop(issue=hyperdb.Link('issue'))
self.db.msg.addprop(tx_Source=hyperdb.String())
self.db.post_init()
tx_Source_init(self.db)
self.client_env = {
'PATH_INFO': 'http://localhost/rounduptest/rest/',
'HTTP_HOST': 'localhost',
'TRACKER_NAME': 'rounduptest',
'HTTP_ORIGIN': 'http://tracker.example'
}
self.dummy_client = client.Client(self.instance, MockNull(),
self.client_env,
cgi.FieldStorage(), None)
self.dummy_client.request.headers.get = self.get_header
self.dummy_client.db = self.db
self.empty_form = cgi.FieldStorage()
# under python2 invoking:
# python2 -m pytest --durations=20
# loads the form with:
# FieldStorage(None, None, [MiniFieldStorage('--durations', '2')])
# Invoking it as: python2 -m pytest -v --durations=20
# results in an empty list. In any case, force it to be empty.
self.empty_form.list = []
self.terse_form = cgi.FieldStorage()
self.terse_form.list = [
cgi.MiniFieldStorage('@verbose', '0'),
]
self.server = RestfulInstance(self.dummy_client, self.db)
self.db.Otk = self.db.getOTKManager()
self.db.config['WEB_SECRET_KEY'] = "XyzzykrnKm45Sd"
def tearDown(self):
self.db.close()
try:
shutil.rmtree(self.dirname)
except OSError as error:
if error.errno not in (errno.ENOENT, errno.ESRCH):
raise
def get_header(self, header, not_found=None):
try:
return self.headers[header.lower()]
except (AttributeError, KeyError, TypeError):
if header.upper() in self.client_env:
return self.client_env[header.upper()]
return not_found
def create_stati(self):
try:
self.db.status.create(name='open', order='9')
except ValueError:
pass
try:
self.db.status.create(name='closed', order='91')
except ValueError:
pass
try:
self.db.priority.create(name='normal')
except ValueError:
pass
try:
self.db.priority.create(name='critical')
except ValueError:
pass
def create_sampledata(self, data_max=3):
""" Create sample data common to some test cases
"""
self.create_stati()
self.db.issue.create(
title='foo1',
status=self.db.status.lookup('open'),
priority=self.db.priority.lookup('normal'),
nosy=["1", "2"]
)
issue_open_norm = self.db.issue.create(
title='foo2',
status=self.db.status.lookup('open'),
priority=self.db.priority.lookup('normal'),
assignedto="3"
)
issue_open_crit = self.db.issue.create(
title='foo5',
status=self.db.status.lookup('open'),
priority=self.db.priority.lookup('critical')
)
if data_max > 10:
raise ValueError('data_max must be less than 10')
if data_max == 3:
return
sample_data = [
["foo6", "normal", "closed"],
["foo7", "critical", "open"],
["foo8", "normal", "open"],
["foo9", "critical", "open"],
["foo10", "normal", "closed"],
["foo11", "critical", "open"],
["foo12", "normal", "closed"],
["foo13", "normal", "open"],
]
for title, priority, status in sample_data:
new_issue = self.db.issue.create(
title=title,
status=self.db.status.lookup(status),
priority=self.db.priority.lookup(priority)
)
if int(new_issue) == data_max:
break
def test_no_next_link_on_full_last_page(self):
"""Make sure that there is no next link
on the last page where the total number of entries
is a multiple of the page size.
"""
self.server.client.env.update({'REQUEST_METHOD': 'GET'})
# Retrieve third user of the total of 3.
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@page_index', '3'),
cgi.MiniFieldStorage('@page_size', '1'),
]
results = self.server.get_collection('user', form)
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(len(results['data']['collection']), 1)
self.assertEqual(results['data']['collection'][0]['id'], "3")
self.assertEqual(results['data']['@total_size'], 3)
print(self.dummy_client.additional_headers["X-Count-Total"])
self.assertEqual(
self.dummy_client.additional_headers["X-Count-Total"],
"3"
)
self.assertNotIn('next', results['data']['@links'])
self.dummy_client.additional_headers.clear()
# Retrieve first user of the total of 3.
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@page_index', '1'),
cgi.MiniFieldStorage('@page_size', '1'),
]
results = self.server.get_collection('user', form)
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(len(results['data']['collection']), 1)
self.assertEqual(results['data']['collection'][0]['id'], "1")
self.assertEqual(results['data']['@total_size'], 3)
print(self.dummy_client.additional_headers["X-Count-Total"])
self.assertEqual(
self.dummy_client.additional_headers["X-Count-Total"],
"3"
)
self.assertIn('next', results['data']['@links'])
self.dummy_client.additional_headers.clear()
def testTotal_size(self):
"""Make sure that total_size is properly set if @page_size
is specified.
Also test for the cases:
@page_size >= the max number of retreivable rows.
raises UsageError (and error code 400)
@page_size < max retreivable rows, but
the amount of matching rows is > max retreivable rows.
total_size/X-Count-Total should be -1
no @page_size and limit < total results returns
limit size and -1 for total.
Check:
http response code
length of collection
An expected id at end of collection
@total_size in payload
X-Count-Total in http headers
"""
from roundup.rest import RestfulInstance
self.server.client.env.update({'REQUEST_METHOD': 'GET'})
# Retrieve one user of the total of 3. limit 10M+1
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@page_index', '1'),
cgi.MiniFieldStorage('@page_size', '1'),
]
results = self.server.get_collection('user', form)
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(len(results['data']['collection']), 1)
self.assertEqual(results['data']['collection'][0]['id'], "1")
self.assertEqual(results['data']['@total_size'], 3)
print(self.dummy_client.additional_headers["X-Count-Total"])
self.assertEqual(
self.dummy_client.additional_headers["X-Count-Total"],
"3"
)
self.dummy_client.additional_headers.clear()
# set max number of returned rows
self.stored_max = RestfulInstance.max_response_row_size
RestfulInstance.max_response_row_size = 2
# Retrieve whole class (no @page_*) with max rows restricted.
form = cgi.FieldStorage()
results = self.server.get_collection('user', self.empty_form)
# reset so changes don't affect other tests if any assetion fails.
RestfulInstance.max_response_row_size = self.stored_max
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(len(results['data']['collection']), 2)
self.assertEqual(results['data']['collection'][1]['id'], "2")
self.assertEqual(results['data']['@total_size'], -1)
print(self.dummy_client.additional_headers["X-Count-Total"])
self.assertEqual(
self.dummy_client.additional_headers["X-Count-Total"],
"-1"
)
self.dummy_client.additional_headers.clear()
# Make sure we can access items that are returned
# in rows RestfulInstance.max_response_row_size + 1.
# so can we access item 2
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@page_index', '2'),
cgi.MiniFieldStorage('@page_size', '1'),
]
RestfulInstance.max_response_row_size = 2
results = self.server.get_collection('user', form)
RestfulInstance.max_response_row_size = self.stored_max
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(len(results['data']['collection']), 1)
self.assertEqual(results['data']['collection'][0]['id'], "2")
self.assertEqual(results['data']['@total_size'], -1)
print(self.dummy_client.additional_headers["X-Count-Total"])
self.assertEqual(
self.dummy_client.additional_headers["X-Count-Total"],
"-1"
)
self.dummy_client.additional_headers.clear()
# Same as above, but access item 3
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@page_index', '3'),
cgi.MiniFieldStorage('@page_size', '1'),
]
RestfulInstance.max_response_row_size = 2
results = self.server.get_collection('user', form)
RestfulInstance.max_response_row_size = self.stored_max
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(len(results['data']['collection']), 1)
self.assertEqual(results['data']['collection'][0]['id'], "3")
self.assertEqual(results['data']['@total_size'], 3)
print(self.dummy_client.additional_headers["X-Count-Total"])
self.assertEqual(
self.dummy_client.additional_headers["X-Count-Total"],
"3"
)
self.dummy_client.additional_headers.clear()
# Retrieve one user but max number of rows is set to 2,
# and we retrieve two users from the db.
# So we don't know how many total users there are.
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@page_index', '1'),
cgi.MiniFieldStorage('@page_size', '1'),
]
RestfulInstance.max_response_row_size = 2
results = self.server.get_collection('user', form)
RestfulInstance.max_response_row_size = self.stored_max
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(len(results['data']['collection']), 1)
self.assertEqual(results['data']['collection'][0]['id'], "1")
self.assertEqual(results['data']['@total_size'], -1)
print(self.dummy_client.additional_headers["X-Count-Total"])
self.assertEqual(
self.dummy_client.additional_headers["X-Count-Total"],
"-1"
)
self.dummy_client.additional_headers.clear()
# Set the page size to be >= the max number of rows returned.
# and verify the exception returned.
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@page_index', '2'),
cgi.MiniFieldStorage('@page_size', '2'),
]
RestfulInstance.max_response_row_size = 2
results = self.server.get_collection('user', form)
RestfulInstance.max_response_row_size = self.stored_max
self.assertEqual(self.dummy_client.response_code, 400)
self.assertEqual(results['error']['status'], 400)
self.assertTrue(isinstance(results['error']['msg'], UsageError))
self.assertEqual(results['error']['msg'].args[0],
"Page size 2 must be less than "
"admin limit on query result size: 2.")
self.assertTrue('@total_size' not in results)
self.assertTrue('@data' not in results)
self.assertTrue("X-Count-Total" not in
self.dummy_client.additional_headers)
# reset environment just in case I forgot a reset above.
RestfulInstance.max_response_row_size = self.stored_max
def testGet(self):
"""
Retrieve all three users
obtain data for 'joe'
"""
self.server.client.env.update({'REQUEST_METHOD': 'GET'})
# Retrieve all three users.
results = self.server.get_collection('user', self.empty_form)
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(len(results['data']['collection']), 3)
self.assertEqual(results['data']['@total_size'], 3)
print(self.dummy_client.additional_headers["X-Count-Total"])
self.assertEqual(
self.dummy_client.additional_headers["X-Count-Total"],
"3"
)
# Obtain data for 'joe'.
results = self.server.get_element('user', self.joeid, self.empty_form)
results = results['data']
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(results['attributes']['username'], 'joe')
self.assertEqual(results['attributes']['realname'], 'Joe Random')
# Obtain data for 'joe' via username lookup.
results = self.server.get_element('user', 'joe', self.empty_form)
results = results['data']
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(results['attributes']['username'], 'joe')
self.assertEqual(results['attributes']['realname'], 'Joe Random')
# Obtain data for 'joe' via username lookup (long form).
key = 'username=joe'
results = self.server.get_element('user', key, self.empty_form)
results = results['data']
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(results['attributes']['username'], 'joe')
self.assertEqual(results['attributes']['realname'], 'Joe Random')
# Obtain data for 'joe'.
results = self.server.get_attribute(
'user', self.joeid, 'username', self.empty_form
)
self.assertEqual(self.dummy_client.response_code, 200)
self.assertEqual(results['data']['data'], 'joe')
def testGetTransitive(self):
"""
Retrieve all issues with an 'o' in status
sort by status.name (not order)
"""
base_path = self.db.config['TRACKER_WEB'] + 'rest/data/'
# self.maxDiff=None
self.create_sampledata()
self.db.issue.set('2', status=self.db.status.lookup('closed'))
self.db.issue.set('3', status=self.db.status.lookup('chatting'))
expected = {'data':
{'@total_size': 2,
'collection': [
{'id': '2',
'link': base_path + 'issue/2',
'assignedto.issue': None,
'status':
{'id': '10',
'link': base_path + 'status/10'
}
},
{'id': '1',
'link': base_path + 'issue/1',
'assignedto.issue': None,
'status':
{'id': '9',
'link': base_path + 'status/9'
}
},
]}
}
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('status.name', 'o'),
cgi.MiniFieldStorage('@fields', 'status,assignedto.issue'),
cgi.MiniFieldStorage('@sort', 'status.name'),
]
results = self.server.get_collection('issue', form)
self.assertDictEqual(expected, results)
def testGetBadTransitive(self):
"""
Mess up the names of various properties and make sure we get a 400
and a somewhat useful error message.
"""
base_path = self.db.config['TRACKER_WEB'] + 'rest/data/'
# self.maxDiff=None
self.create_sampledata()
self.db.issue.set('2', status=self.db.status.lookup('closed'))
self.db.issue.set('3', status=self.db.status.lookup('chatting'))
expected = [
{'error': {'msg': KeyError('Unknown property: assignedto.isse',),
'status': 400}},
{'error': {'msg': KeyError('Unknown property: stat',),
'status': 400}},
{'error': {'msg': KeyError('Unknown property: status.nam',),
'status': 400}},
]
## test invalid transitive property in @fields
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('status.name', 'o'),
cgi.MiniFieldStorage('@fields', 'status,assignedto.isse'),
cgi.MiniFieldStorage('@sort', 'status.name'),
]
results = self.server.get_collection('issue', form)
self.assertEqual(self.dummy_client.response_code, 400)
self.assertEqual(repr(expected[0]['error']['msg']),
repr(results['error']['msg']))
self.assertEqual(expected[0]['error']['status'],
results['error']['status'])
## test invalid property in @fields
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('status.name', 'o'),
cgi.MiniFieldStorage('@fields', 'stat,assignedto.isuse'),
cgi.MiniFieldStorage('@sort', 'status.name'),
]
results = self.server.get_collection('issue', form)
self.assertEqual(self.dummy_client.response_code, 400)
self.assertEqual(repr(expected[1]['error']['msg']),
repr(results['error']['msg']))
self.assertEqual(expected[1]['error']['status'],
results['error']['status'])
## test invalid transitive property in filter TODO
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('status.nam', 'o'),
cgi.MiniFieldStorage('@fields', 'status,assignedto.isuse'),
cgi.MiniFieldStorage('@sort', 'status.name'),
]
results = self.server.get_collection('issue', form)
# is currently 403 not 400
self.assertEqual(self.dummy_client.response_code, 400)
self.assertEqual(repr(expected[2]['error']['msg']),
repr(results['error']['msg']))
self.assertEqual(expected[2]['error']['status'],
results['error']['status'])
def testGetExactMatch(self):
""" Retrieve all issues with an exact title
"""
base_path = self.db.config['TRACKER_WEB'] + 'rest/data/'
# self.maxDiff=None
self.create_sampledata()
self.db.issue.set('2', title='This is an exact match')
self.db.issue.set('3', title='This is an exact match')
self.db.issue.set('1', title='This is AN exact match')
expected = {'data':
{'@total_size': 2,
'collection': [
{'id': '2',
'link': base_path + 'issue/2',
},
{'id': '3',
'link': base_path + 'issue/3',
},
]}
}
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('title:', 'This is an exact match'),
cgi.MiniFieldStorage('@sort', 'status.name'),
]
results = self.server.get_collection('issue', form)
self.assertDictEqual(expected, results)
def testOutputFormat(self):
""" test of @fields and @verbose implementation """
self.maxDiff = 4000
self.create_sampledata()
base_path = self.db.config['TRACKER_WEB'] + 'rest/data/issue/'
# Check formating for issues status=open; @fields and verbose tests
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('status', 'open'),
cgi.MiniFieldStorage('@fields', 'nosy,status,creator'),
cgi.MiniFieldStorage('@verbose', '2')
]
expected = {'data':
{'@total_size': 3,
'collection': [ {
'creator': {'id': '3',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3',
'username': 'joe'},
'status': {'id': '9',
'name': 'open',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status/9'},
'id': '1',
'nosy': [
{'username': 'admin',
'id': '1',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/1'},
{'username': 'anonymous',
'id': '2',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/2'}
],
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1',
'title': 'foo1' },
{ 'creator': {'id': '3',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3',
'username': 'joe'},
'status': {
'id': '9',
'name': 'open',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status/9' },
'id': '2',
'nosy': [
{'username': 'joe',
'id': '3',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3'}
],
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/2',
'title': 'foo2'},
{'creator': {'id': '3',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3',
'username': 'joe'},
'status': {
'id': '9',
'name': 'open',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status/9'},
'id': '3',
'nosy': [],
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3',
'title': 'foo5'}
]}}
results = self.server.get_collection('issue', form)
self.assertDictEqual(expected, results)
# Check formating for issues status=open; @fields and verbose tests
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('status', 'open')
# default cgi.MiniFieldStorage('@verbose', '1')
]
expected={'data':
{'@total_size': 3,
'collection': [
{'id': '1',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1',},
{ 'id': '2',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/2'},
{'id': '3',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3'} ]}}
results = self.server.get_collection('issue', form)
self.assertDictEqual(expected, results)
# Generate failure case, unknown field.
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('status', 'open'),
cgi.MiniFieldStorage('@fields', 'title,foo')
]
expected={'error': {
'msg': UsageError("Failed to find property 'foo' "
"for class issue.",),
'status': 400}}
results = self.server.get_collection('issue', form)
# I tried assertDictEqual but seems it can't handle
# the exception value of 'msg'. So I am using repr to check.
self.assertEqual(repr(sorted(expected['error'])),
repr(sorted(results['error']))
)
# Check formating for issues status=open; @fields and verbose tests
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('status', 'open'),
cgi.MiniFieldStorage('@fields', 'nosy,status,assignedto'),
cgi.MiniFieldStorage('@verbose', '0')
]
expected={'data': {
'@total_size': 3,
'collection': [
{'assignedto': None,
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1',
'status': '9',
'nosy': ['1', '2'],
'id': '1'},
{'assignedto': '3',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/2',
'status': '9',
'nosy': ['3'],
'id': '2'},
{'assignedto': None,
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3',
'status': '9',
'nosy': [],
'id': '3'}]}}
results = self.server.get_collection('issue', form)
print(results)
self.assertDictEqual(expected, results)
# check users
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@fields', 'username,queries,password'),
cgi.MiniFieldStorage('@verbose', '0')
]
# note this is done as user joe, so we only get queries
# and password for joe.
expected = {'data': {'collection': [
{'id': '1',
'username': 'admin',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/1'},
{'id': '2',
'username': 'anonymous',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/2'},
{'password': '[password hidden scheme PBKDF2S5]',
'id': '3',
'queries': [],
'username': 'joe',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3'}],
'@total_size': 3}}
results = self.server.get_collection('user', form)
self.assertDictEqual(expected, results)
## Start testing get_element
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@fields', 'queries,password,creator'),
cgi.MiniFieldStorage('@verbose', '2')
]
expected = {'data': {
'id': '3',
'type': 'user',
'@etag': '',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3',
'attributes': {
'creator': {'id': '1',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/1',
'username': 'admin'},
'password': '[password hidden scheme PBKDF2S5]',
'queries': [],
'username': 'joe'
}
}}
results = self.server.get_element('user', self.joeid, form)
results['data']['@etag'] = '' # etag depends on date, set to empty
self.assertDictEqual(expected,results)
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@fields', 'status:priority'),
cgi.MiniFieldStorage('@verbose', '1')
]
expected = {'data': {
'type': 'issue',
'id': '3',
'attributes': {
'status': {
'id': '9',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status/9'},
'priority': {
'id': '1',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/priority/1'}},
'@etag': '',
'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3'}}
results = self.server.get_element('issue', "3", form)
results['data']['@etag'] = '' # etag depends on date, set to empty
self.assertDictEqual(expected,results)
form = cgi.FieldStorage()
form.list = [
cgi.MiniFieldStorage('@fields', 'status,priority'),
cgi.MiniFieldStorage('@verbose', '0')
]
expected = {'data': {
'type': 'issue',