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

from nomad import utils
23
from nomad.search import search
24
25
26
27
from nomad.datamodel import Dataset
from nomad import processing as proc

from tests.utils import ExampleData
28
29
30
from tests.app.v1.routers.common import assert_response
from tests.processing.test_edit_metadata import (
    assert_metadata_edited, all_coauthor_entry_metadata, all_admin_entry_metadata)
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47


logger = utils.get_logger(__name__)


class TestEditRepo():

    def query(self, *uploads):
        return {'upload_id:any': uploads}

    @pytest.fixture(autouse=True)
    def set_api(self, client, elastic, mongo):
        self.api = client

    @pytest.fixture(autouse=True)
    def example_datasets(self, test_user, other_test_user, mongo):
        self.example_dataset = Dataset(
48
            dataset_id='example_ds', dataset_name='example_ds', user_id=test_user.user_id)
49
50
51
        self.example_dataset.a_mongo.create()

        self.other_example_dataset = Dataset(
52
            dataset_id='other_example_ds', dataset_name='other_example_ds',
53
54
55
56
57
58
59
60
            user_id=other_test_user.user_id)
        self.other_example_dataset.a_mongo.create()

    @pytest.fixture(autouse=True)
    def example_data(self, test_user, other_test_user, raw_files, elastic, mongo):
        # TODO
        example_data = ExampleData()

61
        example_data.create_upload('upload_1', main_author=test_user, published=True, embargo_length=0)
62
        example_data.create_entry(upload_id='upload_1')
63
        example_data.create_upload('upload_2', main_author=test_user, published=True, embargo_length=36)
64
65
        example_data.create_entry(upload_id='upload_2')
        example_data.create_entry(upload_id='upload_2')
66
        example_data.create_upload('upload_3', main_author=other_test_user, published=True, embargo_length=0)
67
        example_data.create_entry(upload_id='upload_3')
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

        example_data.save()

    @pytest.fixture(autouse=True)
    def auth(self, test_user_auth):
        self.test_user_auth = test_user_auth

    def perform_edit(self, query=None, verify=False, **kwargs):
        actions = {}
        for key, value in kwargs.items():
            if isinstance(value, list):
                actions[key] = [dict(value=i) for i in value]
            else:
                actions[key] = dict(value=value)

        data = dict(actions=actions)
        if query is not None:
            data.update(query=query)
        if verify:
            data.update(verify=verify)

89
        return self.api.post('entries/edit_v0', headers=self.test_user_auth, json=data)
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

    def assert_edit(self, rv, quantity: str, success: bool, message: bool, status_code: int = 200):
        data = rv.json()
        assert rv.status_code == status_code, data
        actions = data.get('actions')
        assert actions is not None
        assert [quantity] == list(actions.keys())
        quantity_actions = actions[quantity]
        if not isinstance(quantity_actions, list):
            quantity_actions = [quantity_actions]
        has_failure = False
        has_message = False
        for action in quantity_actions:
            has_failure = has_failure or not action['success']
            has_message = has_message or ('message' in action)
        assert not has_failure == success
        assert has_message == message

    def mongo(self, *args, edited: bool = True, **kwargs):
109
        for entry_id in args:
David Sikter's avatar
David Sikter committed
110
            entry = proc.Entry.objects(entry_id='test_entry_id_%d' % entry_id).first()
111
            assert entry is not None
112
            if edited:
113
114
                assert entry.last_edit_time is not None
            metadata = entry.mongo_metadata(entry.upload).m_to_dict()
115
116
117
118
119
120
121
122
123
124
125
126
127
            for key, value in kwargs.items():
                if metadata.get(key) != value:
                    return False
        return True

    def assert_elastic(self, *args, invert: bool = False, **kwargs):
        def assert_entry(get_entries):
            for arg in args:
                entry_id = 'test_entry_id_%d' % arg
                entries = list(get_entries(entry_id))
                assert len(entries) > 0, entry_id
                for entry in entries:
                    for key, value in kwargs.items():
128
                        if key in ['authors', 'viewers']:
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
                            ids = [user['user_id'] for user in entry.get(key)]
                            if ids != value:
                                return False
                        else:
                            if entry.get(key) != value:
                                return False

            return True

        # test v1 data
        assert invert != assert_entry(
            lambda id: search(owner=None, query=dict(entry_id=id)).data)

    def test_edit_all_properties(self, test_user, other_test_user):
        edit_data = dict(
144
            # reviewers=[other_test_user.user_id],  # TODO: need to set on upload level
145
146
147
148
            # entry_coauthors=[other_test_user.user_id]  # Not editable any more
            comment='test_edit_props',
            references=['http://test', 'http://test2'])

