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

10
11
12
13
14
15
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)

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

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

22
# import fixtures
23
from tests.test_files import clear_files, archive, archive_config  # noqa pylint: disable=unused-import
24
25
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
26
from tests.test_repo import example_elastic_calc  # noqa pylint: disable=unused-import
27

28

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

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

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


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


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


55
56
57
58
59
60
61
62
63
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)


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

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

76
77
78
    return data


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

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


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


91
def test_stale_upload(client, test_user_auth):
92
93
    rv = client.post(
        '/uploads',
94
        headers=test_user_auth,
95
96
97
98
99
        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
100
    upload = Upload.get(upload_id)
101
102
103
    upload.create_time = datetime.now() - timedelta(days=2)
    upload.save()

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


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

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

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

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


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


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

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

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

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


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

155
156
    upload_cmd = upload['upload_command']
    headers = dict(Authorization='Basic %s' % re.search(r'.*-HAuthorization: Basic ([^\s]+).*', upload_cmd).group(1))
157
158
    upload_endpoint = '/uploads/%s' % upload_id
    upload_file_endpoint = '%s/file' % upload_endpoint
159

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

    while True:
176
        time.sleep(0.1)
177

178
        rv = client.get(upload_endpoint, headers=test_user_auth)
179
180
181
        assert rv.status_code == 200
        upload = assert_upload(rv.data)
        assert 'upload_time' in upload
Markus Scheidgen's avatar
Markus Scheidgen committed
182
        if upload['completed']:
Markus Scheidgen's avatar
Markus Scheidgen committed
183
            break
184

Markus Scheidgen's avatar
Markus Scheidgen committed
185
186
187
    assert len(upload['tasks']) == 4
    assert upload['status'] == 'SUCCESS'
    assert upload['current_task'] == 'cleanup'
188
    calcs = upload['calcs']['results']
Markus Scheidgen's avatar
Markus Scheidgen committed
189
190
191
192
    for calc in calcs:
        assert calc['status'] == 'SUCCESS'
        assert calc['current_task'] == 'archiving'
        assert len(calc['tasks']) == 3
193
        assert UploadFile(upload['upload_id']).exists()
Markus Scheidgen's avatar
Markus Scheidgen committed
194

195
    if upload['calcs']['pagination']['total'] > 1:
196
        rv = client.get('%s?page=2&per_page=1&order_by=status' % upload_endpoint)
197
198
199
200
        assert rv.status_code == 200
        upload = assert_upload(rv.data)
        assert len(upload['calcs']['results']) == 1

Markus Scheidgen's avatar
Markus Scheidgen committed
201
    rv = client.post(
202
        upload_endpoint,
Markus Scheidgen's avatar
Markus Scheidgen committed
203
204
205
206
207
208
209
210
        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)
211
212


213
def test_repo_calc(client, example_elastic_calc, no_warn):
Markus Scheidgen's avatar
Markus Scheidgen committed
214
215
    rv = client.get(
        '/repo/%s/%s' % (example_elastic_calc.upload_hash, example_elastic_calc.calc_hash))
216
217
218
    assert rv.status_code == 200


219
def test_non_existing_repo_cals(client, no_warn):
220
221
222
223
    rv = client.get('/repo/doesnt/exist')
    assert rv.status_code == 404


224
def test_repo_calcs(client, example_elastic_calc, no_warn):
225
226
227
228
229
230
231
232
233
    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


234
def test_repo_calcs_pagination(client, example_elastic_calc, no_warn):
235
236
237
238
239
240
241
242
243
    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


244
def test_repo_calcs_user(client, example_elastic_calc, test_user_auth, no_warn):
245
246
247
248
249
250
251
252
    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


253
def test_repo_calcs_user_authrequired(client, example_elastic_calc, no_warn):
254
255
256
257
    rv = client.get('/repo?owner=user')
    assert rv.status_code == 401


258
def test_repo_calcs_user_invisible(client, example_elastic_calc, test_other_user_auth, no_warn):
259
260
261
262
263
264
265
266
    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


267
268
269
def test_get_archive(client, archive, no_warn):
    rv = client.get('/archive/%s' % archive.object_id)
    assert rv.status_code == 200
270
271


272
def test_get_non_existing_archive(client, no_warn):
273
274
    rv = client.get('/archive/%s' % 'doesnt/exist')
    assert rv.status_code == 404