test_entries.py 32.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD. See https://nomad-lab.eu for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

19
20
21
22
23
24
import pytest
from urllib.parse import urlencode
import zipfile
import io
import json

25
26
from nomad.datamodel import results
from nomad.metainfo.elasticsearch_extension import entry_type
27

28
from tests.utils import ExampleData
29
from tests.test_files import example_mainfile_contents, append_raw_files  # pylint: disable=unused-import
30

31
from .common import (
32
33
    aggregation_exclude_from_search_test_parameters, assert_response, assert_base_metadata_response,
    assert_metadata_response, assert_required, assert_aggregations, assert_pagination,
34
    perform_metadata_test, post_query_test_parameters, get_query_test_parameters,
35
    perform_owner_test, owner_test_parameters, pagination_test_parameters,
36
    aggregation_test_parameters)
37
from tests.conftest import example_data as data  # pylint: disable=unused-import
38

39
40
41
42
43
44
45
46
47
48
49
'''
These are the tests for all API operations below ``entries``. The tests are organized
using the following type of methods: fixtures, ``perfrom_*_test``, ``assert_*``, and
``test_*``. While some ``test_*`` methods test individual API operations, some
test methods will test multiple API operations that use common aspects like
supporting queries, pagination, or the owner parameter. The test methods will use
``perform_*_test`` methods as an parameter. Similarely, the ``assert_*`` methods allow
to assert for certain aspects in the responses.
'''


50
51
52
def perform_entries_metadata_test(*args, **kwargs):
    kwargs.update(endpoint='entries')
    return perform_metadata_test(*args, **kwargs)
53
54
55


def perform_entries_raw_download_test(
56
        client, headers={}, query={}, owner=None, files={}, total=-1, files_per_entry=5,
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
        status_code=200, http_method='get'):

    if owner == 'all':
        # This operation is not allow for owner 'all'
        status_code = 401

    if http_method == 'post':
        body = {'query': query, 'files': files}
        if owner is not None:
            body['owner'] = owner
        response = client.post('entries/raw/download/query', headers=headers, json=body)

    elif http_method == 'get':
        params = dict(**query)
        params.update(**files)
        if owner is not None:
            params['owner'] = owner
        response = client.get('entries/raw/download?%s' % urlencode(params, doseq=True), headers=headers)

    else:
        assert False

    assert_response(response, status_code)
    if status_code == 200:
        assert_raw_zip_file(
82
            response, files=total * files_per_entry + 1, manifest_entries=total,
83
84
85
86
87
            compressed=files.get('compress', False))


def perform_entries_raw_test(
        client, owner=None, headers={}, status_code=200,
88
        total=None, http_method='get', files_per_entry=-1, **kwargs):
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

    if owner == 'all':
        # This operation is not allow for owner 'all'
        status_code = 401

    if http_method == 'get':
        params = {}
        if owner is not None:
            params['owner'] = owner
        for value in kwargs.values():
            params.update(**value)
        response = client.get(
            'entries/raw?%s' % urlencode(params, doseq=True), headers=headers)

    elif http_method == 'post':
        body = dict(**kwargs)
        if owner is not None:
            body['owner'] = owner
        response = client.post('entries/raw/query', headers=headers, json=body)

    else:
        assert False

112
    response_json = assert_base_metadata_response(response, status_code=status_code)
113
114
115
116
117

    if response_json is None:
        return None

    assert 'pagination' in response_json
118
119
    if total is not None:
        assert response_json['pagination']['total'] == total
120
121
122
123
124
125
126
127

    assert_entries_raw_response(response_json, files_per_entry=files_per_entry)

    return response_json


def perform_entries_archive_download_test(
        client, headers={}, query={}, owner=None, files={},
128
        total=-1, status_code=200, http_method='get'):
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

    if owner == 'all':
        # This operation is not allow for owner 'all'
        status_code = 401

    if http_method == 'post':
        body = {'query': query, 'files': files}
        if owner is not None:
            body['owner'] = owner
        response = client.post('entries/archive/download/query', headers=headers, json=body)

    elif http_method == 'get':
        params = dict(**query)
        params.update(**files)
        if owner is not None:
            params['owner'] = owner
        response = client.get('entries/archive/download?%s' % urlencode(params, doseq=True), headers=headers)

    else:
        assert False

    assert_response(response, status_code)
    if status_code == 200:
        assert_archive_zip_file(
153
            response, total=total,
154
155
156
157
            compressed=files.get('compress', False))


