test_api.py 8.42 KB
Newer Older
1
2
3
4
5
import pytest
import time
import json
from mongoengine import connect
from mongoengine.connection import disconnect
6
from datetime import datetime, timedelta
7
import base64
8

9
10
11
12
13
14
from nomad import config
# for convinience we test the api without path prefix
services_config = config.services._asdict()
services_config.update(api_base_path='')
config.services = config.NomadServicesConfig(**services_config)

15
16
17
from nomad import api  # noqa
from nomad.files import UploadFile  # noqa
from nomad.processing import Upload  # noqa
18

Markus Scheidgen's avatar
Markus Scheidgen committed
19
from tests.processing.test_data import example_files  # noqa
20

21
# import fixtures
22
from tests.test_files import clear_files, archive, archive_config  # noqa pylint: disable=unused-import
23
24
from tests.test_normalizing import normalized_template_example  # noqa pylint: disable=unused-import
from tests.test_parsing import parsed_template_example  # noqa pylint: disable=unused-import
Markus Scheidgen's avatar
Markus Scheidgen committed
25
from tests.test_repo import example_elastic_calc  # noqa pylint: disable=unused-import
26

27

28
@pytest.fixture(scope='function')
29
def client(mockmongo):
30
    disconnect()
Markus Scheidgen's avatar
Markus Scheidgen committed
31
    connect('users_test', host=config.mongo.host, port=config.mongo.port, is_mock=True)
32
33
34
35
36

    api.app.config['TESTING'] = True
    client = api.app.test_client()

    yield client
37
    Upload._get_collection().drop()
38
39


40
41
42
43
44
45
46
@pytest.fixture(scope='session')
def test_user_auth():
    return {
        'Authorization': 'Basic %s' % base64.b64encode(b'me@gmail.com:nomad').decode('utf-8')
    }


47
48
49
50
51
52
53
@pytest.fixture(scope='session')
def test_other_user_auth():
    return {
        'Authorization': 'Basic %s' % base64.b64encode(b'other@gmail.com:nomad').decode('utf-8')
    }


54
55
56
57
58
59
60
61
62
def assert_uploads(upload_json_str, count=0, **kwargs):
    data = json.loads(upload_json_str)
    assert isinstance(data, list)
    assert len(data) == count

    if count > 0:
        assert_upload(json.dumps(data[0]), **kwargs)


63
def assert_upload(upload_json_str, id=None, **kwargs):
64
    data = json.loads(upload_json_str)
Markus Scheidgen's avatar
Markus Scheidgen committed
65
    assert 'upload_id' in data
66
    if id is not None:
Markus Scheidgen's avatar
Markus Scheidgen committed
67
        assert id == data['upload_id']
68
69
    assert 'create_time' in data
    assert 'presigned_url' in data
70
    assert 'upload_command' in data
71

72
73
74
    for key, value in kwargs.items():
        assert data.get(key, None) == value

75
76
77
    return data


78
def test_no_uploads(client, test_user_auth, no_warn):
79
    rv = client.get('/uploads', headers=test_user_auth)
80
81
82
83
84

    assert rv.status_code == 200
    assert_uploads(rv.data, count=0)


85
def test_not_existing_upload(client, test_user_auth, no_warn):
86
    rv = client.get('/uploads/123456789012123456789012', headers=test_user_auth)
87
88
89
    assert rv.status_code == 404


90
def test_stale_upload(client, test_user_auth):
91
92
    rv = client.post(
        '/uploads',
93
        headers=test_user_auth,
94
95
96
97
98
        data=json.dumps(dict(name='test_name')),
        content_type='application/json')
    assert rv.status_code == 200
    upload_id = assert_upload(rv.data)['upload_id']

Markus Scheidgen's avatar
Markus Scheidgen committed
99
    upload = Upload.get(upload_id)
100
101
102
    upload.create_time = datetime.now() - timedelta(days=2)
    upload.save()

103
    rv = client.get('/uploads/%s' % upload_id, headers=test_user_auth)
104
105
106
107
    assert rv.status_code == 200
    assert_upload(rv.data, is_stale=True)


108
def test_create_upload(client, test_user_auth, no_warn):
109
    rv = client.post('/uploads', headers=test_user_auth)
110
111

    assert rv.status_code == 200
Markus Scheidgen's avatar
Markus Scheidgen committed
112
    upload_id = assert_upload(rv.data)['upload_id']
113

114
    rv = client.get('/uploads/%s' % upload_id, headers=test_user_auth)
115
    assert rv.status_code == 200
116
    assert_upload(rv.data, id=upload_id, is_stale=False)
117

118
    rv = client.get('/uploads', headers=test_user_auth)
119
120
121
122
    assert rv.status_code == 200
    assert_uploads(rv.data, count=1, id=upload_id)


123
def test_create_upload_with_name(client, test_user_auth, no_warn):
124
    rv = client.post(
125
126
        '/uploads', headers=test_user_auth,
        data=json.dumps(dict(name='test_name')), content_type='application/json')
127
128
129
130
131
    assert rv.status_code == 200
    upload = assert_upload(rv.data)
    assert upload['name'] == 'test_name'


132
def test_delete_empty_upload(client, test_user_auth, no_warn):
133
    rv = client.post('/uploads', headers=test_user_auth)
Markus Scheidgen's avatar
Markus Scheidgen committed
134
135
136
137

    assert rv.status_code == 200
    upload_id = assert_upload(rv.data)['upload_id']

138
    rv = client.delete('/uploads/%s' % upload_id, headers=test_user_auth)
Markus Scheidgen's avatar
Markus Scheidgen committed
139
140
    assert rv.status_code == 200

