test_materials.py 10.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#
# 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.
#

import pytest
from urllib.parse import urlencode

22
from nomad.metainfo.elasticsearch_extension import material_entry_type
23
24
25
26

from tests.test_files import example_mainfile_contents  # pylint: disable=unused-import

from .common import (
27
    aggregation_exclude_from_search_test_parameters, assert_pagination, assert_metadata_response, assert_required, assert_aggregations,
28
    perform_metadata_test, perform_owner_test, owner_test_parameters,
29
    post_query_test_parameters, get_query_test_parameters, pagination_test_parameters,
30
    aggregation_test_parameters)
31
32
33
34
from ..conftest import example_data as data  # pylint: disable=unused-import

'''
These are the tests for all API operations below ``entries``. The tests are organized
35
using the following type of methods: fixtures, ``perform*_test``, ``assert_*``, and
36
37
38
``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
39
``perform_*_test`` methods as an parameter. Similarly, the ``assert_*`` methods allow
40
41
42
43
44
45
46
47
48
49
50
51
to assert for certain aspects in the responses.
'''


def perform_materials_metadata_test(*args, **kwargs):
    kwargs.update(endpoint='materials')
    return perform_metadata_test(*args, **kwargs)


program_name = 'entries.results.method.simulation.program_name'


52
53
54
55
56
57
58
59
@pytest.mark.parametrize(
    'aggregation, total, size, status_code, user',
    aggregation_test_parameters(
        entity_id='material_id', material_prefix='', entry_prefix='entries.', total=6))
def test_materials_aggregations(client, data, test_user_auth, aggregation, total, size, status_code, user):
    headers = {}
    if user == 'test_user':
        headers = test_user_auth
60

61
    aggregations = {'test_agg_name': aggregation}
62

63
64
65
66
    response_json = perform_materials_metadata_test(
        client, headers=headers, owner='visible', aggregations=aggregations,
        pagination=dict(page_size=0),
        status_code=status_code, http_method='post')
67

68
69
70
    if response_json is None:
        return

71
72
73
74
    for aggregation_obj in aggregation.values():
        assert_aggregations(
            response_json, 'test_agg_name', aggregation_obj, total=total, size=size,
            default_key='material_id')
75

76
77
78
79
80
        # make sure that (nested) terms aggregation produce sensible counts
        if 'terms' in aggregation:
            for bucket in response_json['aggregations']['test_agg_name']['terms']['data']:
                assert bucket['count'] <= 6  # the total number of materials, counting entries we would surpass this

81

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
@pytest.mark.parametrize(
    'query,aggs,agg_lengths,total,status_code',
    aggregation_exclude_from_search_test_parameters(entry_prefix='entries.', total_per_entity=3, total=6))
def test_materials_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_materials_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']
    assert len(response_agg['data']) == length


103
104
105
106
107
108
109
110
111
112
113
@pytest.mark.parametrize('required, status_code', [
    pytest.param({'include': ['material_id', program_name]}, 200, id='include'),
    pytest.param({'include': ['entries.*', program_name]}, 200, id='include-section'),
    pytest.param({'exclude': [program_name]}, 200, id='exclude'),
    pytest.param({'exclude': ['missspelled', program_name]}, 422, id='bad-quantitiy'),
    pytest.param({'exclude': ['material_id']}, 200, id='exclude-id'),
    pytest.param({'exclude': ['entries.results.*']}, 200, id='exclude-sub-section'),
    pytest.param({'exclude': [program_name, 'entries.results.method.*']}, 200, id='exclude-multiple'),
    pytest.param({'include': [program_name]}, 200, id='include-id')
])
@pytest.mark.parametrize('http_method', ['post', 'get'])
114
def test_materials_required(client, data, required, status_code, http_method):
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    response_json = perform_materials_metadata_test(
        client, required=required, pagination={'page_size': 1}, status_code=status_code, http_method=http_method)

    if response_json is None:
        return

    assert_required(response_json['data'][0], required, default_key='material_id')


@pytest.mark.parametrize('material_id, required, status_code', [
    pytest.param('id_01', {}, 200, id='id'),
    pytest.param('doesnotexist', {}, 404, id='404'),
    pytest.param('id_01', {'include': ['material_id', 'n_elements']}, 200, id='include'),
    pytest.param('id_01', {'exclude': ['n_elements']}, 200, id='exclude'),
    pytest.param('id_01', {'exclude': ['material_id', 'n_elements']}, 200, id='exclude-id')
])
131
def test_material_metadata(client, data, material_id, required, status_code):
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
    response = client.get('materials/%s?%s' % (material_id, urlencode(required, doseq=True)))
    response_json = assert_metadata_response(response, status_code=status_code)

    if response_json is None:
        return

    assert_required(response_json['data'], required, default_key='material_id')