def perform_entries_archive_test(
158
        client, headers={}, total=-1, status_code=200, http_method='get', **kwargs):
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

    if kwargs.get('owner') == 'all':
        # This operation is not allow for owner 'all'
        status_code = 401

    if http_method == 'get':
        assert 'required' not in kwargs
        params = {}
        if 'owner' in kwargs: params.update(owner=kwargs['owner'])
        if 'query' in kwargs: params.update(**kwargs['query'])
        if 'pagination' in kwargs: params.update(**kwargs['pagination'])
        response = client.get('entries/archive?%s' % urlencode(params, doseq=True), headers=headers)

    else:
        body = dict(**kwargs)
        response = client.post('entries/archive/query', headers=headers, json=body)

    assert_response(response, status_code)
    if status_code != 200:
        return None

    json_response = response.json()
181
182
    if total >= 0:
        assert json_response['pagination']['total'] == total
183
184
185
186
    for archive_data in json_response['data']:
        required = kwargs.get('required', '*')
        archive = archive_data['archive']
        if required == '*':
187
            for key in ['metadata', 'run']:
188
189
190
191
192
193
194
195
196
197
198
                assert key in archive
        else:
            for key in required: assert key in archive
            for key in archive: assert key in required

    return json_response


def assert_raw_zip_file(
        response, files: int = -1, manifest_entries: int = -1, compressed: bool = False):

199
    manifest_keys = ['entry_id', 'upload_id', 'mainfile']
200
201
202
203
204
205

    assert len(response.content) > 0
    with zipfile.ZipFile(io.BytesIO(response.content)) as zip_file:
        with zip_file.open('manifest.json', 'r') as f:
            manifest = json.load(f)

206
207
        with_missing_files = any(entry['entry_id'] == 'id_02' for entry in manifest)
        with_overlapping_files = any(entry['entry_id'] == 'id_11' for entry in manifest)
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

        assert zip_file.testzip() is None
        zip_files = set(zip_file.namelist())
        if files >= 0:
            if with_missing_files or with_overlapping_files:
                assert files - (5 if with_missing_files else 0) - (4 if with_overlapping_files else 0) <= len(zip_files) < files
            else:
                assert len(zip_files) == files
            assert (zip_file.getinfo(zip_file.namelist()[0]).compress_type > 0) == compressed

        for path in zip_files:
            assert path == 'manifest.json' or path.startswith('id_')

        if manifest_entries >= 0:
            assert len(manifest) == manifest_entries

            for entry in manifest:
                if 'mainfile' in manifest:
                    manifest['mainfile'] in zip_files
                assert all(key in entry for key in manifest_keys)
                assert all(key in manifest_keys for key in entry)


def assert_entries_raw_response(response_json, files_per_entry: int = -1):
    assert 'data' in response_json
    for entry in response_json['data']:
        assert_entry_raw(entry, files_per_entry)


def assert_entry_raw_response(response_json, files_per_entry: int = -1):
    for key in ['entry_id', 'data']:
        assert key in response_json
    assert_entry_raw(response_json['data'], files_per_entry=files_per_entry)


def assert_entry_raw(data, files_per_entry: int = -1):
244
    for key in ['upload_id', 'entry_id', 'files']:
245
246
247
        assert key in data
    files = data['files']
    if files_per_entry >= 0:
248
        if data['entry_id'] == 'id_02':
249
250
            # missing files
            assert len(files) == 0
251
        elif data['entry_id'] in ['id_10', 'id_11']:
252
253
254
255
256
257
258
259
260
            # overlapping files
            assert len(files) == files_per_entry + 1
        else:
            assert len(files) == files_per_entry
    for file_ in files:
        assert 'size' in file_
        assert 'path' in file_


261
def assert_archive_zip_file(response, total: int = -1, compressed: bool = False):
262
    manifest_keys = ['entry_id', 'upload_id', 'path', 'parser_name']
263
264
265
266
267
268
269

    assert len(response.content) > 0
    with zipfile.ZipFile(io.BytesIO(response.content)) as zip_file:
        assert zip_file.testzip() is None
        with zip_file.open('manifest.json', 'r') as f:
            manifest = json.load(f)

270
        with_missing_files = any(entry['entry_id'] == 'id_02' for entry in manifest)
