/
test_action.py
1653 lines (1399 loc) · 70.1 KB
/
test_action.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
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 re
import json
import urllib
from pprint import pprint
from nose.tools import assert_equal, assert_raises
from nose.plugins.skip import SkipTest
from pylons import config
import datetime
import ckan
from ckan.lib.create_test_data import CreateTestData
from ckan.lib.dictization.model_dictize import resource_dictize
import ckan.model as model
import ckan.tests as tests
from ckan.tests import WsgiAppCase
from ckan.tests.functional.api import assert_dicts_equal_ignoring_ordering
from ckan.tests import setup_test_search_index, search_related
from ckan.tests import StatusCodes
from ckan.logic import get_action, NotAuthorized
from ckan.logic.action import get_domain_object
from ckan.tests import TestRoles
import ckan.lib.search as search
from ckan import plugins
from ckan.plugins import SingletonPlugin, implements, IPackageController
class TestAction(WsgiAppCase):
sysadmin_user = None
normal_user = None
@classmethod
def setup_class(cls):
search.clear()
CreateTestData.create()
cls.sysadmin_user = model.User.get('testsysadmin')
cls.normal_user = model.User.get('annafan')
CreateTestData.make_some_vocab_tags()
@classmethod
def teardown_class(cls):
model.repo.rebuild_db()
def _add_basic_package(self, package_name=u'test_package', **kwargs):
package = {
'name': package_name,
'title': u'A Novel By Tolstoy',
'resources': [{
'description': u'Full text.',
'format': u'plain text',
'url': u'http://www.annakarenina.com/download/'
}]
}
package.update(kwargs)
postparams = '%s=1' % json.dumps(package)
res = self.app.post('/api/action/package_create', params=postparams,
extra_environ={'Authorization': 'tester'})
return json.loads(res.body)['result']
def test_01_package_list(self):
res = json.loads(self.app.post('/api/action/package_list',
headers={'content-type': 'application/json'}).body)
assert res['success'] is True
assert len(res['result']) == 2
assert 'warandpeace' in res['result']
assert 'annakarenina' in res['result']
assert res['help'].startswith(
"Return a list of the names of the site's datasets (packages).")
postparams = '%s=1' % json.dumps({'limit': 1})
res = json.loads(self.app.post('/api/action/package_list',
params=postparams).body)
assert res['success'] is True
assert len(res['result']) == 1
assert 'warandpeace' in res['result'] or 'annakarenina' in res['result']
# Test GET request
res = json.loads(self.app.get('/api/action/package_list').body)
assert len(res['result']) == 2
assert 'warandpeace' in res['result']
assert 'annakarenina' in res['result']
def test_01_current_package_list_with_resources(self):
url = '/api/action/current_package_list_with_resources'
postparams = '%s=1' % json.dumps({
'limit': 1,
'offset': 1})
res = json.loads(self.app.post(url, params=postparams).body)
assert res['success']
assert len(res['result']) == 1
postparams = '%s=1' % json.dumps({
'limit': '5'})
res = json.loads(self.app.post(url, params=postparams).body)
assert res['success']
postparams = '%s=1' % json.dumps({
'limit': -2})
res = json.loads(self.app.post(url, params=postparams,
status=StatusCodes.STATUS_409_CONFLICT).body)
assert not res['success']
postparams = '%s=1' % json.dumps({
'offset': 'a'})
res = json.loads(self.app.post(url, params=postparams,
status=StatusCodes.STATUS_409_CONFLICT).body)
assert not res['success']
postparams = '%s=1' % json.dumps({
'limit': 2,
'page': 1})
res = json.loads(self.app.post(url, params=postparams).body)
assert res['success']
assert len(res['result']) == 2
postparams = '%s=1' % json.dumps({
'limit': 1,
'page': 0})
res = json.loads(self.app.post(url,
params=postparams,
status=StatusCodes.STATUS_409_CONFLICT).body)
assert not res['success']
def test_01_package_show(self):
anna_id = model.Package.by_name(u'annakarenina').id
postparams = '%s=1' % json.dumps({'id': anna_id})
res = self.app.post('/api/action/package_show', params=postparams)
res_dict = json.loads(res.body)
assert_equal(res_dict['success'], True)
assert res_dict['help'].startswith(
"Return the metadata of a dataset (package) and its resources.")
pkg = res_dict['result']
assert_equal(pkg['name'], 'annakarenina')
missing_keys = set(('title', 'groups')) - set(pkg.keys())
assert not missing_keys, missing_keys
def test_01_package_show_with_jsonp(self):
anna_id = model.Package.by_name(u'annakarenina').id
postparams = '%s=1' % json.dumps({'id': anna_id})
res = self.app.post('/api/action/package_show?callback=jsoncallback', params=postparams)
assert re.match('jsoncallback\(.*\);', res.body), res
# Unwrap JSONP callback (we want to look at the data).
msg = res.body[len('jsoncallback')+1:-2]
res_dict = json.loads(msg)
assert_equal(res_dict['success'], True)
assert res_dict['help'].startswith(
"Return the metadata of a dataset (package) and its resources.")
pkg = res_dict['result']
assert_equal(pkg['name'], 'annakarenina')
missing_keys = set(('title', 'groups')) - set(pkg.keys())
assert not missing_keys, missing_keys
def test_02_package_autocomplete_match_name(self):
postparams = '%s=1' % json.dumps({'q':'war', 'limit': 5})
res = self.app.post('/api/action/package_autocomplete', params=postparams)
res_obj = json.loads(res.body)
assert_equal(res_obj['success'], True)
pprint(res_obj['result'][0]['name'])
assert_equal(res_obj['result'][0]['name'], 'warandpeace')
assert_equal(res_obj['result'][0]['title'], 'A Wonderful Story')
assert_equal(res_obj['result'][0]['match_field'], 'name')
assert_equal(res_obj['result'][0]['match_displayed'], 'warandpeace')
def test_02_package_autocomplete_match_title(self):
postparams = '%s=1' % json.dumps({'q':'a%20w', 'limit': 5})
res = self.app.post('/api/action/package_autocomplete', params=postparams)
res_obj = json.loads(res.body)
assert_equal(res_obj['success'], True)
pprint(res_obj['result'][0]['name'])
assert_equal(res_obj['result'][0]['name'], 'warandpeace')
assert_equal(res_obj['result'][0]['title'], 'A Wonderful Story')
assert_equal(res_obj['result'][0]['match_field'], 'title')
assert_equal(res_obj['result'][0]['match_displayed'], 'A Wonderful Story (warandpeace)')
def test_03_create_update_package(self):
package = {
'author': None,
'author_email': None,
'extras': [{'key': u'original media','value': u'"book"'}],
'license_id': u'other-open',
'maintainer': None,
'maintainer_email': None,
'name': u'annakareninanew',
'notes': u'Some test now',
'resources': [{'alt_url': u'alt123',
'description': u'Full text.',
'extras': {u'alt_url': u'alt123', u'size': u'123'},
'format': u'plain text',
'hash': u'abc123',
'position': 0,
'url': u'http://www.annakarenina.com/download/'},
{'alt_url': u'alt345',
'description': u'Index of the novel',
'extras': {u'alt_url': u'alt345', u'size': u'345'},
'format': u'JSON',
'hash': u'def456',
'position': 1,
'url': u'http://www.annakarenina.com/index.json'}],
'tags': [{'name': u'russian'}, {'name': u'tolstoy'}],
'title': u'A Novel By Tolstoy',
'url': u'http://www.annakarenina.com',
'version': u'0.7a'
}
wee = json.dumps(package)
postparams = '%s=1' % json.dumps(package)
res = self.app.post('/api/action/package_create', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)})
package_created = json.loads(res.body)['result']
print package_created
package_created['name'] = 'moo'
postparams = '%s=1' % json.dumps(package_created)
res = self.app.post('/api/action/package_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)})
package_updated = json.loads(res.body)['result']
package_updated.pop('revision_id')
package_updated.pop('revision_timestamp')
package_updated.pop('metadata_created')
package_updated.pop('metadata_modified')
package_created.pop('revision_id')
package_created.pop('revision_timestamp')
package_created.pop('metadata_created')
package_created.pop('metadata_modified')
assert package_updated == package_created#, (pformat(json.loads(res.body)), pformat(package_created['result']))
def test_03_create_private_package(self):
# Make an organization, because private datasets must belong to one.
organization = tests.call_action_api(self.app, 'organization_create',
name='test_org',
apikey=self.sysadmin_user.apikey)
# Create a dataset without specifying visibility
package_dict = {
'extras': [{'key': u'original media','value': u'"book"'}],
'license_id': u'other-open',
'maintainer_email': None,
'name': u'annakarenina_vis',
'notes': u'Some test now',
'resources': [{'alt_url': u'alt123',
'description': u'Full text.',
'extras': {u'alt_url': u'alt123', u'size': u'123'},
'format': u'plain text',
'hash': u'abc123',
'position': 0,
'url': u'http://www.annakarenina.com/download/'},
{'alt_url': u'alt345',
'description': u'Index of the novel',
'extras': {u'alt_url': u'alt345', u'size': u'345'},
'format': u'JSON',
'hash': u'def456',
'position': 1,
'url': u'http://www.annakarenina.com/index.json'}],
'tags': [{'name': u'russian'}, {'name': u'tolstoy'}],
'title': u'A Novel By Tolstoy',
'url': u'http://www.annakarenina.com',
'owner_org': organization['id'],
'version': u'0.7a',
}
package_created = tests.call_action_api(self.app, 'package_create',
apikey=self.sysadmin_user.apikey,
**package_dict)
assert package_created['private'] is False
# Create a new one, explicitly saying it is public
package_dict['name'] = u'annakareninanew_vis_public'
package_dict['private'] = False
package_created_public = tests.call_action_api(self.app,
'package_create',
apikey=self.sysadmin_user.apikey,
**package_dict)
assert package_created_public['private'] is False
# Create a new one, explicitly saying it is private
package_dict['name'] = u'annakareninanew_vis_private'
package_dict['private'] = True
package_created_private = tests.call_action_api(self.app,
'package_create',
apikey=self.sysadmin_user.apikey,
**package_dict)
assert package_created_private['private'] is True
def test_18_create_package_not_authorized(self):
# I cannot understand the logic on this one we seem to be user
# tester but no idea how.
raise SkipTest
package = {
'extras': [{'key': u'original media','value': u'"book"'}],
'license_id': u'other-open',
'maintainer': None,
'maintainer_email': None,
'name': u'annakareninanew_not_authorized',
'notes': u'Some test now',
'tags': [{'name': u'russian'}, {'name': u'tolstoy'}],
'title': u'A Novel By Tolstoy',
'url': u'http://www.annakarenina.com',
}
wee = json.dumps(package)
postparams = '%s=1' % json.dumps(package)
res = self.app.post('/api/action/package_create', params=postparams,
status=StatusCodes.STATUS_403_ACCESS_DENIED)
def test_41_create_resource(self):
anna_id = model.Package.by_name(u'annakarenina').id
resource = {'package_id': anna_id, 'url': 'http://new_url'}
api_key = model.User.get('testsysadmin').apikey.encode('utf8')
postparams = '%s=1' % json.dumps(resource)
res = self.app.post('/api/action/resource_create', params=postparams,
extra_environ={'Authorization': api_key })
resource = json.loads(res.body)['result']
assert resource['url'] == 'http://new_url'
def test_42_create_resource_with_error(self):
anna_id = model.Package.by_name(u'annakarenina').id
resource = {'package_id': anna_id, 'url': 'new_url', 'created': 'bad_date'}
api_key = model.User.get('testsysadmin').apikey.encode('utf8')
postparams = '%s=1' % json.dumps(resource)
res = self.app.post('/api/action/resource_create', params=postparams,
extra_environ={'Authorization': api_key},
status=StatusCodes.STATUS_409_CONFLICT)
assert json.loads(res.body)['error'] == {"__type": "Validation Error", "created": ["Date format incorrect"]}
def test_04_user_list(self):
postparams = '%s=1' % json.dumps({})
res = self.app.post('/api/action/user_list', params=postparams)
res_obj = json.loads(res.body)
assert res_obj['help'].startswith(
"Return a list of the site's user accounts.")
assert res_obj['success'] == True
assert len(res_obj['result']) == 7
assert res_obj['result'][0]['name'] == 'annafan'
assert res_obj['result'][0]['about'] == 'I love reading Annakarenina. My site: http://anna.com'
assert not 'apikey' in res_obj['result'][0]
def test_05_user_show(self):
# Anonymous request
postparams = '%s=1' % json.dumps({'id':'annafan'})
res = self.app.post('/api/action/user_show', params=postparams)
res_obj = json.loads(res.body)
assert res_obj['help'].startswith("Return a user account.")
assert res_obj['success'] == True
result = res_obj['result']
assert result['name'] == 'annafan'
assert result['about'] == 'I love reading Annakarenina. My site: http://anna.com'
assert 'activity' in result
assert 'created' in result
assert 'display_name' in result
assert 'number_administered_packages' in result
assert 'number_of_edits' in result
assert not 'apikey' in result
assert not 'reset_key' in result
# Same user can see his api key
res = self.app.post('/api/action/user_show', params=postparams,
extra_environ={'Authorization': str(self.normal_user.apikey)})
res_obj = json.loads(res.body)
result = res_obj['result']
assert result['name'] == 'annafan'
assert 'apikey' in result
assert 'reset_key' in result
# Sysadmin user can see everyone's api key
res = self.app.post('/api/action/user_show', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)})
res_obj = json.loads(res.body)
result = res_obj['result']
assert result['name'] == 'annafan'
assert 'apikey' in result
assert 'reset_key' in result
def test_05_user_show_edits(self):
postparams = '%s=1' % json.dumps({'id':'tester'})
res = self.app.post('/api/action/user_show', params=postparams)
res_obj = json.loads(res.body)
assert res_obj['help'].startswith("Return a user account.")
assert res_obj['success'] == True
result = res_obj['result']
assert result['name'] == 'tester'
assert_equal(result['about'], None)
assert result['number_of_edits'] >= 1
edit = result['activity'][-1] # first edit chronologically
assert_equal(edit['author'], 'tester')
assert 'timestamp' in edit
assert_equal(edit['state'], 'active')
assert_equal(edit['approved_timestamp'], None)
assert_equal(set(edit['groups']), set(( 'roger', 'david')))
assert_equal(edit['state'], 'active')
assert edit['message'].startswith('Creating test data.')
assert_equal(set(edit['packages']), set(('warandpeace', 'annakarenina')))
assert 'id' in edit
def test_05b_user_show_datasets(self):
postparams = '%s=1' % json.dumps({'id':'annafan'})
res = self.app.post('/api/action/user_show', params=postparams)
res_obj = json.loads(res.body)
result = res_obj['result']
datasets = result['datasets']
assert_equal(len(datasets), 1)
dataset = result['datasets'][0]
assert_equal(dataset['name'], u'annakarenina')
def test_10_user_create_parameters_missing(self):
user_dict = {}
postparams = '%s=1' % json.dumps(user_dict)
res = self.app.post('/api/action/user_create', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
status=StatusCodes.STATUS_409_CONFLICT)
res_obj = json.loads(res.body)
assert res_obj['error'] == {
'__type': 'Validation Error',
'name': ['Missing value'],
'email': ['Missing value'],
'password': ['Missing value']
}
assert res_obj['help'].startswith("Create a new user.")
assert res_obj['success'] is False
def test_11_user_create_wrong_password(self):
user_dict = {'name':'test_create_from_action_api_2',
'email':'me@test.org',
'password':'tes'} #Too short
postparams = '%s=1' % json.dumps(user_dict)
res = self.app.post('/api/action/user_create', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
status=StatusCodes.STATUS_409_CONFLICT)
res_obj = json.loads(res.body)
assert res_obj['help'].startswith('Create a new user.')
assert res_obj['success'] is False
assert res_obj['error'] == { '__type': 'Validation Error',
'password': ['Your password must be 4 characters or longer']}
def test_12_user_update(self):
normal_user_dict = {'id': self.normal_user.id,
'name': self.normal_user.name,
'fullname': 'Updated normal user full name',
'email': 'me@test.org',
'about':'Updated normal user about'}
sysadmin_user_dict = {'id': self.sysadmin_user.id,
'fullname': 'Updated sysadmin user full name',
'email': 'me@test.org',
'about':'Updated sysadmin user about'}
#Normal users can update themselves
postparams = '%s=1' % json.dumps(normal_user_dict)
res = self.app.post('/api/action/user_update', params=postparams,
extra_environ={'Authorization': str(self.normal_user.apikey)})
res_obj = json.loads(res.body)
assert res_obj['help'].startswith("Update a user account.")
assert res_obj['success'] == True
result = res_obj['result']
assert result['id'] == self.normal_user.id
assert result['name'] == self.normal_user.name
assert result['fullname'] == normal_user_dict['fullname']
assert result['about'] == normal_user_dict['about']
assert 'apikey' in result
assert 'created' in result
assert 'display_name' in result
assert 'number_administered_packages' in result
assert 'number_of_edits' in result
assert not 'password' in result
#Sysadmin users can update themselves
postparams = '%s=1' % json.dumps(sysadmin_user_dict)
res = self.app.post('/api/action/user_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)})
res_obj = json.loads(res.body)
assert res_obj['help'].startswith("Update a user account.")
assert res_obj['success'] == True
result = res_obj['result']
assert result['id'] == self.sysadmin_user.id
assert result['name'] == self.sysadmin_user.name
assert result['fullname'] == sysadmin_user_dict['fullname']
assert result['about'] == sysadmin_user_dict['about']
#Sysadmin users can update all users
postparams = '%s=1' % json.dumps(normal_user_dict)
res = self.app.post('/api/action/user_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)})
res_obj = json.loads(res.body)
assert res_obj['help'].startswith("Update a user account.")
assert res_obj['success'] == True
result = res_obj['result']
assert result['id'] == self.normal_user.id
assert result['name'] == self.normal_user.name
assert result['fullname'] == normal_user_dict['fullname']
assert result['about'] == normal_user_dict['about']
#Normal users can not update other users
postparams = '%s=1' % json.dumps(sysadmin_user_dict)
res = self.app.post('/api/action/user_update', params=postparams,
extra_environ={'Authorization': str(self.normal_user.apikey)},
status=StatusCodes.STATUS_403_ACCESS_DENIED)
res_obj = json.loads(res.body)
assert res_obj['help'].startswith("Update a user account.")
assert res_obj['error'] == {
'__type': 'Authorization Error',
'message': 'Access denied'
}
assert res_obj['success'] is False
def test_12_user_update_errors(self):
test_calls = (
# Empty name
{'user_dict': {'id': self.normal_user.id,
'name':'',
'email':'test@test.com'},
'messages': [('name','Name must be at least 2 characters long')]},
# Invalid characters in name
{'user_dict': {'id': self.normal_user.id,
'name':'i++%',
'email':'test@test.com'},
'messages': [('name','Url must be purely lowercase alphanumeric')]},
# Existing name
{'user_dict': {'id': self.normal_user.id,
'name':self.sysadmin_user.name,
'email':'test@test.com'},
'messages': [('name','That login name is not available')]},
# Missing email
{'user_dict': {'id': self.normal_user.id,
'name':self.normal_user.name},
'messages': [('email','Missing value')]},
)
for test_call in test_calls:
postparams = '%s=1' % json.dumps(test_call['user_dict'])
res = self.app.post('/api/action/user_update', params=postparams,
extra_environ={'Authorization': str(self.normal_user.apikey)},
status=StatusCodes.STATUS_409_CONFLICT)
res_obj = json.loads(res.body)
for expected_message in test_call['messages']:
assert expected_message[1] in ''.join(res_obj['error'][expected_message[0]])
def test_13_group_list(self):
postparams = '%s=1' % json.dumps({})
res = self.app.post('/api/action/group_list', params=postparams)
res_obj = json.loads(res.body)
assert res_obj['result'] == ['david', 'roger']
assert res_obj['success'] is True
assert res_obj['help'].startswith(
"Return a list of the names of the site's groups.")
# Test GET request
res = self.app.get('/api/action/group_list')
res_obj = json.loads(res.body)
assert res_obj['result'] == ['david', 'roger']
#Get all fields
postparams = '%s=1' % json.dumps({'all_fields':True})
res = self.app.post('/api/action/group_list', params=postparams)
res_obj = json.loads(res.body)
assert res_obj['success'] == True
assert res_obj['result'][0]['name'] == 'david'
assert res_obj['result'][0]['display_name'] == 'Dave\'s books'
assert res_obj['result'][0]['packages'] == 2
assert res_obj['result'][1]['name'] == 'roger', res_obj['result'][1]
assert res_obj['result'][1]['packages'] == 1
assert 'id' in res_obj['result'][0]
assert 'revision_id' in res_obj['result'][0]
assert 'state' in res_obj['result'][0]
def test_13_group_list_by_size(self):
postparams = '%s=1' % json.dumps({'order_by': 'packages'})
res = self.app.post('/api/action/group_list',
params=postparams)
res_obj = json.loads(res.body)
assert_equal(sorted(res_obj['result']), ['david','roger'])
def test_13_group_list_by_size_all_fields(self):
postparams = '%s=1' % json.dumps({'order_by': 'packages',
'all_fields': 1})
res = self.app.post('/api/action/group_list',
params=postparams)
res_obj = json.loads(res.body)
result = res_obj['result']
assert_equal(len(result), 2)
assert_equal(result[0]['name'], 'david')
assert_equal(result[0]['packages'], 2)
assert_equal(result[1]['name'], 'roger')
assert_equal(result[1]['packages'], 1)
def test_14_group_show(self):
postparams = '%s=1' % json.dumps({'id':'david'})
res = self.app.post('/api/action/group_show', params=postparams)
res_obj = json.loads(res.body)
assert res_obj['help'].startswith("Return the details of a group.")
assert res_obj['success'] == True
result = res_obj['result']
assert result['name'] == 'david'
assert result['title'] == result['display_name'] == 'Dave\'s books'
assert result['state'] == 'active'
assert 'id' in result
assert 'revision_id' in result
assert len(result['packages']) == 2
#Group not found
postparams = '%s=1' % json.dumps({'id':'not_present_in_the_db'})
res = self.app.post('/api/action/group_show', params=postparams,
status=StatusCodes.STATUS_404_NOT_FOUND)
res_obj = json.loads(res.body)
pprint(res_obj)
assert res_obj['error'] == {
'__type': 'Not Found Error',
'message': 'Not found'
}
assert res_obj['help'].startswith('Return the details of a group.')
assert res_obj['success'] is False
def test_16_user_autocomplete(self):
#Empty query
postparams = '%s=1' % json.dumps({})
res = self.app.post(
'/api/action/user_autocomplete',
params=postparams,
status=StatusCodes.STATUS_409_CONFLICT)
res_obj = json.loads(res.body)
assert res_obj['help'].startswith(
"Return a list of user names that contain a string.")
assert res_obj['success'] is False
#Normal query
postparams = '%s=1' % json.dumps({'q':'joe'})
res = self.app.post('/api/action/user_autocomplete', params=postparams)
res_obj = json.loads(res.body)
assert res_obj['result'][0]['name'] == 'joeadmin'
assert 'id','fullname' in res_obj['result'][0]
def test_17_bad_action(self):
#Empty query
postparams = '%s=1' % json.dumps({})
res = self.app.post('/api/action/bad_action_name', params=postparams,
status=400)
res_obj = json.loads(res.body)
assert_equal(res_obj, u'Bad request - Action name not known: bad_action_name')
def test_19_update_resource(self):
package = {
'name': u'annakareninanew',
'resources': [{
'alt_url': u'alt123',
'description': u'Full text.',
'extras': {u'alt_url': u'alt123', u'size': u'123'},
'format': u'plain text',
'hash': u'abc123',
'position': 0,
'url': u'http://www.annakarenina.com/download/'
}],
'title': u'A Novel By Tolstoy',
'url': u'http://www.annakarenina.com',
}
postparams = '%s=1' % json.dumps(package)
res = self.app.post('/api/action/package_create', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)})
package_created = json.loads(res.body)['result']
resource_created = package_created['resources'][0]
new_resource_url = u'http://www.annakareinanew.com/download/'
resource_created['url'] = new_resource_url
postparams = '%s=1' % json.dumps(resource_created)
res = self.app.post('/api/action/resource_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)})
resource_updated = json.loads(res.body)['result']
assert resource_updated['url'] == new_resource_url, resource_updated
resource_updated.pop('url')
resource_updated.pop('revision_id')
resource_updated.pop('revision_timestamp')
resource_created.pop('url')
resource_created.pop('revision_id')
resource_created.pop('revision_timestamp')
assert_equal(resource_updated, resource_created)
def test_20_task_status_update(self):
package_created = self._add_basic_package(u'test_task_status_update')
task_status = {
'entity_id': package_created['id'],
'entity_type': u'package',
'task_type': u'test_task',
'key': u'test_key',
'value': u'test_value',
'state': u'test_state',
'error': u'test_error',
}
postparams = '%s=1' % json.dumps(task_status)
res = self.app.post(
'/api/action/task_status_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
)
task_status_updated = json.loads(res.body)['result']
task_status_id = task_status_updated.pop('id')
task_status_updated.pop('last_updated')
assert task_status_updated == task_status, (task_status_updated, task_status)
task_status_updated['id'] = task_status_id
task_status_updated['value'] = u'test_value_2'
postparams = '%s=1' % json.dumps(task_status_updated)
res = self.app.post(
'/api/action/task_status_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
)
task_status_updated_2 = json.loads(res.body)['result']
task_status_updated_2.pop('last_updated')
assert task_status_updated_2 == task_status_updated, task_status_updated_2
def test_21_task_status_update_many(self):
package_created = self._add_basic_package(u'test_task_status_update_many')
task_statuses = {
'data': [
{
'entity_id': package_created['id'],
'entity_type': u'package',
'task_type': u'test_task',
'key': u'test_task_1',
'value': u'test_value_1',
'state': u'test_state',
'error': u'test_error'
},
{
'entity_id': package_created['id'],
'entity_type': u'package',
'task_type': u'test_task',
'key': u'test_task_2',
'value': u'test_value_2',
'state': u'test_state',
'error': u'test_error'
}
]
}
postparams = '%s=1' % json.dumps(task_statuses)
res = self.app.post(
'/api/action/task_status_update_many', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
)
task_statuses_updated = json.loads(res.body)['result']['results']
for i in range(len(task_statuses['data'])):
task_status = task_statuses['data'][i]
task_status_updated = task_statuses_updated[i]
task_status_updated.pop('id')
task_status_updated.pop('last_updated')
assert task_status == task_status_updated, (task_status_updated, task_status, i)
def test_22_task_status_normal_user_not_authorized(self):
task_status = {}
postparams = '%s=1' % json.dumps(task_status)
res = self.app.post(
'/api/action/task_status_update', params=postparams,
extra_environ={'Authorization': str(self.normal_user.apikey)},
status=StatusCodes.STATUS_403_ACCESS_DENIED
)
res_obj = json.loads(res.body)
assert res_obj['help'].startswith("Update a task status.")
assert res_obj['success'] is False
assert res_obj['error'] == {'message': 'Access denied', '__type': 'Authorization Error'}
def test_23_task_status_validation(self):
task_status = {}
postparams = '%s=1' % json.dumps(task_status)
res = self.app.post(
'/api/action/task_status_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
status=StatusCodes.STATUS_409_CONFLICT
)
def test_24_task_status_show(self):
package_created = self._add_basic_package(u'test_task_status_show')
task_status = {
'entity_id': package_created['id'],
'entity_type': u'package',
'task_type': u'test_task',
'key': u'test_task_status_show',
'value': u'test_value',
'state': u'test_state',
'error': u'test_error'
}
postparams = '%s=1' % json.dumps(task_status)
res = self.app.post(
'/api/action/task_status_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
)
task_status_updated = json.loads(res.body)['result']
# make sure show works when giving a task status ID
postparams = '%s=1' % json.dumps({'id': task_status_updated['id']})
res = self.app.post(
'/api/action/task_status_show', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
)
task_status_show = json.loads(res.body)['result']
task_status_show.pop('last_updated')
task_status_updated.pop('last_updated')
assert task_status_show == task_status_updated, (task_status_show, task_status_updated)
# make sure show works when giving a (entity_id, task_type, key) tuple
postparams = '%s=1' % json.dumps({
'entity_id': task_status['entity_id'],
'task_type': task_status['task_type'],
'key': task_status['key']
})
res = self.app.post(
'/api/action/task_status_show', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
)
task_status_show = json.loads(res.body)['result']
task_status_show.pop('last_updated')
assert task_status_show == task_status_updated, (task_status_show, task_status_updated)
def test_25_task_status_delete(self):
package_created = self._add_basic_package(u'test_task_status_delete')
task_status = {
'entity_id': package_created['id'],
'entity_type': u'package',
'task_type': u'test_task',
'key': u'test_task_status_delete',
'value': u'test_value',
'state': u'test_state',
'error': u'test_error'
}
postparams = '%s=1' % json.dumps(task_status)
res = self.app.post(
'/api/action/task_status_update', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
)
task_status_updated = json.loads(res.body)['result']
postparams = '%s=1' % json.dumps({'id': task_status_updated['id']})
res = self.app.post(
'/api/action/task_status_delete', params=postparams,
extra_environ={'Authorization': str(self.sysadmin_user.apikey)},
)
task_status_delete = json.loads(res.body)
assert task_status_delete['success'] == True
def test_26_resource_show(self):
pkg = model.Package.get('annakarenina')
resource = pkg.resources[0]
postparams = '%s=1' % json.dumps({'id': resource.id})
res = self.app.post('/api/action/resource_show', params=postparams)
result = json.loads(res.body)['result']
resource_dict = resource_dictize(resource, {'model': model})
assert result == resource_dict, (result, resource_dict)
def test_27_get_site_user_not_authorized(self):
assert_raises(NotAuthorized,
get_action('get_site_user'),
{'model': model}, {})
user = model.User.get('test.ckan.net')
assert not user
site_id = config.get('ckan.site_id')
user = get_action('get_site_user')({'model': model, 'ignore_auth': True}, {})
assert user['name'] == site_id
user = model.User.get(site_id)
assert user
user=get_action('get_site_user')({'model': model, 'ignore_auth': True}, {})
assert user['name'] == site_id
user = model.Session.query(model.User).filter_by(name=site_id).one()
assert user
def test_28_group_package_show(self):
group_id = model.Group.get('david').id
group_packages = get_action('group_package_show')(
{'model': model, 'user': self.normal_user.name, 'ignore_auth': True},
{'id': group_id}
)
assert len(group_packages) == 2, group_packages
group_names = set([g.get('name') for g in group_packages])
assert group_names == set(['annakarenina', 'warandpeace']), group_names
def test_29_group_package_show_pending(self):
context = {'model': model, 'session': model.Session, 'user': self.sysadmin_user.name, 'api_version': 2, 'ignore_auth': True}
group = {
'name': 'test_group_pending_package',
'packages': [{'id': model.Package.get('annakarenina').id}]
}
group = get_action('group_create')(context, group)
pkg = {
'name': 'test_pending_package',
'groups': [{'id': group['id']}]
}
pkg = get_action('package_create')(context, pkg)
# can't seem to add a package with 'pending' state, so update it
pkg['state'] = 'pending'
get_action('package_update')(context, pkg)
group_packages = get_action('group_package_show')(context, {'id': group['id']})
assert len(group_packages) == 2, (len(group_packages), group_packages)
group_names = set([g.get('name') for g in group_packages])
assert group_names == set(['annakarenina', 'test_pending_package']), group_names
get_action('group_delete')(context, group)
get_action('package_delete')(context, pkg)
def test_30_status_show(self):
postparams = '%s=1' % json.dumps({})
res = self.app.post('/api/action/status_show', params=postparams)
status = json.loads(res.body)['result']
assert_equal(status['site_title'], 'CKAN')
assert_equal(status['ckan_version'], ckan.__version__)
assert_equal(status['site_url'], 'http://test.ckan.net')
def test_31_bad_request_format(self):
postparams = '%s=1' % json.dumps('not a dict')
res = self.app.post('/api/action/package_list', params=postparams,
status=400)
assert "Bad request - JSON Error: Request data JSON decoded to 'not a dict' but it needs to be a dictionary." in res.body, res.body
def test_31_bad_request_format_not_json(self):
postparams = '=1'
res = self.app.post('/api/action/package_list', params=postparams,
status=400)
assert "Bad request - Bad request data: Request data JSON decoded to '' but it needs to be a dictionary." in res.body, res.body
def test_32_get_domain_object(self):
anna = model.Package.by_name(u'annakarenina')
assert_equal(get_domain_object(model, anna.name).name, anna.name)
assert_equal(get_domain_object(model, anna.id).name, anna.name)
group = model.Group.by_name(u'david')
assert_equal(get_domain_object(model, group.name).name, group.name)
assert_equal(get_domain_object(model, group.id).name, group.name)
def test_33_roles_show(self):
anna = model.Package.by_name(u'annakarenina')
annafan = model.User.by_name(u'annafan')
postparams = '%s=1' % json.dumps({'domain_object': anna.id})
res = self.app.post('/api/action/roles_show', params=postparams,
extra_environ={'Authorization': str(annafan.apikey)},
status=200)
results = json.loads(res.body)['result']
anna = model.Package.by_name(u'annakarenina')
assert_equal(results['domain_object_id'], anna.id)
assert_equal(results['domain_object_type'], 'Package')
roles = results['roles']
assert len(roles) > 2, results
assert set(roles[0].keys()) > set(('user_id', 'package_id', 'role',
'context', 'user_object_role_id'))
def test_34_roles_show_for_user(self):
anna = model.Package.by_name(u'annakarenina')
annafan = model.User.by_name(u'annafan')
postparams = '%s=1' % json.dumps({'domain_object': anna.id,
'user': 'annafan'})
res = self.app.post('/api/action/roles_show', params=postparams,
extra_environ={'Authorization': str(annafan.apikey)},
status=200)
results = json.loads(res.body)['result']
anna = model.Package.by_name(u'annakarenina')
assert_equal(results['domain_object_id'], anna.id)
assert_equal(results['domain_object_type'], 'Package')
roles = results['roles']
assert_equal(len(roles), 1)
assert set(roles[0].keys()) > set(('user_id', 'package_id', 'role',
'context', 'user_object_role_id'))
def test_35_user_role_update(self):