@pytest.mark.parametrize(
    'query, status_code, total',
    post_query_test_parameters('material_id', total=6, material_prefix='', entry_prefix='entries.') + [
        pytest.param({'entries.entry_id': 'id_01'}, 200, 1, id='entries-single'),
        pytest.param({'entries.entry_id:any': ['id_01', 'id_02']}, 200, 1, id='any-entry-same-material'),
        pytest.param({'entries.entry_id:any': ['id_01', 'id_05']}, 200, 2, id='any-entry-diff-material'),
        pytest.param({'entries.entry_id:all': ['id_01', 'id_02']}, 200, 0, id='all-entry-same-material'),
        pytest.param({'entries.entry_id:all': ['id_01', 'id_05']}, 200, 0, id='all-entry-diff-material'),
        pytest.param({
            'and': [
                {'entries.entry_id': 'id_01'},
                {'entries.entry_id': 'id_02'}
            ]
        }, 200, 1, id='per-entry-same-material'),
        pytest.param({
            'and': [
                {'entries.entry_id': 'id_01'},
                {'entries.entry_id': 'id_05'}
            ]
        }, 200, 0, id='per-entry-diff-material'),
        pytest.param({'entries': {'entry_id:any': ['id_01', 'id_02']}}, 200, 1, id='alt-any-entry-same-material'),
        pytest.param({'entries': {'entry_id:any': ['id_01', 'id_05']}}, 200, 2, id='alt-any-entry-diff-material'),
        pytest.param({'entries': {'entry_id:all': ['id_01', 'id_02']}}, 200, 0, id='alt-all-entry-same-material'),
        pytest.param({'entries': {'entry_id:all': ['id_01', 'id_05']}}, 200, 0, id='alt-all-entry-diff-material'),
        pytest.param({'entry_id': 'id_01'}, 422, 0, id='not-material-quantity'),
        pytest.param({'entries.material_id': 'id_01'}, 422, 0, id='not-entry-quantity')
    ])
def test_materials_post_query(client, data, query, status_code, total):
    response_json = perform_materials_metadata_test(
        client, query=query, status_code=status_code, total=total,
        http_method='post')

    response = client.post('materials/query', json={'query': query})
    response_json = assert_metadata_response(response, status_code=status_code)

    if response_json is None:
        return

    if 'pagination' not in response_json:
        return

    pagination = response_json['pagination']
    assert pagination['total'] == total
    assert pagination['page_size'] == 10
    assert pagination['order_by'] == 'material_id'
    assert pagination['order'] == 'asc'
    assert ('next_page_after_value' in pagination) == (total > 10)


@pytest.mark.parametrize('query, status_code, total', get_query_test_parameters(
    'material_id', total=6, material_prefix='', entry_prefix='entries.'))
def test_materials_get_query(client, data, query, status_code, total):
193
    assert 'entries.upload_create_time' in material_entry_type.quantities
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

    response_json = perform_materials_metadata_test(
        client, query=query, status_code=status_code, total=total, http_method='get')

    if response_json is None:
        return

    if 'pagination' not in response_json:
        return

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

    response_json = assert_metadata_response(response, status_code=status_code)

    if response_json is None:
        return

    pagination = response_json['pagination']
    assert pagination['total'] == total
    assert pagination['page_size'] == 10
    assert pagination['order_by'] == 'material_id'
    assert pagination['order'] == 'asc'
    assert ('next_page_after_value' in pagination) == (total > 10)


@pytest.mark.parametrize('owner, user, status_code, total', owner_test_parameters(total=6))
@pytest.mark.parametrize('http_method', ['post', 'get'])
@pytest.mark.parametrize('test_method', [
    pytest.param(perform_materials_metadata_test, id='metadata')])
def test_materials_owner(
        client, data, test_user_auth, other_test_user_auth, admin_user_auth,
        owner, user, status_code, total, http_method, test_method):

    perform_owner_test(
        client, test_user_auth, other_test_user_auth, admin_user_auth,
        owner, user, status_code, total, http_method, test_method)


@pytest.mark.parametrize('pagination, response_pagination, status_code', pagination_test_parameters(
    elements='elements', n_elements='n_elements', crystal_system='symmetry.crystal_system',
    total=6))
@pytest.mark.parametrize('http_method', ['post', 'get'])
def test_materials_pagination(client, data, pagination, response_pagination, status_code, http_method):
    response_json = perform_materials_metadata_test(
        client, pagination=pagination, status_code=status_code, http_method=http_method)

    if response_json is None:
        return

    assert_pagination(pagination, response_json['pagination'], response_json['data'], is_get=(http_method == 'get'))