271
272

        zip_files = set(zip_file.namelist())
273
274
        if total >= 0:
            assert len(zip_files) == total + 1 - (1 if with_missing_files else 0)
275
276
277
278
279
280
281
            assert (zip_file.getinfo(zip_file.namelist()[0]).compress_type > 0) == compressed

        for path in zip_files:
            assert path.endswith('.json')
            with zip_file.open(path, 'r') as f:
                data = json.load(f)
                if path != 'manifest.json':
282
                    for key in ['entry_id', 'archive']:
283
284
285
                        assert key in data
                    assert_archive(data['archive'])

286
287
        if total >= 0:
            assert len(manifest) == total
288
289
290
291
292
293
294
295
296

            for entry in manifest:
                if 'mainfile' in manifest:
                    manifest['path'] in zip_files
                assert all(key in entry for key in manifest_keys)
                assert all(key in manifest_keys for key in entry)


def assert_archive_response(response_json, required=None):
297
    for key in ['entry_id', 'required', 'data']:
298
        assert key in response_json
299
300
    if required is not None:
        assert required == response_json['required']
301
    for key in ['entry_id', 'upload_id', 'parser_name', 'archive']:
302
303
        assert key in response_json['data']
    assert_archive(response_json['data']['archive'], required=required)
304
305
306


def assert_archive(archive, required=None):
307
    for key in ['metadata']:
308
309
310
        assert key in archive


311
n_code_names = results.Simulation.program_name.a_elasticsearch[0].default_aggregation_size
312
program_name = 'results.method.simulation.program_name'
313
314


315
def test_entries_all_metrics(client, data):
316
317
318
319
320
321
    aggregations = {
        quantity: {
            'terms': {
                'quantity': quantity, 'metrics': [metric for metric in entry_type.metrics]
            }
        }
322
        for quantity in entry_type.quantities if entry_type.quantities[quantity].aggregateable}
323
    response_json = perform_entries_metadata_test(
324
325
326
        client, aggregations=aggregations, status_code=200, http_method='post')
    for name, agg in aggregations.items():
        assert_aggregations(response_json, name, agg['terms'])
327
328


329
@pytest.mark.parametrize(
330
331
332
333
    'aggregation, total, size, status_code, user',
    aggregation_test_parameters(entity_id='entry_id', material_prefix='results.material.', entry_prefix='', total=23) + [
        pytest.param(
            {
334
335
336
337
338
339
                'terms': {
                    'quantity': 'upload_id',
                    'entries': {
                        'size': 10,
                        'required': {'exclude': ['files', 'mainfile']}
                    }
340
341
                }
            },
342
            7, 7, 200, 'test_user', id='entries-exclude'),
343
        pytest.param(
344
            {'terms': {'quantity': 'entry_id', 'value_filter': '_0'}},
345
346
            9, 9, 200, None, id='filter'),
        pytest.param(
347
            {'terms': {'quantity': 'entry_id', 'value_filter': '.*_0.*'}},
348
            -1, -1, 422, None, id='bad-filter')
349
    ])
350
351
352
353
354
def test_entries_aggregations(client, data, test_user_auth, aggregation, total, size, status_code, user):
    headers = {}
    if user == 'test_user':
        headers = test_user_auth

355
    aggregations = {'test_agg_name': aggregation}
356

357
358
    response_json = perform_entries_metadata_test(
        client, headers=headers, owner='visible', aggregations=aggregations,
359
        pagination=dict(page_size=0),
360
361
362
363
364
        status_code=status_code, http_method='post')

    if response_json is None:
        return

365
366
367
368
    for aggregation_obj in aggregation.values():
        assert_aggregations(
            response_json, 'test_agg_name', aggregation_obj, total=total, size=size,
            default_key='entry_id')
369
370


371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
@pytest.mark.parametrize(
    'query,aggs,agg_lengths,total,status_code',
    aggregation_exclude_from_search_test_parameters(entry_prefix='', total_per_entity=1, total=23))
def test_entries_aggregations_exclude_from_search(client, data, query, aggs, agg_lengths, total, status_code):
    aggs = {f'agg_{i}': {'terms': agg} for i, agg in enumerate(aggs)}

    response_json = perform_entries_metadata_test(
        client, owner='visible',
        query=query, aggregations=aggs,
        pagination=dict(page_size=0),
        status_code=status_code, http_method='post')

    if response_json is None:
        return

    assert response_json['pagination']['total'] == total
    for i, length in enumerate(agg_lengths):
        response_agg = response_json['aggregations'][f'agg_{i}']['terms']