149
150
151
152
153
154
155
156
157
158
159
160
161
162
        rv = self.perform_edit(**edit_data, query=self.query('upload_1'))
        result = rv.json()
        assert rv.status_code == 200, result
        actions = result.get('actions')
        for key in edit_data:
            assert key in actions
            quantity_actions = actions.get(key)
            if not isinstance(quantity_actions, list):
                quantity_actions = [quantity_actions]
            for quantity_action in quantity_actions:
                assert quantity_action['success']

        assert self.mongo(1, comment='test_edit_props')
        assert self.mongo(1, references=['http://test', 'http://test2'])
163
        # assert self.mongo(1, entry_coauthors=[other_test_user.user_id])
164
        # assert self.mongo(1, reviewers=[other_test_user.user_id])  TODO: need to be set on upload level
165
166
167

        self.assert_elastic(1, comment='test_edit_props')
        self.assert_elastic(1, references=['http://test', 'http://test2'])
168
        self.assert_elastic(1, authors=[test_user.user_id])
169
        # self.assert_elastic(1, viewers=[test_user.user_id, other_test_user.user_id])
170
171
172

        edit_data = dict(
            comment='',
173
174
            # entry_coauthors=[]
            references=[])
175
176
177
178
179
180
181
182
183
184
185
186
187
188
        rv = self.perform_edit(**edit_data, query=self.query('upload_1'))
        result = rv.json()
        assert rv.status_code == 200
        actions = result.get('actions')
        for key in edit_data:
            assert key in actions
            quantity_actions = actions.get(key)
            if not isinstance(quantity_actions, list):
                quantity_actions = [quantity_actions]
            for quantity_action in quantity_actions:
                assert quantity_action['success']

        assert self.mongo(1, comment=None)
        assert self.mongo(1, references=[])
189
        # assert self.mongo(1, entry_coauthors=[])
Mohammad Nakhaee's avatar
Mohammad Nakhaee committed
190
        assert self.mongo(1, reviewers=[])
191
192

        self.assert_elastic(1, comment=None)
193
        self.assert_elastic(1, references=[])
194
        self.assert_elastic(1, authors=[test_user.user_id])
195
        self.assert_elastic(1, viewers=[test_user.user_id])
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

    def test_edit_all(self):
        rv = self.perform_edit(comment='test_edit_all')
        self.assert_edit(rv, quantity='comment', success=True, message=False)
        assert self.mongo(1, 2, 3, comment='test_edit_all')
        self.assert_elastic(1, 2, 3, comment='test_edit_all')
        assert not self.mongo(4, comment='test_edit_all', edited=False)
        self.assert_elastic(4, comment='test_edit_all', edited=False, invert=True)

    def test_edit_multi(self):
        rv = self.perform_edit(comment='test_edit_multi', query=self.query('upload_1', 'upload_2'))
        self.assert_edit(rv, quantity='comment', success=True, message=False)
        assert self.mongo(1, 2, 3, comment='test_edit_multi')
        self.assert_elastic(1, 2, 3, comment='test_edit_multi')
        assert not self.mongo(4, comment='test_edit_multi', edited=False)
        self.assert_elastic(4, comment='test_edit_multi', edited=False, invert=True)

    def test_edit_some(self):
        rv = self.perform_edit(comment='test_edit_some', query=self.query('upload_1'))
        self.assert_edit(rv, quantity='comment', success=True, message=False)
        assert self.mongo(1, comment='test_edit_some')
        self.assert_elastic(1, comment='test_edit_some')
        assert not self.mongo(2, 3, 4, comment='test_edit_some', edited=False)
        self.assert_elastic(2, 3, 4, comment='test_edit_some', edited=False, invert=True)

    def test_edit_verify(self):
        rv = self.perform_edit(
            comment='test_edit_verify', verify=True, query=self.query('upload_1'))
        self.assert_edit(rv, quantity='comment', success=True, message=False)
        assert not self.mongo(1, comment='test_edit_verify', edited=False)

    def test_edit_empty_list(self, other_test_user):
228
229
230
231
232
        rv = self.perform_edit(references=['a'], query=self.query('upload_1'))
        self.assert_edit(rv, quantity='references', success=True, message=False)
        rv = self.perform_edit(references=[], query=self.query('upload_1'))
        self.assert_edit(rv, quantity='references', success=True, message=False)
        assert self.mongo(1, references=[])
233
234

    def test_edit_duplicate_value(self, other_test_user):
235
236
        rv = self.perform_edit(references=['a', 'a'], query=self.query('upload_1'))
        self.assert_edit(rv, status_code=400, quantity='references', success=False, message=True)
