-
Notifications
You must be signed in to change notification settings - Fork 2k
/
test_datastore.py
1149 lines (989 loc) · 46.7 KB
/
test_datastore.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 unittest
import json
import sqlalchemy
import ckan.plugins as p
import ckan.lib.create_test_data as ctd
import ckan.model as model
import ckan.tests as tests
import ckanext.datastore.db as db
import pprint
import datetime
def extract(d, keys):
return dict((k, d[k]) for k in keys if k in d)
class TestTypeGetters(unittest.TestCase):
def test_list(self):
assert db._get_list(None) == None
assert db._get_list([]) == []
assert db._get_list('') == []
assert db._get_list('foo') == ['foo']
assert db._get_list('foo, bar') == ['foo', 'bar']
assert db._get_list('"foo", "bar"') == ['foo', 'bar']
assert db._get_list(u'foo, bar') == ['foo', 'bar']
assert db._get_list(['foo', 'bar']) == ['foo', 'bar']
assert db._get_list([u'foo', u'bar']) == ['foo', 'bar']
assert db._get_list(['foo', ['bar', 'baz']]) == ['foo', ['bar', 'baz']]
def test_bool(self):
assert db._get_bool(None) == False
assert db._get_bool(False) == False
assert db._get_bool(True) == True
assert db._get_bool('', True) == True
assert db._get_bool('', False) == False
assert db._get_bool('True') == True
assert db._get_bool('False') == False
assert db._get_bool('1') == True
assert db._get_bool('0') == False
assert db._get_bool('on') == True
assert db._get_bool('off') == False
class TestDatastoreCreate(tests.WsgiAppCase):
sysadmin_user = None
normal_user = None
p.load('datastore')
@classmethod
def setup_class(cls):
ctd.CreateTestData.create()
cls.sysadmin_user = model.User.get('testsysadmin')
cls.normal_user = model.User.get('annafan')
@classmethod
def teardown_class(cls):
model.repo.rebuild_db()
def test_create_requires_auth(self):
resource = model.Package.get('annakarenina').resources[0]
data = {
'resource_id': resource.id
}
postparams = '%s=1' % json.dumps(data)
res = self.app.post('/api/action/datastore_create', params=postparams,
status=403)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_create_empty_fails(self):
postparams = '%s=1' % json.dumps({})
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_create_invalid_field_type(self):
resource = model.Package.get('annakarenina').resources[0]
data = {
'resource_id': resource.id,
'fields': [{'id': 'book', 'type': 'INVALID'},
{'id': 'author', 'type': 'INVALID'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_create_invalid_field_name(self):
resource = model.Package.get('annakarenina').resources[0]
data = {
'resource_id': resource.id,
'fields': [{'id': '_book', 'type': 'text'},
{'id': '_author', 'type': 'text'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
data = {
'resource_id': resource.id,
'fields': [{'id': '"book"', 'type': 'text'},
{'id': '"author', 'type': 'text'}]
}
postparams = '%s=1' % json.dumps(data)
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_create_invalid_record_field(self):
resource = model.Package.get('annakarenina').resources[0]
data = {
'resource_id': resource.id,
'fields': [{'id': 'book', 'type': 'text'},
{'id': 'author', 'type': 'text'}],
'records': [{'book': 'annakarenina', 'author': 'tolstoy'},
{'book': 'warandpeace', 'published': '1869'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_bad_records(self):
resource = model.Package.get('annakarenina').resources[0]
data = {
'resource_id': resource.id,
'fields': [{'id': 'book', 'type': 'text'},
{'id': 'author', 'type': 'text'}],
'records': ['bad'] # treat author as null
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
resource = model.Package.get('annakarenina').resources[0]
data = {
'resource_id': resource.id,
'fields': [{'id': 'book', 'type': 'text'},
{'id': 'author', 'type': 'text'}],
'records': [{'book': 'annakarenina', 'author': 'tolstoy'},
[],
{'book': 'warandpeace'}] # treat author as null
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_create_basic(self):
resource = model.Package.get('annakarenina').resources[0]
alias = u'books1'
data = {
'resource_id': resource.id,
'alias': alias,
'fields': [{'id': 'book', 'type': 'text'},
{'id': 'author', 'type': '_json'}],
'primary_key': 'book, author',
'indexes': ['author'],
'records': [
{'book': 'crime', 'author': ['tolstoy', 'dostoevsky']},
{'book': 'annakarenina', 'author': ['tolstoy', 'putin']},
{'book': 'warandpeace'}] # treat author as null
}
### Firstly test to see if resource things it has datastore table
postparams = '%s=1' % json.dumps({'id': resource.id})
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/resource_show', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['result']['datastore_active'] == False
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
assert res_dict['result']['resource_id'] == data['resource_id']
assert res_dict['result']['fields'] == data['fields']
assert res_dict['result']['records'] == data['records']
c = model.Session.connection()
results = c.execute('select * from "{0}"'.format(resource.id))
assert results.rowcount == 3
for i, row in enumerate(results):
assert data['records'][i].get('book') == row['book']
assert data['records'][i].get('author') == (
json.loads(row['author'][0]) if row['author'] else None)
results = c.execute('''
select * from "{0}" where _full_text @@ to_tsquery('warandpeace')
'''.format(resource.id))
assert results.rowcount == 1, results.rowcount
results = c.execute('''
select * from "{0}" where _full_text @@ to_tsquery('tolstoy')
'''.format(resource.id))
assert results.rowcount == 2
model.Session.remove()
# check alias for resource
c = model.Session.connection()
results = [row for row in c.execute('select * from "{0}"'.format(resource.id))]
results_alias = [row for row in c.execute('select * from "{0}"'.format(alias))]
assert results == results_alias
sql = ("select * from _table_metadata "
"where alias_of='{}' and name='{}'").format(resource.id, alias)
results = c.execute(sql)
assert results.rowcount == 1
# check to test to see if resource now has a datastore table
postparams = '%s=1' % json.dumps({'id': resource.id})
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/resource_show', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['result']['datastore_active'] == True
####### insert again simple
data2 = {
'resource_id': resource.id,
'records': [{'book': 'hagji murat', 'author': ['tolstoy']}]
}
postparams = '%s=1' % json.dumps(data2)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
c = model.Session.connection()
results = c.execute('select * from "{0}"'.format(resource.id))
assert results.rowcount == 4
all_data = data['records'] + data2['records']
for i, row in enumerate(results):
assert all_data[i].get('book') == row['book']
assert all_data[i].get('author') == (
json.loads(row['author'][0]) if row['author'] else None)
results = c.execute('''
select * from "{0}" where _full_text @@ 'tolstoy'
'''.format(resource.id))
assert results.rowcount == 3
model.Session.remove()
####### insert again extra field
data3 = {
'resource_id': resource.id,
'records': [{'book': 'crime and punsihment',
'author': ['dostoevsky'], 'rating': 'good'}],
'indexes': ['rating']
}
postparams = '%s=1' % json.dumps(data3)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
c = model.Session.connection()
results = c.execute('select * from "{0}"'.format(resource.id))
assert results.rowcount == 5
all_data = data['records'] + data2['records'] + data3['records']
for i, row in enumerate(results):
assert all_data[i].get('book') == row['book'], (i, all_data[i].get('book'), row['book'])
assert all_data[i].get('author') == (json.loads(row['author'][0]) if row['author'] else None)
results = c.execute('''select * from "{0}" where _full_text @@ to_tsquery('dostoevsky') '''.format(resource.id))
assert results.rowcount == 2
model.Session.remove()
####### insert again which will fail because of unique book name
data4 = {
'resource_id': resource.id,
'records': [{'book': 'warandpeace'}],
'primary_key': 'book'
}
postparams = '%s=1' % json.dumps(data4)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
assert 'constraints' in res_dict['error']
####### insert again which should not fail because constraint is removed
data5 = {
'resource_id': resource.id,
'records': [{'book': 'warandpeace'}],
'primary_key': ''
}
postparams = '%s=1' % json.dumps(data5)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, expect_errors=True)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
def test_guess_types(self):
resource = model.Package.get('annakarenina').resources[1]
data = {
'resource_id': resource.id,
'fields': [{'id': 'author', 'type': '_json'},
{'id': 'count'},
{'id': 'book'},
{'id': 'date'}],
'records': [{'book': 'annakarenina', 'author': 'tolstoy',
'count': 1, 'date': '2005-12-01', 'count2': 2},
{'book': 'crime', 'author': ['tolstoy', 'dostoevsky']},
{'book': 'warandpeace'}] # treat author as null
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
c = model.Session.connection()
results = c.execute('''select * from "{0}" '''.format(resource.id))
types = [db._pg_types[field[1]] for field in results.cursor.description]
assert types == [u'int4', u'tsvector', u'_json', u'int4',
u'text', u'timestamp', u'int4'], types
assert results.rowcount == 3
for i, row in enumerate(results):
assert data['records'][i].get('book') == row['book']
assert data['records'][i].get('author') == (
json.loads(row['author'][0]) if row['author'] else None)
model.Session.remove()
### extend types
data = {
'resource_id': resource.id,
'fields': [{'id': 'author', 'type': 'text'},
{'id': 'count'},
{'id': 'book'},
{'id': 'date'},
{'id': 'count2'},
{'id': 'extra', 'type':'text'},
{'id': 'date2'},
],
'records': [{'book': 'annakarenina', 'author': 'tolstoy',
'count': 1, 'date': '2005-12-01', 'count2': 2,
'nested': [1, 2], 'date2': '2005-12-01'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
c = model.Session.connection()
results = c.execute('''select * from "{0}" '''.format(resource.id))
types = [db._pg_types[field[1]] for field in results.cursor.description]
assert types == [u'int4', # id
u'tsvector', # fulltext
u'_json', # author
u'int4', # count
u'text', # book
u'timestamp', # date
u'int4', # count2
u'text', # extra
u'timestamp', # date2
u'_json', # count3
], types
### fields resupplied in wrong order
data = {
'resource_id': resource.id,
'fields': [{'id': 'author', 'type': 'text'},
{'id': 'count'},
{'id': 'date'}, # date and book in wrong order
{'id': 'book'},
{'id': 'count2'},
{'id': 'extra', 'type':'text'},
{'id': 'date2'},
],
'records': [{'book': 'annakarenina', 'author': 'tolstoy',
'count': 1, 'date': '2005-12-01', 'count2': 2,
'count3': 432, 'date2': '2005-12-01'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
class TestDatastoreUpsert(tests.WsgiAppCase):
sysadmin_user = None
normal_user = None
p.load('datastore')
@classmethod
def setup_class(cls):
p.load('datastore')
ctd.CreateTestData.create()
cls.sysadmin_user = model.User.get('testsysadmin')
cls.normal_user = model.User.get('annafan')
resource = model.Package.get('annakarenina').resources[0]
cls.data = {
'resource_id': resource.id,
'fields': [{'id': u'b\xfck', 'type': 'text'},
{'id': 'author', 'type': 'text'},
{'id': 'published'}],
'primary_key': u'b\xfck',
'records': [{u'b\xfck': 'annakarenina', 'author': 'tolstoy',
'published': '2005-03-01', 'nested': ['b', {'moo': 'moo'}]},
{u'b\xfck': 'warandpeace', 'author': 'tolstoy',
'nested': {'a':'b'}}
]
}
postparams = '%s=1' % json.dumps(cls.data)
auth = {'Authorization': str(cls.sysadmin_user.apikey)}
res = cls.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
@classmethod
def teardown_class(cls):
model.repo.rebuild_db()
def test_upsert_requires_auth(self):
data = {
'resource_id': self.data['resource_id']
}
postparams = '%s=1' % json.dumps(data)
res = self.app.post('/api/action/datastore_upsert', params=postparams,
status=403)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_upsert_empty_fails(self):
postparams = '%s=1' % json.dumps({})
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_upsert', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_insert(self):
data = {
'resource_id': self.data['resource_id'],
'method': 'insert',
'records': [{u'b\xfck': 'hitchhikers guide to the galaxy', 'author': 'tolstoy'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_upsert', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
c = model.Session.connection()
results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
assert results.rowcount == 3
def test_update(self):
c = model.Session.connection()
results = c.execute('select 1 from "{0}"'.format(self.data['resource_id']))
assert results.rowcount == 3
model.Session.remove()
hhguide = u"hitchhikers guide to the galaxy"
data = {
'resource_id': self.data['resource_id'],
'method': 'update',
'records': [{u'b\xfck': hhguide, 'author': 'adams'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_upsert', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
c = model.Session.connection()
results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
assert results.rowcount == 3
records = results.fetchall()
assert records[2][u'b\xfck'] == hhguide
assert records[2].author == 'adams'
model.Session.remove()
c = model.Session.connection()
results = c.execute("select * from \"{0}\" where author='{1}'".format(self.data['resource_id'], 'adams'))
assert results.rowcount == 1
model.Session.remove()
#update only the publish date
data = {
'resource_id': self.data['resource_id'],
'method': 'update',
'records': [{u'b\xfck': hhguide, 'published': '1979-1-1'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_upsert', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
c = model.Session.connection()
results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
assert results.rowcount == 3
records = results.fetchall()
assert records[2][u'b\xfck'] == hhguide
assert records[2].author == 'adams'
assert records[2].published == datetime.datetime(1979, 1, 1)
model.Session.remove()
def test_update_missing_key(self):
data = {
'resource_id': self.data['resource_id'],
'method': 'update',
'records': [{'author': 'tolkien'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_upsert', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_update_non_existing_key(self):
data = {
'resource_id': self.data['resource_id'],
'method': 'update',
'records': [{u'b\xfck': '', 'author': 'tolkien'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_upsert', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
class TestDatastoreDelete(tests.WsgiAppCase):
sysadmin_user = None
normal_user = None
@classmethod
def setup_class(cls):
p.load('datastore')
ctd.CreateTestData.create()
cls.sysadmin_user = model.User.get('testsysadmin')
cls.normal_user = model.User.get('annafan')
resource = model.Package.get('annakarenina').resources[0]
cls.data = {
'resource_id': resource.id,
'alias': 'books2',
'fields': [{'id': 'book', 'type': 'text'},
{'id': 'author', 'type': 'text'}],
'records': [{'book': 'annakarenina', 'author': 'tolstoy'},
{'book': 'warandpeace', 'author': 'tolstoy'}]
}
@classmethod
def teardown_class(cls):
model.repo.rebuild_db()
def _create(self):
postparams = '%s=1' % json.dumps(self.data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
return res_dict
def _delete(self):
data = {'resource_id': self.data['resource_id']}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_delete', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
assert res_dict['result'] == data
return res_dict
def test_delete_basic(self):
self._create()
self._delete()
resource_id = self.data['resource_id']
c = model.Session.connection()
# alias should be deleted
results = c.execute("select 1 from pg_views where viewname = '{}'".format(self.data['alias']))
assert results.rowcount == 0
try:
# check that data was actually deleted: this should raise a
# ProgrammingError as the table should not exist any more
c.execute('select * from "{0}";'.format(resource_id))
raise Exception("Data not deleted")
except sqlalchemy.exc.ProgrammingError as e:
expected_msg = 'relation "{}" does not exist'.format(resource_id)
assert expected_msg in str(e)
model.Session.remove()
def test_delete_invalid_resource_id(self):
postparams = '%s=1' % json.dumps({'resource_id': 'bad'})
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_delete', params=postparams,
extra_environ=auth, status=404)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_delete_filters(self):
self._create()
resource_id = self.data['resource_id']
# try and delete just the 'warandpeace' row
data = {'resource_id': resource_id,
'filters': {'book': 'warandpeace'}}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_delete', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
c = model.Session.connection()
result = c.execute('select * from "{0}";'.format(resource_id))
results = [r for r in result]
assert len(results) == 1
assert results[0].book == 'annakarenina'
model.Session.remove()
# shouldn't delete anything
data = {'resource_id': resource_id,
'filters': {'book': 'annakarenina', 'author': 'bad'}}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_delete', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
c = model.Session.connection()
result = c.execute('select * from "{0}";'.format(resource_id))
results = [r for r in result]
assert len(results) == 1
assert results[0].book == 'annakarenina'
model.Session.remove()
# delete the 'annakarenina' row
data = {'resource_id': resource_id,
'filters': {'book': 'annakarenina', 'author': 'tolstoy'}}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_delete', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
c = model.Session.connection()
result = c.execute('select * from "{0}";'.format(resource_id))
results = [r for r in result]
assert len(results) == 0
model.Session.remove()
self._delete()
class TestDatastoreSearch(tests.WsgiAppCase):
sysadmin_user = None
normal_user = None
@classmethod
def setup_class(cls):
p.load('datastore')
ctd.CreateTestData.create()
cls.sysadmin_user = model.User.get('testsysadmin')
cls.normal_user = model.User.get('annafan')
resource = model.Package.get('annakarenina').resources[0]
cls.data = {
'resource_id': resource.id,
'alias': 'books3',
'fields': [{'id': u'b\xfck', 'type': 'text'},
{'id': 'author', 'type': 'text'},
{'id': 'published'}],
'records': [{u'b\xfck': 'annakarenina', 'author': 'tolstoy',
'published': '2005-03-01', 'nested': ['b', {'moo': 'moo'}]},
{u'b\xfck': 'warandpeace', 'author': 'tolstoy',
'nested': {'a':'b'}}
]
}
postparams = '%s=1' % json.dumps(cls.data)
auth = {'Authorization': str(cls.sysadmin_user.apikey)}
res = cls.app.post('/api/action/datastore_create', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
cls.expected_records = [{u'published': u'2005-03-01T00:00:00',
u'_id': 1,
u'nested':
[u'b', {u'moo': u'moo'}],
u'b\xfck': u'annakarenina',
u'author': u'tolstoy'},
{u'published': None,
u'_id': 2,
u'nested':
{u'a': u'b'},
u'b\xfck': u'warandpeace',
u'author': u'tolstoy'}]
@classmethod
def teardown_class(cls):
model.repo.rebuild_db()
def test_search_basic(self):
data = {'resource_id': self.data['resource_id']}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == len(self.data['records'])
assert result['records'] == self.expected_records
data = {'resource_id': self.data['alias']}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict_alias = json.loads(res.body)
assert res_dict_alias['result']['records'] == res_dict['result']['records']
def test_search_invalid_field(self):
data = {'resource_id': self.data['resource_id'],
'fields': [{'id': 'bad'}]}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_search_fields(self):
data = {'resource_id': self.data['resource_id'],
'fields': [u'b\xfck']}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == len(self.data['records'])
assert result['records'] == [{u'b\xfck': 'annakarenina'},
{u'b\xfck': 'warandpeace'}], result['records']
data = {'resource_id': self.data['resource_id'],
'fields': u'b\xfck, author'}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == len(self.data['records'])
assert result['records'] == [{u'b\xfck': 'annakarenina', 'author': 'tolstoy'},
{u'b\xfck': 'warandpeace', 'author': 'tolstoy'}], result['records']
def test_search_filters(self):
data = {'resource_id': self.data['resource_id'],
'filters': {u'b\xfck': 'annakarenina'}}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == 1
assert result['records'] == [self.expected_records[0]]
def test_search_sort(self):
data = {'resource_id': self.data['resource_id'],
'sort': u'b\xfck asc, author desc'}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == 2
assert result['records'] == self.expected_records, result['records']
data = {'resource_id': self.data['resource_id'],
'sort': [u'b\xfck desc', '"author" asc']}
postparams = '%s=1' % json.dumps(data)
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == 2
assert result['records'] == self.expected_records[::-1]
def test_search_limit(self):
data = {'resource_id': self.data['resource_id'],
'limit': 1}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == 2
assert result['records'] == [self.expected_records[0]]
def test_search_invalid_limit(self):
data = {'resource_id': self.data['resource_id'],
'limit': 'bad'}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_search_offset(self):
data = {'resource_id': self.data['resource_id'],
'limit': 1,
'offset': 1}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == 2
assert result['records'] == [self.expected_records[1]]
def test_search_invalid_offset(self):
data = {'resource_id': self.data['resource_id'],
'offset': 'bad'}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_search_full_text(self):
data = {'resource_id': self.data['resource_id'],
'q': 'annakarenina'}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == 1
results = [extract(result['records'][0],
[u'_id', u'author', u'b\xfck', u'nested', u'published'])]
assert results == [self.expected_records[0]]
data = {'resource_id': self.data['resource_id'],
'q': 'tolstoy'}
postparams = '%s=1' % json.dumps(data)
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == 2
results = [extract(
record,
[u'_id', u'author', u'b\xfck', u'nested', u'published']
) for record in result['records']]
assert results == self.expected_records, result['records']
expected_fields = [{u'type': u'int4', u'id': u'_id'},
{u'type': u'text', u'id': u'b\xfck'},
{u'type': u'text', u'id': u'author'},
{u'type': u'timestamp', u'id': u'published'},
{u'type': u'_json', u'id': u'nested'},
{u'type': u'float4', u'id': u'rank'}]
for field in expected_fields:
assert field in result['fields'], field
# test multiple word queries (connected with and)
data = {'resource_id': self.data['resource_id'],
'plain': True,
'q': 'tolstoy annakarenina'}
postparams = '%s=1' % json.dumps(data)
res = self.app.post('/api/action/datastore_search', params=postparams,
extra_environ=auth)
res_dict = json.loads(res.body)
assert res_dict['success'] is True
result = res_dict['result']
assert result['total'] == 1
results = [extract(
result['records'][0],
[u'_id', u'author', u'b\xfck', u'nested', u'published']
)]
assert results == [self.expected_records[0]], result['records']
for field in expected_fields:
assert field in result['fields'], field
class TestDatastoreFullTextSearch(tests.WsgiAppCase):
@classmethod
def setup_class(cls):
p.load('datastore')
ctd.CreateTestData.create()
cls.sysadmin_user = model.User.get('testsysadmin')
cls.normal_user = model.User.get('annafan')
resource = model.Package.get('annakarenina').resources[0]
cls.data = dict(
resource_id=resource.id,
fields=[
{'id': 'id'},
{'id': 'date', 'type':'date'},
{'id': 'x'},
{'id': 'y'},
{'id': 'z'},
{'id': 'country'},
{'id': 'title'},
{'id': 'lat'},
{'id': 'lon'}