389
        assert len(response_agg['data']) == length
390
391


392
@pytest.mark.parametrize('required, status_code', [
393
394
    pytest.param({'include': ['entry_id', 'upload_id']}, 200, id='include'),
    pytest.param({'include': ['results.*', 'upload_id']}, 200, id='include-section'),
395
396
    pytest.param({'exclude': ['upload_id']}, 200, id='exclude'),
    pytest.param({'exclude': ['missspelled', 'upload_id']}, 422, id='bad-quantitiy'),
397
398
399
    pytest.param({'exclude': ['entry_id']}, 200, id='exclude-id'),
    pytest.param({'exclude': ['results.material.*']}, 200, id='exclude-sub-section'),
    pytest.param({'exclude': ['files', 'results.material.*', 'results.method.*']}, 200, id='exclude-multiple'),
400
401
402
403
404
    pytest.param({'include': ['upload_id']}, 200, id='include-id')
])
@pytest.mark.parametrize('http_method', ['post', 'get'])
def test_entries_required(client, data, required, status_code, http_method):
    response_json = perform_entries_metadata_test(
405
        client, required=required, pagination={'page_size': 1}, status_code=status_code, http_method=http_method)
406
407
408
409

    if response_json is None:
        return

410
    assert_required(response_json['data'][0], required, default_key='entry_id')
411
412
413
414
415


@pytest.mark.parametrize('entry_id, required, status_code', [
    pytest.param('id_01', {}, 200, id='id'),
    pytest.param('doesnotexist', {}, 404, id='404'),
416
    pytest.param('id_01', {'include': ['entry_id', 'upload_id']}, 200, id='include'),
417
    pytest.param('id_01', {'exclude': ['upload_id']}, 200, id='exclude'),
418
    pytest.param('id_01', {'exclude': ['entry_id', 'upload_id']}, 200, id='exclude-entry-id')
419
420
421
])
def test_entry_metadata(client, data, entry_id, required, status_code):
    response = client.get('entries/%s?%s' % (entry_id, urlencode(required, doseq=True)))
422
    response_json = assert_metadata_response(response, status_code=status_code)
423
424
425
426

    if response_json is None:
        return

427
    assert_required(response_json['data'], required, default_key='entry_id')
428
429


430
@pytest.mark.parametrize('query, files, total, files_per_entry, status_code', [
431
    pytest.param({}, {}, 23, 5, 200, id='all'),
432
433
    pytest.param({'entry_id': 'id_01'}, {}, 1, 5, 200, id='all'),
    pytest.param({program_name: 'DOESNOTEXIST'}, {}, 0, 5, 200, id='empty')
434
435
])
@pytest.mark.parametrize('http_method', ['post', 'get'])
436
def test_entries_raw(client, data, query, files, total, files_per_entry, status_code, http_method):
437
    perform_entries_raw_test(
438
        client, status_code=status_code, query=query, files=files, total=total,
439
440
441
        files_per_entry=files_per_entry, http_method=http_method)


442
@pytest.mark.parametrize('query, files, total, files_per_entry, status_code', [
443
    pytest.param({}, {}, 23, 5, 200, id='all'),
444
    pytest.param({program_name: 'DOESNOTEXIST'}, {}, 0, 5, 200, id='empty'),
445
446
447
448
449
450
    pytest.param({}, {'glob_pattern': '*.json'}, 23, 1, 200, id='glob'),
    pytest.param({}, {'re_pattern': '[a-z]*\\.aux'}, 23, 4, 200, id='re'),
    pytest.param({}, {'re_pattern': 'test_entry_02'}, 1, 5, 200, id='re-filter-entries'),
    pytest.param({}, {'re_pattern': 'test_entry_02/.*\\.json'}, 1, 1, 200, id='re-filter-entries-and-files'),
    pytest.param({}, {'glob_pattern': '*.json', 're_pattern': '.*\\.aux'}, 23, 4, 200, id='re-overwrites-glob'),
    pytest.param({}, {'re_pattern': '**'}, -1, -1, 422, id='bad-re-pattern'),
451
452
453
    pytest.param({}, {'compress': True}, 23, 5, 200, id='compress'),
    pytest.param({}, {'include_files': ['1.aux']}, 23, 1, 200, id='file'),
    pytest.param({}, {'include_files': ['1.aux', '2.aux']}, 23, 2, 200, id='files')
454
455
])
@pytest.mark.parametrize('http_method', ['post', 'get'])
456
def test_entries_download_raw(client, data, query, files, total, files_per_entry, status_code, http_method):
457
    perform_entries_raw_download_test(
458
        client, status_code=status_code, query=query, files=files, total=total,
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
        files_per_entry=files_per_entry, http_method=http_method)