237

238
    def test_edit_main_author_as_coauthor(self, test_user):
239
240
241
        pass
        # rv = self.perform_edit(entry_coauthors=[test_user.user_id], query=self.query('upload_1'))
        # self.assert_edit(rv, status_code=400, quantity='entry_coauthors', success=False, message=True)
242
243
244

    def test_edit_ds(self):
        rv = self.perform_edit(
245
            datasets=[self.example_dataset.dataset_name], query=self.query('upload_1'))
246
247
248
249
250
        self.assert_edit(rv, quantity='datasets', success=True, message=False)
        assert self.mongo(1, datasets=[self.example_dataset.dataset_id])

    def test_edit_ds_remove_doi(self):
        rv = self.perform_edit(
251
            datasets=[self.example_dataset.dataset_name], query=self.query('upload_1'))
252
253

        assert rv.status_code == 200
254
        rv = self.api.post('datasets/%s/action/doi' % self.example_dataset.dataset_name, headers=self.test_user_auth)
255
256
257
258
259
        assert rv.status_code == 200
        rv = self.perform_edit(datasets=[], query=self.query('upload_1'))
        assert rv.status_code == 400
        data = rv.json()
        assert not data['success']
260
        assert self.example_dataset.dataset_name in data['message']
261
262
263
264
        assert Dataset.m_def.a_mongo.get(dataset_id=self.example_dataset.dataset_id) is not None

    def test_edit_ds_remove(self):
        rv = self.perform_edit(
265
            datasets=[self.example_dataset.dataset_name], query=self.query('upload_1'))
266
267
268
269
270
271
272
273
        assert rv.status_code == 200
        rv = self.perform_edit(datasets=[], query=self.query('upload_1'))
        assert rv.status_code == 200
        with pytest.raises(KeyError):
            assert Dataset.m_def.a_mongo.get(dataset_id=self.example_dataset.dataset_id) is None

    def test_edit_ds_user_namespace(self, test_user):
        assert Dataset.m_def.a_mongo.objects(
274
            dataset_name=self.other_example_dataset.dataset_name).first() is not None
275
276

        rv = self.perform_edit(
277
            datasets=[self.other_example_dataset.dataset_name], query=self.query('upload_1'))
278
279
280

        self.assert_edit(rv, quantity='datasets', success=True, message=True)
        new_dataset = Dataset.m_def.a_mongo.objects(
281
            dataset_name=self.other_example_dataset.dataset_name,
282
283
284
285
286
287
288
            user_id=test_user.user_id).first()
        assert new_dataset is not None
        assert self.mongo(1, datasets=[new_dataset.dataset_id])

    def test_edit_new_ds(self, test_user):
        rv = self.perform_edit(datasets=['new_dataset'], query=self.query('upload_1'))
        self.assert_edit(rv, quantity='datasets', success=True, message=True)
289
        new_dataset = Dataset.m_def.a_mongo.objects(dataset_name='new_dataset').first()
290
291
292
293
294
        assert new_dataset is not None
        assert new_dataset.user_id == test_user.user_id
        assert self.mongo(1, datasets=[new_dataset.dataset_id])

    def test_edit_bad_user(self):
295
296
297
        pass
        # rv = self.perform_edit(entry_coauthors=['bad_user'], query=self.query('upload_1'))
        # self.assert_edit(rv, status_code=400, quantity='entry_coauthors', success=False, message=True)
298
299

    def test_edit_user(self, other_test_user):
300
301
302
        pass
        # rv = self.perform_edit(entry_coauthors=[other_test_user.user_id], query=self.query('upload_1'))
        # self.assert_edit(rv, quantity='entry_coauthors', success=True, message=False)
303

304
    @pytest.mark.skip(reason='Not necessary during transition. Fails because main_author is not editable anyways.')
305
    def test_admin_only(self, other_test_user):
306
        rv = self.perform_edit(main_author=other_test_user.user_id)
307
        assert rv.status_code != 200
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327


