-
Notifications
You must be signed in to change notification settings - Fork 16
/
test_query.py
593 lines (488 loc) · 24.5 KB
/
test_query.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
from portality import models
from doajtest.fixtures import AccountFixtureFactory, ArticleFixtureFactory, EditorGroupFixtureFactory, \
ApplicationFixtureFactory
from doajtest.helpers import DoajTestCase, deep_sort
from portality.bll.services.query import QueryService, Query
from portality.bll import exceptions
QUERY_ROUTE = {
"query" : {
"article" : {
"auth" : False,
"role" : None,
"query_filters" : ["only_in_doaj"],
"result_filters" : ["public_result_filter"],
"dao" : "portality.models.Article"
}
},
"publisher_query" : {
"journal" : {
"auth" : True,
"role" : "publisher",
"query_filters" : ["owner", "only_in_doaj"],
"result_filters" : ["publisher_result_filter"],
"dao" : "portality.models.Journal"
}
},
"admin_query" : {
"journal" : {
"auth" : True,
"role" : "admin",
"dao" : "portality.models.Journal"
},
"suggestion" : {
"auth" : True,
"role" : "admin",
"dao" : "portality.models.Application"
},
},
"api_query" : {
"article" : {
"auth" : False,
"role" : None,
"query_filters" : ["only_in_doaj", "public_source"],
"result_filters" : ["public_result_filter"],
"dao" : "portality.models.Article",
"page_size" : 1
},
"journal" : {
"auth" : False,
"role" : None,
"query_filters" : ["only_in_doaj", "public_source"],
"dao" : "portality.models.Journal"
},
"suggestion" : {
"auth" : True,
"role" : None,
"query_filters" : ["owner", "private_source"],
"dao" : "portality.models.Suggestion"
}
},
"editor_query" : {
"journal" : {
"auth" : True,
"role" : "editor",
"dao" : "portality.models.Journal"
},
"suggestion" : {
"auth" : True,
"role" : "editor",
"dao" : "portality.models.Application"
}
},
"associate_query": {
"journal": {
"auth": True,
"role": "associate_editor",
"dao": "portality.models.Journal"
},
"suggestion" : {
"auth" : True,
"role" : "associate_editor",
"dao" : "portality.models.Application"
}
}
}
SEARCH_ALL_QUERY_ROUTE = {
"query" : {
"journal" : {
"auth" : False,
"role" : None,
"query_filters" : ["search_all_meta"],
"dao" : "portality.models.Journal"
}
},
"editor_query" : {
"journal" : {
"auth" : True,
"role" : "editor",
"query_filters" : ["search_all_meta"],
"dao" : "portality.models.Journal"
},
"suggestion" : {
"auth" : False,
"role" : "editor",
"query_filters" : ["search_all_meta"],
"dao" : "portality.models.Application"
}
},
"associate_query": {
"journal": {
"auth": False,
"role": "associate_editor",
"query_filters" : ["search_all_meta"],
"dao": "portality.models.Journal"
},
"suggestion" : {
"auth" : False,
"role" : "associate_editor",
"query_filters" : ["search_all_meta"],
"dao" : "portality.models.Application"
}
}
}
QUERY_FILTERS = {
"non_public_fields_validator" : "portality.lib.query_filters.non_public_fields_validator",
# query filters
"only_in_doaj" : "portality.lib.query_filters.only_in_doaj",
"owner" : "portality.lib.query_filters.owner",
"associate" : "portality.lib.query_filters.associate",
"editor" : "portality.lib.query_filters.editor",
# result filters
"public_result_filter" : "portality.lib.query_filters.public_result_filter",
# source filter
"public_source": "portality.lib.query_filters.public_source",
# search on all meta field
"search_all_meta" : "portality.lib.query_filters.search_all_meta",
}
def without_keys(d, keys):
return {x: d[x] for x in d if x not in keys}
class TestQuery(DoajTestCase):
def setUp(self):
super(TestQuery, self).setUp()
self.OLD_QUERY_ROUTE = self.app_test.config.get('QUERY_ROUTE')
self.app_test.config['QUERY_ROUTE'] = QUERY_ROUTE
self.OLD_QUERY_FILTERS = self.app_test.config.get('QUERY_FILTERS')
self.app_test.config['QUERY_FILTERS'] = QUERY_FILTERS
def tearDown(self):
super(TestQuery, self).tearDown()
self.app_test.config['QUERY_ROUTE'] = self.OLD_QUERY_ROUTE
self.app_test.config['QUERY_FILTERS'] = self.OLD_QUERY_FILTERS
def get_application_with_notes(self):
source = ApplicationFixtureFactory.make_application_source()
app = models.Application(**source)
app.add_note("application test", "2015-01-01T00:00:00Z")
app.save()
return app
def get_journal_with_notes(self):
j = models.Journal()
j.set_id("aabbccdd")
j.set_created("2010-01-01T00:00:00Z")
j.set_last_updated("2012-01-01T00:00:00Z")
j.set_last_manual_update("2014-01-01T00:00:00Z")
j.set_seal(True)
j.set_owner("rama")
j.set_editor_group("worldwide")
j.set_editor("eddie")
j.add_contact("rama", "rama@email.com")
j.add_note("testing", "2015-01-01T00:00:00Z")
j.set_bibjson({"title": "test"})
j.save()
return j
def test_01_auth(self):
with self.app_test.test_client() as t_client:
response = t_client.get('/query/journal') # not in the settings above
assert response.status_code == 403, response.status_code
# theoretically should be a 404, but the code checks QUERY_ROUTE config first, so auth checks go first
response = t_client.get('/query/nonexistent')
assert response.status_code == 403, response.status_code
response = t_client.get('/query/article')
assert response.status_code == 200, response.status_code
response = t_client.get('/publisher_query/journal')
assert response.status_code == 403, response.status_code
# These don't work for some reason, the logging in bit with the context doesn't work so they're all 403 Forbidden.
# a publisher logs in
# pub = models.Account(**AccountFixtureFactory.make_publisher_source())
# ctx = self._make_and_push_test_context(acc=pub, path='/publisher_query/journal')
# response = t_client.get('/publisher_query/journal')
# assert response.status_code == 200, response.status_code
#
# response = t_client.get('/admin_query/journal')
# assert response.status_code == 403, response.status_code
# ctx.pop()
# a managing editor logs in
# maned = models.Account(**AccountFixtureFactory.make_managing_editor_source())
# with self._make_and_push_test_context(acc=maned):
# response = t_client.get('/admin_query/journal')
# assert response.status_code == 200, response.status_code
def test_02_query_gen(self):
q = Query()
q.add_must({"term": {"admin.in_doaj": True}})
assert q.as_dict() == {
'track_total_hits' : True,
'query': {
'bool': {
'must': [
{"match_all" : {}},
{'term': {'admin.in_doaj': True}}
]
}
}
},q.as_dict()
q = Query()
q.clear_match_all()
assert q.as_dict() == {'track_total_hits' : True, 'query': {}}, q.as_dict()
q = Query()
q.add_include("last_updated")
assert q.as_dict() == {'track_total_hits' : True, "query": {"match_all": {}},"_source": {"includes": ["last_updated"]}}, q.as_dict()
q = Query()
q.add_include(["last_updated", "id"])
assert sorted(q.as_dict()) == sorted({'track_total_hits' : True, "query": {"match_all": {}},"_source": {"includes": ["last_updated", "id"]}}) or sorted(q.as_dict()) == sorted({"query": {"match_all": {}},"_source": {"include": ["last_updated", "id"]}}), sorted(q.as_dict())
def test_03_query_svc_get_config(self):
qsvc = QueryService()
cfg = qsvc._get_config_for_search('query', 'article', account=None)
assert cfg == {
"auth" : False,
"role" : None,
"query_filters" : ["only_in_doaj"],
"result_filters" : ["public_result_filter"],
"dao" : "portality.models.Article"
}, cfg
with self.assertRaises(exceptions.AuthoriseException):
cfg = qsvc._get_config_for_search('query_nonexistent', 'article', account=None)
with self.assertRaises(exceptions.AuthoriseException):
cfg = qsvc._get_config_for_search('query', 'article_nonexistent', account=None)
with self.assertRaises(exceptions.AuthoriseException): # because account is None and auth is required
cfg = qsvc._get_config_for_search('publisher_query', 'journal', account=None)
pub = models.Account(**AccountFixtureFactory.make_publisher_source())
cfg = qsvc._get_config_for_search('publisher_query', 'journal', account=pub)
assert cfg == {
"auth" : True,
"role" : "publisher",
"query_filters" : ["owner", "only_in_doaj"],
"result_filters" : ["publisher_result_filter"],
"dao" : "portality.models.Journal"
}
with self.assertRaises(exceptions.AuthoriseException): # because account is a publisher and an 'admin' role is needed
cfg = qsvc._get_config_for_search('admin_query', 'journal', account=pub)
maned = models.Account(**AccountFixtureFactory.make_managing_editor_source())
cfg = qsvc._get_config_for_search('admin_query', 'journal', account=maned)
assert cfg == {
"auth" : True,
"role" : "admin",
"dao" : "portality.models.Journal"
}
def test_04_pre_filter_search_query(self):
q = Query()
qsvc = QueryService()
cfg = qsvc._get_config_for_search('query', 'article', account=None)
assert q.as_dict() == {"track_total_hits" : True, "query": {"match_all": {}}}, q.as_dict()
qsvc._pre_filter_search_query(cfg, q)
assert q.as_dict() == {
"track_total_hits": True,
'query': {
'bool': {
'filter': [
{'term': {'admin.in_doaj': True}}
]
}
}
}, q.as_dict()
def test_05_post_filter_search_results(self):
# The config above says that the public_result_filter should run on the results. That should delete admin.publisher_record_id.
# We take a fake result set with the secret info in, run the results filters and expect to have the data cleaned.
# We are testing that the mechanism that runs post filters works, the idea is not to test public_result_filter specifically.
qsvc = QueryService()
cfg = qsvc._get_config_for_search('query', 'article', account=None)
res = {
"hits": {
"hits": [
{ "_type": "article", "_source": { "admin": { "seal": False, "publisher_record_id" : "some_identifier"}, "bibjson": {}}},
{ "_type": "article", "_source": { "admin": { "seal": False, "publisher_record_id" : "some_identifier"}, "bibjson": {}}},
{ "_type": "article", "_source": { "admin": { "seal": False, "publisher_record_id" : "some_identifier"}, "bibjson": {}}}
],
"total": 3
}
}
res = qsvc._post_filter_search_results(cfg, res)
assert res == {
"hits": {
"hits": [
{ "_type": "article", "_source": { "admin": { "seal": False }, "bibjson": {}}},
{ "_type": "article", "_source": { "admin": { "seal": False }, "bibjson": {}}},
{ "_type": "article", "_source": { "admin": { "seal": False }, "bibjson": {}}}
],
"total": 3
}
}
def test_06_post_filter_search_results_unpacked(self):
# The config above says that the public_result_filter should run on the results. That should delete admin.publisher_record_id.
# We take a fake result set with the secret info in, run the results filters and expect to have the data cleaned.
# We are testing that the mechanism that runs post filters works, the idea is not to test public_result_filter specifically.
qsvc = QueryService()
cfg = qsvc._get_config_for_search('query', 'article', account=None)
res1 = { "admin": { "seal": False, "publisher_record_id" : "some_identifier"}, "bibjson": {}}
res2 = { "admin": { "seal": False, "publisher_record_id" : "some_identifier"}, "bibjson": {}}
res3 = { "admin": { "seal": False, "publisher_record_id" : "some_identifier"}, "bibjson": {}}
res1 = qsvc._post_filter_search_results(cfg, res1, unpacked=True)
assert res1 == { "admin": { "seal": False }, "bibjson": {}}
res2 = qsvc._post_filter_search_results(cfg, res2, unpacked=True)
assert res2 == { "admin": { "seal": False }, "bibjson": {}}
res3 = qsvc._post_filter_search_results(cfg, res3, unpacked=True)
assert res1 == { "admin": { "seal": False }, "bibjson": {}}
def test_07_get_query(self):
# q = Query()
raw_query = {
"query" : {
"query_string" : {
"query" : '*',
"default_operator": "AND"
}
},
"from" : 0,
"size" : 100
}
qsvc = QueryService()
cfg = qsvc._get_config_for_search('api_query', 'journal', account=None)
# assert q.as_dict() == {"query": {"match_all": {}}}, q.as_dict()
query = qsvc._get_query(cfg, raw_query)
expected_result = {
'query': {
'bool': {
'must': [
{'query_string': {'query': '*', 'default_operator': 'AND'}}
],
"filter" : [
{'term': {'admin.in_doaj': True}}
]
}
},
'_source': {'includes': ['last_updated', 'admin.ticked', 'created_date', 'admin.seal', 'id', 'bibjson']},
'from': 0, 'size': 100
}
q_but_source = without_keys(query.as_dict(), ['_source'])
r_but_source = without_keys(expected_result, ['_source'])
query_sorted = deep_sort(query.as_dict())
expected_result_sorted = deep_sort(expected_result)
assert query_sorted == expected_result_sorted, query_sorted
def test_08_get_dao_klass(self):
qsvc = QueryService()
cfg = qsvc._get_config_for_search('query', 'article', account=None)
dao_klass = qsvc._get_dao_klass(cfg)
self.assertIs(dao_klass, models.Article)
def test_09_search(self):
# Just bringing it all together. Make 4 articles: 3 in DOAJ, 1 not in DOAJ
# We then expect pre-filters to run on the query, ensuring we only get the 3 in DOAJ articles.
# We also expect the post-filters to run on the results, ensuring non-public data is deleted from the admin section.
qsvc = QueryService()
articles = []
for i in range(0, 3):
articles.append(models.Article(**ArticleFixtureFactory.make_article_source(with_id=False)))
assert articles[-1].publisher_record_id() == 'some_identifier'
articles[-1].save(blocking=True)
articles.append(models.Article(**ArticleFixtureFactory.make_article_source(with_id=False, in_doaj=False)))
articles[-1].save(blocking=True)
res = qsvc.search('query', 'article', {"query": {"match_all": {}}}, account=None, additional_parameters={})
assert res['hits']['total']["value"] == 3, res['hits']['total']["value"]
for hit in res['hits']['hits']:
am = models.Article(**hit)
assert am.publisher_record_id() is None, am.publisher_record_id()
def test_10_scroll(self):
# Just bringing it all together. Make 4 articles: 3 in DOAJ, 1 not in DOAJ
# We then expect pre-filters to run on the query, ensuring we only get the 3 in DOAJ articles.
# We also expect the post-filters to run on the results, ensuring non-public data is deleted from the admin section.
qsvc = QueryService()
articles = []
for i in range(0, 3):
articles.append(models.Article(**ArticleFixtureFactory.make_article_source(with_id=False)))
assert articles[-1].publisher_record_id() == 'some_identifier'
articles[-1].save(blocking=True)
articles.append(models.Article(**ArticleFixtureFactory.make_article_source(with_id=False, in_doaj=False)))
articles[-1].save(blocking=True)
q = {"query": {"match_all": {}}}
for res in qsvc.scroll('api_query', 'article', q, None, None):
am = models.Article(**res)
assert am.publisher_record_id() is None, am.publisher_record_id()
def test_public_query_notes(self):
self.app_test.config['QUERY_ROUTE'] = SEARCH_ALL_QUERY_ROUTE
self.get_journal_with_notes()
qsvc = QueryService()
res = qsvc.search('query', 'journal', {'query': {'query_string': {'query': 'testing',
'default_operator': 'AND'}}, 'size': 0, 'aggs': {'country_publisher':
{'terms': {'field': 'index.country.exact', 'size': 100, 'order': {'_count': 'desc'}}}},
'track_total_hits': True}, account=None, additional_parameters={})
assert res['hits']['total']["value"] == 0, res['hits']['total']["value"]
def test_admin_query_notes(self):
self.get_journal_with_notes()
maned = models.Account(**AccountFixtureFactory.make_managing_editor_source())
maned.save(blocking=True)
qsvc = QueryService()
res = qsvc.search('admin_query', 'journal', {'query': {'query_string': {'query': 'testing',
'default_operator': 'AND'}}, 'size': 0, 'aggs': {'country_publisher':
{'terms': {'field': 'index.country.exact', 'size': 100, 'order': {'_count': 'desc'}}}},
'track_total_hits': True}, account=maned, additional_parameters={})
assert res['hits']['total']["value"] == 1, res['hits']['total']["value"]
def test_editor_query_notes(self):
self.app_test.config['QUERY_ROUTE'] = SEARCH_ALL_QUERY_ROUTE
self.get_journal_with_notes()
editor = models.Account(**AccountFixtureFactory.make_editor_source())
editor.save(blocking=True)
eg_source = EditorGroupFixtureFactory.make_editor_group_source(maned=editor.id)
eg = models.EditorGroup(**eg_source)
eg.save(blocking=True)
qsvc = QueryService()
res = qsvc.search('editor_query', 'journal', {'query': {'query_string': {'query': 'testing',
'default_operator': 'AND'}}, 'size': 0, 'aggs': {'country_publisher':
{'terms': {'field': 'index.country.exact', 'size': 100, 'order': {'_count': 'desc'}}}},
'track_total_hits': True}, account=editor, additional_parameters={})
assert res['hits']['total']["value"] == 0, res['hits']['total']["value"]
def test_associate_editor_query_notes(self):
self.app_test.config['QUERY_ROUTE'] = SEARCH_ALL_QUERY_ROUTE
self.get_journal_with_notes()
associate = models.Account(**AccountFixtureFactory.make_assed1_source())
associate.save(blocking=True)
eg_source = EditorGroupFixtureFactory.make_editor_group_source(maned=associate.id)
eg = models.EditorGroup(**eg_source)
eg.save(blocking=True)
qsvc = QueryService()
res = qsvc.search('associate_query', 'journal', {'query': {'query_string': {'query': 'testing',
'default_operator': 'AND'}}, 'size': 0, 'aggs': {'country_publisher':
{'terms': {'field': 'index.country.exact', 'size': 100, 'order': {'_count': 'desc'}}}},
'track_total_hits': True}, account=associate, additional_parameters={})
assert res['hits']['total']["value"] == 0, res['hits']['total']["value"]
def test_associate_editor_application_query_notes(self):
self.app_test.config['QUERY_ROUTE'] = SEARCH_ALL_QUERY_ROUTE
app = self.get_application_with_notes()
associate = models.Account(**AccountFixtureFactory.make_assed1_source())
associate.save(blocking=True)
eg_source = EditorGroupFixtureFactory.make_editor_group_source(maned=associate.id)
eg = models.EditorGroup(**eg_source)
eg.set_name(app.editor_group)
eg.save(blocking=True)
qsvc = QueryService()
res = qsvc.search('associate_query', 'suggestion', {'query': {'query_string': {'query': 'application test',
'default_operator': 'AND'}}, 'size': 0, 'aggs': {'country_publisher':
{'terms': {'field': 'index.country.exact', 'size': 100, 'order': {'_count': 'desc'}}}},
'track_total_hits': True}, account=associate, additional_parameters={})
assert res['hits']['total']["value"] == 0, res['hits']['total']["value"]
def test_editor_application_query_notes(self):
self.app_test.config['QUERY_ROUTE'] = SEARCH_ALL_QUERY_ROUTE
app = self.get_application_with_notes()
editor = models.Account(**AccountFixtureFactory.make_editor_source())
editor.save(blocking=True)
eg_source = EditorGroupFixtureFactory.make_editor_group_source(maned=editor.id)
eg = models.EditorGroup(**eg_source)
eg.set_name(app.editor_group)
eg.save(blocking=True)
qsvc = QueryService()
res = qsvc.search('editor_query', 'suggestion', {'query': {'query_string': {'query': 'application test',
'default_operator': 'AND'}}, 'size': 0, 'aggs': {'country_publisher':
{'terms': {'field': 'index.country.exact', 'size': 100, 'order': {'_count': 'desc'}}}},
'track_total_hits': True}, account=editor, additional_parameters={})
assert res['hits']['total']["value"] == 0, res['hits']['total']["value"]
def test_admin_application_query_notes(self):
app = self.get_application_with_notes()
med = models.Account(**AccountFixtureFactory.make_managing_editor_source())
med.save(blocking=True)
eg_source = EditorGroupFixtureFactory.make_editor_group_source(maned=med.id)
eg = models.EditorGroup(**eg_source)
eg.set_name(app.editor_group)
eg.save(blocking=True)
qsvc = QueryService()
res = qsvc.search('admin_query', 'suggestion', {'query': {'query_string': {'query': 'application test',
'default_operator': 'AND'}}, 'size': 0, 'aggs': {'country_publisher':
{'terms': {'field': 'index.country.exact', 'size': 100, 'order': {'_count': 'desc'}}}},
'track_total_hits': True}, account=med, additional_parameters={})
assert res['hits']['total']["value"] == 1, res['hits']['total']["value"]
def test_journal_article_query_notes(self):
self.app_test.config['QUERY_ROUTE'] = self.OLD_QUERY_ROUTE
self.app_test.config['QUERY_FILTERS'] = self.OLD_QUERY_FILTERS
self.article11 = models.Article(
**ArticleFixtureFactory.make_article_source(pissn="1111-1111", eissn="2222-2222", doi="10.0000/article-11",
fulltext="https://www.article11.com"))
self.article11.save(blocking=True)
self.get_journal_with_notes()
qsvc = QueryService()
res = qsvc.search('query', 'journal,article', {'query': {'query_string':
{'query': 'application test','default_operator': 'AND'}},
'size': 0, 'track_total_hits': True}, account=None, additional_parameters={"ref":"fqw"})
assert res['hits']['total']["value"] == 0, res['hits']['total']["value"]