@pytest.mark.parametrize('http_method', ['post', 'get'])
@pytest.mark.parametrize('test_method', [
    pytest.param(perform_entries_raw_download_test, id='raw-download'),
    pytest.param(perform_entries_archive_download_test, id='archive-download')])
def test_entries_download_max(monkeypatch, client, data, test_method, http_method):
    monkeypatch.setattr('nomad.config.max_entry_download', 20)

    test_method(client, status_code=400, http_method=http_method)


@pytest.mark.parametrize('entry_id, files_per_entry, status_code', [
    pytest.param('id_01', 5, 200, id='id'),
    pytest.param('id_embargo', -1, 404, id='404'),
    pytest.param('doesnotexist', -1, 404, id='404')])
def test_entry_raw(client, data, entry_id, files_per_entry, status_code):
    response = client.get('entries/%s/raw' % entry_id)
    assert_response(response, status_code)
    if status_code == 200:
        assert_entry_raw_response(response.json(), files_per_entry=files_per_entry)


@pytest.mark.parametrize('entry_id, files, files_per_entry, status_code', [
    pytest.param('id_01', {}, 5, 200, id='id'),
    pytest.param('doesnotexist', {}, -1, 404, id='404'),
    pytest.param('id_01', {'glob_pattern': '*.json'}, 1, 200, id='glob'),
    pytest.param('id_01', {'re_pattern': '[a-z]*\\.aux'}, 4, 200, id='re'),
    pytest.param('id_01', {'re_pattern': '**'}, -1, 422, id='bad-re-pattern'),
489
490
491
492
    pytest.param('id_01', {'compress': True}, 5, 200, id='compress'),
    pytest.param('id_01', {'include_files': ['1.aux']}, 1, 200, id='file'),
    pytest.param('id_01', {'include_files': ['1.aux', '2.aux']}, 2, 200, id='files')
])
493
def test_entry_raw_download(client, data, entry_id, files, files_per_entry, status_code):
494
495
496
497
498
499
500
501
    response = client.get('entries/%s/raw/download?%s' % (entry_id, urlencode(files, doseq=True)))
    assert_response(response, status_code)
    if status_code == 200:
        assert_raw_zip_file(
            response, files=files_per_entry + 1, manifest_entries=1,
            compressed=files.get('compress', False))


502
@pytest.fixture(scope='function')
503
def example_data_with_compressed_files(elastic_module, raw_files_module, mongo_module, test_user, other_test_user, normalized):
504
    data = ExampleData(main_author=test_user)
505
506
507
508
509
510
511

    data.create_upload(
        upload_id='with_compr_published',
        published=True)
    data.create_entry(
        upload_id='with_compr_published',
        calc_id='with_compr_published',
512
        mainfile='test_content/test_entry/mainfile.json')
513
514
515
516
517
518
    data.create_upload(
        upload_id='with_compr_unpublished',
        published=False)
    data.create_entry(
        upload_id='with_compr_unpublished',
        calc_id='with_compr_unpublished',
519
        mainfile='test_content/test_entry/mainfile.json')
520
521
522
523
524
525

    data.save()

    append_raw_files(
        'with_compr_published', 'tests/data/api/mainfile.xz',
        'test_content/test_entry/mainfile.xz')
526
    append_raw_files(
527
528
        'with_compr_published', 'tests/data/api/mainfile.gz',
        'test_content/test_entry/mainfile.gz')
529
    append_raw_files(
530
531
532
533
534
        'with_compr_unpublished', 'tests/data/api/mainfile.xz',
        'test_content/test_entry/mainfile.xz')
    append_raw_files(
        'with_compr_unpublished', 'tests/data/api/mainfile.gz',
        'test_content/test_entry/mainfile.gz')