141
    rv = client.get('/uploads/%s' % upload_id, headers=test_user_auth)
Markus Scheidgen's avatar
Markus Scheidgen committed
142
143
144
    assert rv.status_code == 404


145
146
@pytest.mark.parametrize('file', example_files)
@pytest.mark.parametrize('mode', ['multipart', 'stream'])
Markus Scheidgen's avatar
Markus Scheidgen committed
147
@pytest.mark.timeout(10)
148
def test_processing(client, file, mode, worker, mocksearch, test_user_auth, no_warn):
149
    rv = client.post('/uploads', headers=test_user_auth)
150
151
    assert rv.status_code == 200
    upload = assert_upload(rv.data)
152
    upload_id = upload['upload_id']
153
154

    upload_url = upload['presigned_url']
155
156
    upload_endpoint = '/uploads/%s' % upload_id
    upload_file_endpoint = '%s/file' % upload_endpoint
157

158
    assert upload_url.endswith(upload_file_endpoint)
159
160
161
162
163
164
165
    if mode == 'multipart':
        rv = client.put(upload_file_endpoint, data=dict(file=(open(file, 'rb'), 'file')))
    elif mode == 'stream':
        with open(file, 'rb') as f:
            rv = client.put(upload_file_endpoint, data=f.read())
    else:
        assert False
166
167
    assert rv.status_code == 200
    upload = assert_upload(rv.data)
168
169

    while True:
170
        time.sleep(0.1)
171

172
        rv = client.get(upload_endpoint, headers=test_user_auth)
173
174
175
        assert rv.status_code == 200
        upload = assert_upload(rv.data)
        assert 'upload_time' in upload
Markus Scheidgen's avatar
Markus Scheidgen committed
176
        if upload['completed']:
Markus Scheidgen's avatar
Markus Scheidgen committed
177
            break
178

Markus Scheidgen's avatar
Markus Scheidgen committed
179
180
181
    assert len(upload['tasks']) == 4
    assert upload['status'] == 'SUCCESS'
    assert upload['current_task'] == 'cleanup'
182
    calcs = upload['calcs']['results']
Markus Scheidgen's avatar
Markus Scheidgen committed
183
184
185
186
    for calc in calcs:
        assert calc['status'] == 'SUCCESS'
        assert calc['current_task'] == 'archiving'
        assert len(calc['tasks']) == 3
187
        assert UploadFile(upload['upload_id']).exists()
Markus Scheidgen's avatar
Markus Scheidgen committed
188

189
    if upload['calcs']['pagination']['total'] > 1:
190
        rv = client.get('%s?page=2&per_page=1&order_by=status' % upload_endpoint)
191
192
193
194
        assert rv.status_code == 200
        upload = assert_upload(rv.data)
        assert len(upload['calcs']['results']) == 1

Markus Scheidgen's avatar
Markus Scheidgen committed
195
    rv = client.post(
196
        upload_endpoint,
Markus Scheidgen's avatar
Markus Scheidgen committed
197
198
199
200
201
202
203
204
        headers=test_user_auth,
        data=json.dumps(dict(operation='unstage')),
        content_type='application/json')
    assert rv.status_code == 200

    rv = client.get('/uploads', headers=test_user_auth)
    assert rv.status_code == 200
    assert_uploads(rv.data, count=0)
205
206


207
def test_repo_calc(client, example_elastic_calc, no_warn):
Markus Scheidgen's avatar
Markus Scheidgen committed
208
209
    rv = client.get(
        '/repo/%s/%s' % (example_elastic_calc.upload_hash, example_elastic_calc.calc_hash))
210
211
212
    assert rv.status_code == 200


213
def test_non_existing_repo_cals(client, no_warn):
214
215
216
217
    rv = client.get('/repo/doesnt/exist')
    assert rv.status_code == 404


218
def test_repo_calcs(client, example_elastic_calc, no_warn):
219
220
221
222
223
224
225
226
227
    rv = client.get('/repo')
    assert rv.status_code == 200
    data = json.loads(rv.data)
    results = data.get('results', None)
    assert results is not None
    assert isinstance(results, list)
    assert len(results) >= 1


228
def test_repo_calcs_pagination(client, example_elastic_calc, no_warn):
229
230
231
232
233
234
235
236
237
    rv = client.get('/repo?page=1&per_page=1')
    assert rv.status_code == 200
    data = json.loads(rv.data)
    results = data.get('results', None)
    assert results is not None
    assert isinstance(results, list)
    assert len(results) == 1


238
def test_repo_calcs_user(client, example_elastic_calc, test_user_auth, no_warn):
239
240
241
242
243
244
245
246
    rv = client.get('/repo?owner=user', headers=test_user_auth)
    assert rv.status_code == 200
    data = json.loads(rv.data)
    results = data.get('results', None)
    assert results is not None
    assert len(results) >= 1


247
def test_repo_calcs_user_authrequired(client, example_elastic_calc, no_warn):
248
249
250
251
    rv = client.get('/repo?owner=user')
    assert rv.status_code == 401


252
def test_repo_calcs_user_invisible(client, example_elastic_calc, test_other_user_auth, no_warn):
253
254
255
256
257
258
259
260
    rv = client.get('/repo?owner=user', headers=test_other_user_auth)
    assert rv.status_code == 200
    data = json.loads(rv.data)
    results = data.get('results', None)
    assert results is not None
    assert len(results) == 0


261
262
263
def test_get_archive(client, archive, no_warn):
    rv = client.get('/archive/%s' % archive.object_id)
    assert rv.status_code == 200
264
265


266
def test_get_non_existing_archive(client, no_warn):
267
268
    rv = client.get('/archive/%s' % 'doesnt/exist')
    assert rv.status_code == 404