@pytest.mark.parametrize('user, kwargs', [
    pytest.param(
        'test_user', dict(
            query={'upload_id': 'id_unpublished_w'},
            metadata=all_coauthor_entry_metadata,
            affected_upload_ids=['id_unpublished_w']),
        id='edit-all'),
    pytest.param(
        'admin_user', dict(
            query={'upload_id': 'id_published_w'},
            owner='all',
            metadata=all_admin_entry_metadata,
            affected_upload_ids=['id_published_w']),
        id='protected-admin'),
    pytest.param(
        'test_user', dict(
            query={'upload_id': 'id_unpublished_w'},
            metadata=all_admin_entry_metadata,
328
            expected_error_loc=('metadata', 'entry_create_time')),
329
330
331
332
333
334
335
336
337
338
339
340
        id='protected-not-admin'),
    pytest.param(
        'admin_user', dict(
            query={'upload_id': 'id_published_w'},
            owner='all',
            metadata=dict(comment='test comment'),
            affected_upload_ids=['id_published_w']),
        id='published-admin'),
    pytest.param(
        'test_user', dict(
            query={'upload_id': 'id_published_w'},
            metadata=dict(comment='test comment'),
Mohammad Nakhaee's avatar
Mohammad Nakhaee committed
341
            affected_upload_ids=['id_published_w']),
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
        id='published-not-admin'),
    pytest.param(
        None, dict(
            owner='all',
            query={'upload_id': 'id_unpublished_w'},
            metadata=dict(comment='test comment'),
            expected_status_code=401),
        id='no-credentials'),
    pytest.param(
        'invalid', dict(
            owner='all',
            query={'upload_id': 'id_unpublished_w'},
            metadata=dict(comment='test comment'),
            expected_status_code=401),
        id='invalid-credentials'),
    pytest.param(
        'other_test_user', dict(
            query={'upload_id': 'id_unpublished_w'},
            metadata=dict(comment='test comment'),
361
            expected_error_loc=('query',)),
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
        id='no-access'),
    pytest.param(
        'other_test_user', dict(
            query={'upload_id': 'id_unpublished_w'},
            metadata=dict(comment='test comment'),
            affected_upload_ids=['id_unpublished_w'],
            add_coauthor=True),
        id='coauthor-access'),
    pytest.param(
        'test_user', dict(
            query={'and': [{'upload_create_time:gt': '2021-01-01'}, {'published': False}]},
            metadata=dict(comment='a test comment'),
            affected_upload_ids=['id_unpublished_w']),
        id='compound-query-ok'),
    pytest.param(
        'test_user', dict(
            query={'upload_id': 'id_unpublished_w'},
            metadata=dict(upload_name='a test name'),
380
            expected_error_loc=('metadata', 'upload_name')),
381
382
383
384
385
        id='query-cannot-edit-upload-data'),
    pytest.param(
        'test_user', dict(
            query={'upload_create_time:lt': '2021-01-01'},
            metadata=dict(comment='a test comment'),
386
            expected_error_loc=('query',)),
387
388
        id='query-no-results')])
def test_post_entries_edit(
389
        client, proc_infra, example_data_writeable, example_datasets, test_auth_dict, test_users_dict,
390
391
392
393
394
395
396
397
398
399
400
401
402
403
        user, kwargs):
    '''
    Note, since the endpoint basically just forwards the request to
    `MetadataEditRequestHandler.edit_metadata`, we only do very simple verification here,
    the more extensive testnig is done in `tests.processing.test_edit_metadata`.
    '''
    user_auth, _token = test_auth_dict[user]
    user = test_users_dict.get(user)
    query = kwargs.get('query')
    owner = kwargs.get('owner', 'visible')
    metadata = kwargs.get('metadata')
    entries = kwargs.get('entries')
    entries_key = kwargs.get('entries_key')
    verify_only = kwargs.get('verify_only', False)
404
405
406
407
    expected_error_loc = kwargs.get('expected_error_loc')
    expected_status_code = kwargs.get('expected_status_code')
    affected_upload_ids = kwargs.get('affected_upload_ids')
    expected_metadata = kwargs.get('expected_metadata', metadata)
408
409
410
411
412
413
414
415
416
417
418
419
420
421

    add_coauthor = kwargs.get('add_coauthor', False)
    if add_coauthor:
        upload = proc.Upload.get(affected_upload_ids[0])
        upload.edit_upload_metadata(
            edit_request_json={'metadata': {'coauthors': user.user_id}}, user_id=upload.main_author)
        upload.block_until_complete()

    edit_request_json = dict(
        query=query, owner=owner, metadata=metadata, entries=entries, entries_key=entries_key,
        verify_only=verify_only)
    url = 'entries/edit'
    edit_start = datetime.utcnow().isoformat()[0:22]
    response = client.post(url, headers=user_auth, json=edit_request_json)
422
423
424
425
426
427
428
429
    if expected_error_loc:
        assert_response(response, 422)
        error_locs = [tuple(d['loc']) for d in response.json()['detail']]
        assert expected_error_loc in error_locs
    elif expected_status_code not in (None, 200):
        assert_response(response, expected_status_code)
    else:
        assert_response(response, 200)
430
431
        assert_metadata_edited(
            user, None, query, metadata, entries, entries_key, verify_only,
432
            expected_metadata, affected_upload_ids, edit_start)