535
536
537

    yield

538
    data.delete()
539
    from nomad.search import search
540
    assert search(query=dict(upload_id='with_compr_published')).pagination.total == 0
541
542
543
544
545
546
547
548
549
550
551
552


@pytest.mark.parametrize('entry_id, path, params, status_code', [
    pytest.param('id_01', 'mainfile.json', {}, 200, id='id'),
    pytest.param('doesnotexist', 'mainfile.json', {}, 404, id='404-entry'),
    pytest.param('id_01', 'doesnot.exist', {}, 404, id='404-file'),
    pytest.param('id_01', 'mainfile.json', {'offset': 10, 'length': 10}, 200, id='offset-length'),
    pytest.param('id_01', 'mainfile.json', {'length': 1000000}, 200, id='length-too-large'),
    pytest.param('id_01', 'mainfile.json', {'offset': 1000000}, 200, id='offset-too-large'),
    pytest.param('id_01', 'mainfile.json', {'offset': -1}, 422, id='bad-offset'),
    pytest.param('id_01', 'mainfile.json', {'length': -1}, 422, id='bad-length'),
    pytest.param('id_01', 'mainfile.json', {'decompress': True}, 200, id='decompress-json'),
553
554
555
556
    pytest.param('with_compr_published', 'mainfile.xz', {'decompress': True}, 200, id='decompress-xz-published'),
    pytest.param('with_compr_published', 'mainfile.gz', {'decompress': True}, 200, id='decompress-gz-published'),
    pytest.param('with_compr_unpublished', 'mainfile.xz', {'decompress': True, 'user': 'test-user'}, 200, id='decompress-xz-unpublished'),
    pytest.param('with_compr_unpublished', 'mainfile.gz', {'decompress': True, 'user': 'test-user'}, 200, id='decompress-gz-unpublished'),
557
    pytest.param('id_unpublished', 'mainfile.json', {}, 404, id='404-unpublished'),
558
559
560
561
562
    pytest.param('id_embargo_1', 'mainfile.json', {}, 404, id='404-embargo-no-user'),
    pytest.param('id_embargo_1', 'mainfile.json', {'user': 'other-test-user'}, 404, id='404-embargo-no-access'),
    pytest.param('id_embargo_1', 'mainfile.json', {'user': 'test-user'}, 200, id='embargo-main_author'),
    pytest.param('id_embargo_w_coauthor_1', 'mainfile.json', {'user': 'other-test-user'}, 200, id='embargo-coauthor'),
    pytest.param('id_embargo_w_reviewer_1', 'mainfile.json', {'user': 'other-test-user'}, 200, id='embargo-reviewer')
563
564
])
def test_entry_raw_download_file(
565
        client, data, example_data_with_compressed_files, example_mainfile_contents, test_user_auth, other_test_user_auth,
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
        entry_id, path, params, status_code):

    user = params.get('user')
    if user:
        del(params['user'])
        if user == 'test-user':
            headers = test_user_auth
        elif user == 'other-test-user':
            headers = other_test_user_auth
    else:
        headers = {}

    response = client.get(
        f'entries/{entry_id}/raw/download/{path}?{urlencode(params, doseq=True)}',
        headers=headers)

    assert_response(response, status_code)
    if status_code == 200:
        content = response.text
        if path.endswith('.json'):
            offset = params.get('offset', 0)
            length = params.get('length', len(example_mainfile_contents) - offset)
            assert content == example_mainfile_contents[offset:offset + length]
        else:
            assert content == 'test content\n'


593
@pytest.mark.parametrize('query, files, total, status_code', [
594
    pytest.param({}, {}, 23, 200, id='all'),
595
    pytest.param({program_name: 'DOESNOTEXIST'}, {}, -1, 200, id='empty'),
596
597
598
    pytest.param({}, {'compress': True}, 23, 200, id='compress')
])
@pytest.mark.parametrize('http_method', ['post', 'get'])
599
def test_entries_archive_download(client, data, query, files, total, status_code, http_method):
600
    perform_entries_archive_download_test(
601
        client, status_code=status_code, query=query, files=files, total=total,
602
603
604
605
606
        http_method=http_method)


@pytest.mark.parametrize('required, status_code', [
    pytest.param('*', 200, id='full'),
607
608
    pytest.param({'metadata': '*'}, 200, id='partial'),
    pytest.param({'run': {'system[NOTANINT]': '*'}}, 422, id='bad-required-1'),
609
    pytest.param({'metadata': {'viewers[NOTANINT]': '*'}}, 422, id='bad-required-2'),
610
    pytest.param({'DOESNOTEXIST': '*'}, 422, id='bad-required-3')
611
612
613
614
615
616
617
618
])
def test_entries_archive(client, data, required, status_code):
    perform_entries_archive_test(
        client, status_code=status_code, required=required, http_method='post')


@pytest.mark.parametrize('entry_id, status_code', [
    pytest.param('id_01', 200, id='id'),
619
620
    pytest.param('id_02', 404, id='404-not-visible'),
    pytest.param('doesnotexist', 404, id='404-does-not-exist')])
621
622
623
624
625
626
627
def test_entry_archive(client, data, entry_id, status_code):
    response = client.get('entries/%s/archive' % entry_id)
    assert_response(response, status_code)
    if status_code == 200:
        assert_archive_response(response.json())


628
629
630
631
632
633
634
635
636
637
638
639
640
@pytest.mark.parametrize('entry_id, status_code', [
    pytest.param('id_01', 200, id='id'),
    pytest.param('id_02', 404, id='404-not-visible'),
    pytest.param('doesnotexist', 404, id='404-does-not-exist')])
def test_entry_archive_download(client, data, entry_id, status_code):
    response = client.get('entries/%s/archive/download' % entry_id)
    assert_response(response, status_code)
    if status_code == 200:
        archive = response.json()
        assert 'metadata' in archive
        assert 'run' in archive


641
642
643
@pytest.mark.parametrize('entry_id, required, status_code', [
    pytest.param('id_01', '*', 200, id='full'),
    pytest.param('id_02', '*', 404, id='404'),
644
645
    pytest.param('id_01', {'metadata': '*'}, 200, id='partial'),
    pytest.param('id_01', {'run': {'system[NOTANINT]': '*'}}, 422, id='bad-required-1'),
646
    pytest.param('id_01', {'metadata': {'viewers[NOTANINT]': '*'}}, 422, id='bad-required-2'),
647
    pytest.param('id_01', {'DOESNOTEXIST': '*'}, 422, id='bad-required-3'),
648
649
    pytest.param('id_01', {'resolve-inplace': 'NotBool', 'workflow': '*'}, 422, id='bad-required-4'),
    pytest.param('id_01', {'resolve-inplace': True, 'metadata': 'include-resolved'}, 200, id='resolve-inplace')
650
651
652
653
654
655
656
657
658
659
])
def test_entry_archive_query(client, data, entry_id, required, status_code):
    response = client.post('entries/%s/archive/query' % entry_id, json={
        'required': required
    })
    assert_response(response, status_code)
    if status_code == 200:
        assert_archive_response(response.json(), required=required)


660
elements = 'results.material.elements'
661
n_elements = 'results.material.n_elements'
662
663


664
@pytest.mark.parametrize('query, status_code, total', post_query_test_parameters(
665
    'entry_id', total=23, material_prefix='results.material.', entry_prefix='') + [
666
667
668
669
670
    pytest.param({'pid': '123'}, 200, 1, id='number-valued-string'),
    pytest.param({'optimade_filter': 'nelements = 2'}, 200, 23, id='optimade-filter-positive'),
    pytest.param({'optimade_filter': 'nelements < 2'}, 200, 0, id='optimade-filter-negative'),
    pytest.param({'optimade_filter': '#broken syntax'}, 422, 0, id='optimade-filter-broken-syntax'),
    pytest.param({'optimade_filter': 'doesnotexist = 1'}, 422, 0, id='optimade-filter-broken-semantics')
671
])
672
673
674
675
676
677
678
@pytest.mark.parametrize('test_method', [
    pytest.param(perform_entries_metadata_test, id='metadata'),
    pytest.param(perform_entries_raw_download_test, id='raw-download'),
    pytest.param(perform_entries_raw_test, id='raw'),
    pytest.param(perform_entries_archive_test, id='archive'),
    pytest.param(perform_entries_archive_download_test, id='archive-download')])
def test_entries_post_query(client, data, query, status_code, total, test_method):
679
    response_json = test_method(client, query=query, status_code=status_code, total=total, http_method='post')
680
681

    response = client.post('entries/query', json={'query': query})
682
    response_json = assert_metadata_response(response, status_code=status_code)
683
684
685
686
687
688
689
690
691

    if response_json is None:
        return

    if 'pagination' not in response_json:
        return

    pagination = response_json['pagination']
    assert pagination['total'] == total
692
    assert pagination['page_size'] == 10
693
    assert pagination['order_by'] == 'entry_id'
694
    assert pagination['order'] == 'asc'
695
    assert ('next_page_after_value' in pagination) == (total > 10)
696
697


698
699
700
@pytest.mark.parametrize('query, status_code, total', get_query_test_parameters(
    'entry_id', total=23, material_prefix='results.material.', entry_prefix='') + [
        pytest.param({'q': 'domain__dft'}, 200, 23, id='enum')])
701
702
703
704
705
706
707
708
@pytest.mark.parametrize('test_method', [
    pytest.param(perform_entries_metadata_test, id='metadata'),
    pytest.param(perform_entries_raw_download_test, id='raw-download'),
    pytest.param(perform_entries_raw_test, id='raw'),
    pytest.param(perform_entries_archive_test, id='archive'),
    pytest.param(perform_entries_archive_download_test, id='archive-download')])
def test_entries_get_query(client, data, query, status_code, total, test_method):
    response_json = test_method(
709
        client, query=query, status_code=status_code, total=total, http_method='get')
710
711
712
713
714
715
716
717
718

    if response_json is None:
        return

    if 'pagination' not in response_json:
        return

    response = client.get('entries?%s' % urlencode(query, doseq=True))

719
    response_json = assert_metadata_response(response, status_code=status_code)
720
721
722
723
724
725

    if response_json is None:
        return

    pagination = response_json['pagination']
    assert pagination['total'] == total
726
    assert pagination['page_size'] == 10
727
    assert pagination['order_by'] == 'entry_id'
728
    assert pagination['order'] == 'asc'
729
    assert ('next_page_after_value' in pagination) == (total > 10)
730
731


732
@pytest.mark.parametrize('owner, user, status_code, total', owner_test_parameters(total=23))
733
734
735
736
737
738
739
740
741
742
743
@pytest.mark.parametrize('http_method', ['post', 'get'])
@pytest.mark.parametrize('test_method', [
    pytest.param(perform_entries_metadata_test, id='metadata'),
    pytest.param(perform_entries_raw_download_test, id='raw-download'),
    pytest.param(perform_entries_raw_test, id='raw'),
    pytest.param(perform_entries_archive_test, id='archive'),
    pytest.param(perform_entries_archive_download_test, id='archive-download')])
def test_entries_owner(
        client, data, test_user_auth, other_test_user_auth, admin_user_auth,
        owner, user, status_code, total, http_method, test_method):

744
    perform_owner_test(
745
746
747
748
        client, test_user_auth, other_test_user_auth, admin_user_auth,
        owner, user, status_code, total, http_method, test_method)


749
750
751
752
753
@pytest.mark.parametrize('pagination, response_pagination, status_code', pagination_test_parameters(
    elements='results.material.elements',
    n_elements='results.material.n_elements',
    crystal_system='results.material.symmetry.crystal_system',
    total=23))
754
755
756
757
758
759
760
761
762
763
764
765
@pytest.mark.parametrize('http_method', ['post', 'get'])
@pytest.mark.parametrize('test_method', [
    pytest.param(perform_entries_metadata_test, id='metadata'),
    pytest.param(perform_entries_raw_test, id='raw'),
    pytest.param(perform_entries_archive_test, id='archive')])
def test_entries_pagination(client, data, pagination, response_pagination, status_code, http_method, test_method):
    response_json = test_method(
        client, pagination=pagination, status_code=status_code, http_method=http_method)

    if response_json is None:
        return

766
    assert_pagination(pagination, response_json['pagination'], response_json['data'], is_get=(http_method == 'get'))
767
768
769
770

    if response_pagination is None:
        return
    for key in response_pagination:
771
772
773
774
        if response_pagination[key] is None:
            assert key not in response_json['pagination']
        else:
            assert response_json['pagination'][key] == response_pagination[key]
775
    if len(response_json['data']) > 0 and 'order_by' not in pagination:
776
777
        if response_pagination['next_page_after_value'] is not None:
            assert response_json['data'][-1]['entry_id'] == response_pagination['next_page_after_value']