test_api.py 29.3 KB
Newer Older
Markus Scheidgen's avatar
Markus Scheidgen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2018 Markus Scheidgen
#
# 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.

15
16
17
import pytest
import time
import json
18
import base64
19
20
import zipfile
import io
21
import inspect
22
from passlib.hash import bcrypt
23

24
from nomad import config, coe_repo, search, parsing
25
26
from nomad.files import UploadFiles, PublicUploadFiles
from nomad.processing import Upload, Calc, SUCCESS
27

28
from tests.conftest import create_auth_headers, clear_elastic
29
30
31
from tests.test_files import example_file, example_file_mainfile, example_file_contents
from tests.test_files import create_staging_upload, create_public_upload
from tests.test_coe_repo import assert_coe_upload
32
33


34
35
36
37
38
def test_alive(client):
    rv = client.get('/alive')
    assert rv.status_code == 200


39
40
41
42
43
44
45
@pytest.fixture(scope='function')
def test_user_signature_token(client, test_user_auth):
    rv = client.get('/auth/token', headers=test_user_auth)
    assert rv.status_code == 200
    return json.loads(rv.data)['token']


46
class TestAdmin:
47
48

    @pytest.mark.timeout(10)
49
    def test_reset(self, client, admin_user_auth, expandable_postgres):
50
51
52
        rv = client.post('/admin/reset', headers=admin_user_auth)
        assert rv.status_code == 200

53
    @pytest.mark.timeout(10)
54
    def test_remove(self, client, admin_user_auth, expandable_postgres):
55
56
        rv = client.post('/admin/remove', headers=admin_user_auth)
        assert rv.status_code == 200
57
58
59
60
61
62

    def test_doesnotexist(self, client, admin_user_auth):
        rv = client.post('/admin/doesnotexist', headers=admin_user_auth)
        assert rv.status_code == 404

    def test_only_admin(self, client, test_user_auth):
Markus Scheidgen's avatar
Markus Scheidgen committed
63
        rv = client.post('/admin/reset', headers=test_user_auth)
64
65
66
67
68
69
70
71
72
73
74
        assert rv.status_code == 401

    @pytest.fixture(scope='function')
    def disable_reset(self, monkeypatch):
        old_config = config.services
        new_config = config.NomadServicesConfig(
            config.services.api_host,
            config.services.api_port,
            config.services.api_base_path,
            config.services.api_secret,
            config.services.admin_password,
75
            config.services.upload_url,
76
77
78
79
80
            True)
        monkeypatch.setattr(config, 'services', new_config)
        yield None
        monkeypatch.setattr(config, 'services', old_config)

81
    def test_disabled(self, client, admin_user_auth, disable_reset, postgres):
82
83
84
85
        rv = client.post('/admin/reset', headers=admin_user_auth)
        assert rv.status_code == 400


86
class TestAuth:
87
    def test_xtoken_auth(self, client, test_user: coe_repo.User, no_warn):
88
        rv = client.get('/uploads/', headers={
89
            'X-Token': test_user.first_name.lower()  # the test users have their firstname as tokens for convinience
90
        })
91

92
        assert rv.status_code == 200
Markus Scheidgen's avatar
Markus Scheidgen committed
93

94
    def test_xtoken_auth_denied(self, client, no_warn, postgres):
95
96
97
        rv = client.get('/uploads/', headers={
            'X-Token': 'invalid'
        })
Markus Scheidgen's avatar
Markus Scheidgen committed
98

99
        assert rv.status_code == 401
100

101
102
103
    def test_basic_auth(self, client, test_user_auth, no_warn):
        rv = client.get('/uploads/', headers=test_user_auth)
        assert rv.status_code == 200
104

105
106
107
108
109
110
111
    def test_basic_auth_denied(self, client, no_warn):
        basic_auth_base64 = base64.b64encode('invalid'.encode('utf-8')).decode('utf-8')
        rv = client.get('/uploads/', headers={
            'Authorization': 'Basic %s' % basic_auth_base64
        })
        assert rv.status_code == 401

112
    def test_get_user(self, client, test_user_auth, test_user: coe_repo.User, no_warn):
113
114
        rv = client.get('/auth/user', headers=test_user_auth)
        assert rv.status_code == 200
115
116
117
        self.assert_user(client, json.loads(rv.data))

    def assert_user(self, client, user):
118
119
120
121
122
123
124
        for key in ['first_name', 'last_name', 'email', 'token']:
            assert key in user

        rv = client.get('/uploads/', headers={
            'X-Token': user['token']
        })

125
126
        assert rv.status_code == 200

127
128
129
    def test_signature_token(self, test_user_signature_token, no_warn):
        assert test_user_signature_token is not None

130
131
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
    def test_put_user(self, client, postgres, admin_user_auth):
        rv = client.put(
            '/auth/user', headers=admin_user_auth,
            content_type='application/json', data=json.dumps(dict(
                email='test@email.com', last_name='Tester', first_name='Testi',
                password=bcrypt.encrypt('test_password', ident='2y'))))

        assert rv.status_code == 200
        self.assert_user(client, json.loads(rv.data))

    def test_put_user_admin_only(self, client, test_user_auth):
        rv = client.put(
            '/auth/user', headers=test_user_auth,
            content_type='application/json', data=json.dumps(dict(
                email='test@email.com', last_name='Tester', first_name='Testi',
                password=bcrypt.encrypt('test_password', ident='2y'))))
        assert rv.status_code == 401

    def test_put_user_required_field(self, client, admin_user_auth):
        rv = client.put(
            '/auth/user', headers=admin_user_auth,
            content_type='application/json', data=json.dumps(dict(
                email='test@email.com', password=bcrypt.encrypt('test_password', ident='2y'))))
        assert rv.status_code == 400

    def test_post_user(self, client, postgres, admin_user_auth):
        rv = client.put(
            '/auth/user', headers=admin_user_auth,
            content_type='application/json', data=json.dumps(dict(
                email='test@email.com', last_name='Tester', first_name='Testi',
                password=bcrypt.encrypt('test_password', ident='2y'))))

        assert rv.status_code == 200
        user = json.loads(rv.data)

        rv = client.post(
            '/auth/user', headers={'X-Token': user['token']},
            content_type='application/json', data=json.dumps(dict(
                last_name='Tester', first_name='Testi v.',
                password=bcrypt.encrypt('test_password_changed', ident='2y'))))
        assert rv.status_code == 200
        self.assert_user(client, json.loads(rv.data))

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205

class TestUploads:

    def assert_uploads(self, upload_json_str, count=0, **kwargs):
        data = json.loads(upload_json_str)
        assert isinstance(data, list)
        assert len(data) == count

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

    def assert_upload(self, upload_json_str, id=None, **kwargs):
        data = json.loads(upload_json_str)
        assert 'upload_id' in data
        if id is not None:
            assert id == data['upload_id']
        assert 'create_time' in data

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

        return data

    def assert_processing(self, client, test_user_auth, upload_id):
        upload_endpoint = '/uploads/%s' % upload_id

        # poll until completed
        while True:
            time.sleep(0.1)
            rv = client.get(upload_endpoint, headers=test_user_auth)
            assert rv.status_code == 200
            upload = self.assert_upload(rv.data)
            assert 'upload_time' in upload
206
            if not upload['tasks_running']:
207
208
209
                break

        assert len(upload['tasks']) == 4
210
        assert upload['tasks_status'] == SUCCESS
211
        assert upload['current_task'] == 'cleanup'
212
        assert not upload['process_running']
213
214
        upload_files = UploadFiles.get(upload['upload_id'])
        assert upload_files is not None
215
216
        calcs = upload['calcs']['results']
        for calc in calcs:
217
            assert calc['tasks_status'] == SUCCESS
218
219
            assert calc['current_task'] == 'archiving'
            assert len(calc['tasks']) == 3
220
            assert client.get('/archive/logs/%s/%s' % (calc['upload_id'], calc['calc_id']), headers=test_user_auth).status_code == 200
221
222

        if upload['calcs']['pagination']['total'] > 1:
223
            rv = client.get('%s?page=2&per_page=1&order_by=tasks_status' % upload_endpoint, headers=test_user_auth)
224
225
226
227
            assert rv.status_code == 200
            upload = self.assert_upload(rv.data)
            assert len(upload['calcs']['results']) == 1

228
    def assert_unstage(self, client, test_user_auth, upload_id, proc_infra, metadata={}):
229
230
231
        rv = client.get('/uploads/%s' % upload_id, headers=test_user_auth)
        upload = self.assert_upload(rv.data)

232
233
234
        rv = client.post(
            '/uploads/%s' % upload_id,
            headers=test_user_auth,
235
            data=json.dumps(dict(operation='publish', metadata=metadata)),
236
            content_type='application/json')
237
        assert rv.status_code == 200
238
        upload = self.assert_upload(rv.data)
239
        assert upload['current_process'] == 'publish_upload'
240
        assert upload['process_running']
241

242
        self.assert_upload_does_not_exist(client, upload_id, test_user_auth)
243
        assert_coe_upload(upload_id, user_metadata=metadata)
244
245

    def assert_upload_does_not_exist(self, client, upload_id: str, test_user_auth):
246
        # poll until publish/delete completed
247
248
249
250
251
252
253
254
255
256
257
        while True:
            time.sleep(0.1)
            rv = client.get('/uploads/%s' % upload_id, headers=test_user_auth)
            if rv.status_code == 200:
                upload = self.assert_upload(rv.data)
                assert upload['process_running']
            elif rv.status_code == 404:
                break
            else:
                assert False

258
259
260
261
262
263
        rv = client.get('/uploads/%s' % upload_id, headers=test_user_auth)
        assert rv.status_code == 404
        assert Upload.objects(upload_id=upload_id).first() is None
        assert Calc.objects(upload_id=upload_id).count() is 0
        upload_files = UploadFiles.get(upload_id)
        assert upload_files is None or isinstance(upload_files, PublicUploadFiles)
Markus Scheidgen's avatar
Markus Scheidgen committed
264

265
266
267
268
269
270
271
    def test_get_command(self, client, test_user_auth, no_warn):
        rv = client.get('/uploads/command', headers=test_user_auth)
        assert rv.status_code == 200
        data = json.loads(rv.data)
        assert 'upload_command' in data
        assert 'upload_url' in data

272
273
    def test_get_empty(self, client, test_user_auth, no_warn):
        rv = client.get('/uploads/', headers=test_user_auth)
Markus Scheidgen's avatar
Markus Scheidgen committed
274

275
276
        assert rv.status_code == 200
        self.assert_uploads(rv.data, count=0)
Markus Scheidgen's avatar
Markus Scheidgen committed
277

278
279
280
    def test_get_not_existing(self, client, test_user_auth, no_warn):
        rv = client.get('/uploads/123456789012123456789012', headers=test_user_auth)
        assert rv.status_code == 404
281

282
283
    @pytest.mark.parametrize('mode', ['multipart', 'stream', 'local_path'])
    @pytest.mark.parametrize('name', [None, 'test_name'])
Markus Scheidgen's avatar
Markus Scheidgen committed
284
    def test_put(self, client, test_user_auth, proc_infra, example_upload, mode, name, no_warn):
285
        file = example_upload
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
        if name:
            url = '/uploads/?name=%s' % name
        else:
            url = '/uploads/'

        if mode == 'multipart':
            rv = client.put(
                url, data=dict(file=(open(file, 'rb'), 'file')), headers=test_user_auth)
        elif mode == 'stream':
            with open(file, 'rb') as f:
                rv = client.put(url, data=f.read(), headers=test_user_auth)
        elif mode == 'local_path':
            url += '&' if name else '?'
            url += 'local_path=%s' % file
            rv = client.put(url, headers=test_user_auth)
        else:
            assert False
303

304
305
306
307
308
        assert rv.status_code == 200
        if mode == 'local_path':
            upload = self.assert_upload(rv.data, local_path=file, name=name)
        else:
            upload = self.assert_upload(rv.data, name=name)
309
        assert upload['tasks_running']
310

311
        self.assert_processing(client, test_user_auth, upload['upload_id'])
312

313
314
315
    def test_delete_not_existing(self, client, test_user_auth, no_warn):
        rv = client.delete('/uploads/123456789012123456789012', headers=test_user_auth)
        assert rv.status_code == 404
316

317
318
319
320
321
322
323
324
325
326
327
328
    @pytest.fixture(scope='function')
    def slow_processing(self, monkeypatch):
        old_cleanup = Upload.cleanup

        def slow_cleanup(self):
            time.sleep(0.5)
            old_cleanup(self)

        monkeypatch.setattr('nomad.processing.data.Upload.cleanup', slow_cleanup)
        yield True
        monkeypatch.setattr('nomad.processing.data.Upload.cleanup', old_cleanup)

Markus Scheidgen's avatar
Markus Scheidgen committed
329
    def test_delete_during_processing(self, client, test_user_auth, proc_infra, slow_processing, no_warn):
330
331
        rv = client.put('/uploads/?local_path=%s' % example_file, headers=test_user_auth)
        upload = self.assert_upload(rv.data)
332
        assert upload['tasks_running']
333
334
335
336
        rv = client.delete('/uploads/%s' % upload['upload_id'], headers=test_user_auth)
        assert rv.status_code == 400
        self.assert_processing(client, test_user_auth, upload['upload_id'])

Markus Scheidgen's avatar
Markus Scheidgen committed
337
    def test_delete_unstaged(self, client, test_user_auth, proc_infra, no_warn):
338
339
340
341
342
        rv = client.put('/uploads/?local_path=%s' % example_file, headers=test_user_auth)
        upload = self.assert_upload(rv.data)
        self.assert_processing(client, test_user_auth, upload['upload_id'])
        self.assert_unstage(client, test_user_auth, upload['upload_id'], proc_infra)
        rv = client.delete('/uploads/%s' % upload['upload_id'], headers=test_user_auth)
343
        assert rv.status_code == 404
344

Markus Scheidgen's avatar
Markus Scheidgen committed
345
    def test_delete(self, client, test_user_auth, proc_infra, no_warn):
346
347
348
349
350
        rv = client.put('/uploads/?local_path=%s' % example_file, headers=test_user_auth)
        upload = self.assert_upload(rv.data)
        self.assert_processing(client, test_user_auth, upload['upload_id'])
        rv = client.delete('/uploads/%s' % upload['upload_id'], headers=test_user_auth)
        assert rv.status_code == 200
351
        self.assert_upload_does_not_exist(client, upload['upload_id'], test_user_auth)
352

Markus Scheidgen's avatar
Markus Scheidgen committed
353
    def test_post(self, client, test_user_auth, example_upload, proc_infra, no_warn):
354
        rv = client.put('/uploads/?local_path=%s' % example_upload, headers=test_user_auth)
355
356
357
        upload = self.assert_upload(rv.data)
        self.assert_processing(client, test_user_auth, upload['upload_id'])
        self.assert_unstage(client, test_user_auth, upload['upload_id'], proc_infra)
358

359
360
    def test_post_metadata(
            self, client, proc_infra, admin_user_auth, test_user_auth, test_user,
Markus Scheidgen's avatar
Markus Scheidgen committed
361
            other_test_user, no_warn):
362
363
364
        rv = client.put('/uploads/?local_path=%s' % example_file, headers=test_user_auth)
        upload = self.assert_upload(rv.data)
        self.assert_processing(client, test_user_auth, upload['upload_id'])
365
366
        metadata = dict(comment='test comment')
        self.assert_unstage(client, admin_user_auth, upload['upload_id'], proc_infra, metadata)
367

Markus Scheidgen's avatar
Markus Scheidgen committed
368
    def test_post_metadata_forbidden(self, client, proc_infra, test_user_auth, no_warn):
369
370
371
372
373
374
        rv = client.put('/uploads/?local_path=%s' % example_file, headers=test_user_auth)
        upload = self.assert_upload(rv.data)
        self.assert_processing(client, test_user_auth, upload['upload_id'])
        rv = client.post(
            '/uploads/%s' % upload['upload_id'],
            headers=test_user_auth,
375
            data=json.dumps(dict(operation='publish', metadata=dict(_pid=256))),
376
377
378
379
            content_type='application/json')
        assert rv.status_code == 401

    # TODO validate metadata (or all input models in API for that matter)
380
    # def test_post_bad_metadata(self, client, proc_infra, test_user_auth, postgres):
381
382
383
384
385
386
    #     rv = client.put('/uploads/?local_path=%s' % example_file, headers=test_user_auth)
    #     upload = self.assert_upload(rv.data)
    #     self.assert_processing(client, test_user_auth, upload['upload_id'])
    #     rv = client.post(
    #         '/uploads/%s' % upload['upload_id'],
    #         headers=test_user_auth,
387
    #         data=json.dumps(dict(operation='publish', metadata=dict(doesnotexist='hi'))),
388
389
390
    #         content_type='application/json')
    #     assert rv.status_code == 400

391

392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
class UploadFilesBasedTests:

    @staticmethod
    def fix_signature(func, wrapper):
        additional_args = list(inspect.signature(func).parameters.values())[4:]
        wrapper_sig = inspect.signature(wrapper)
        wrapper_args = list(wrapper_sig.parameters.values())[:3] + additional_args
        wrapper_sig = wrapper_sig.replace(parameters=tuple(wrapper_args))
        wrapper.__signature__ = wrapper_sig

    @staticmethod
    def check_authorizaton(func):
        @pytest.mark.parametrize('test_data', [
            [True, None, True],     # in staging for upload
            [True, None, False],    # in staging for different user
            [True, None, None],     # in staging for guest
            [False, True, True],    # in public, restricted for uploader
            [False, True, False],   # in public, restricted for different user
            [False, True, None],    # in public, restricted for guest
            [False, False, True],   # in public, public, for uploader
            [False, False, False],  # in public, public, for different user
            [False, False, None]    # in public, public, for guest
        ], indirect=True)
        def wrapper(self, client, test_data, *args, **kwargs):
            upload, authorized, auth_headers = test_data
            try:
                func(self, client, upload, auth_headers, *args, **kwargs)
            except AssertionError as assertion:
                assertion_str = str(assertion)
                if not authorized:
                    if '0 == 5' in assertion_str and 'ZipFile' in assertion_str:
                        # the user is not authorized an gets an empty zip as expected
                        return
                    if '401' in assertion_str:
                        # the user is not authorized and gets a 401 as expected
                        return
                raise assertion

            if not authorized:
                assert False
        UploadFilesBasedTests.fix_signature(func, wrapper)
        return wrapper

    @staticmethod
    def ignore_authorization(func):
        @pytest.mark.parametrize('test_data', [
            [True, None, True],      # in staging
            [False, False, None],    # in public
        ], indirect=True)
        def wrapper(self, client, test_data, *args, **kwargs):
            upload, _, auth_headers = test_data
            func(self, client, upload, auth_headers, *args, **kwargs)
        UploadFilesBasedTests.fix_signature(func, wrapper)
        return wrapper
446

447
    @pytest.fixture(scope='function')
448
    def test_data(self, request, postgres, mongo, no_warn, test_user, other_test_user):
449
450
451
452
453
        # delete potential old test files
        for _ in [0, 1]:
            upload_files = UploadFiles.get('test_upload')
            if upload_files:
                upload_files.delete()
454

455
        in_staging, restricted, for_uploader = request.param
456

457
458
459
460
        if in_staging:
            authorized = for_uploader
        else:
            authorized = not restricted or for_uploader
461

462
463
464
465
466
467
        if for_uploader:
            auth_headers = create_auth_headers(test_user)
        elif for_uploader is False:
            auth_headers = create_auth_headers(other_test_user)
        else:
            auth_headers = None
468

469
470
        calc_specs = 'r' if restricted else 'p'
        if in_staging:
471
            Upload.create(user=test_user, upload_id='test_upload')
472
473
474
            upload_files = create_staging_upload('test_upload', calc_specs=calc_specs)
        else:
            upload_files = create_public_upload('test_upload', calc_specs=calc_specs)
475
            postgres.begin()
476
477
478
            coe_upload = coe_repo.Upload(
                upload_name='test_upload',
                user_id=test_user.user_id, is_processed=True)
479
480
            postgres.add(coe_upload)
            postgres.commit()
481

482
        yield 'test_upload', authorized, auth_headers
483

484
        upload_files.delete()
485
486


487
488
489
490
class TestArchive(UploadFilesBasedTests):
    @UploadFilesBasedTests.check_authorizaton
    def test_get(self, client, upload, auth_headers):
        rv = client.get('/archive/%s/0' % upload, headers=auth_headers)
491
        assert rv.status_code == 200
492
        assert json.loads(rv.data) is not None
493

494
495
496
497
498
499
    @UploadFilesBasedTests.ignore_authorization
    def test_get_signed(self, client, upload, _, test_user_signature_token):
        rv = client.get('/archive/%s/0?token=%s' % (upload, test_user_signature_token))
        assert rv.status_code == 200
        assert json.loads(rv.data) is not None

500
501
502
    @UploadFilesBasedTests.check_authorizaton
    def test_get_calc_proc_log(self, client, upload, auth_headers):
        rv = client.get('/archive/logs/%s/0' % upload, headers=auth_headers)
503
        assert rv.status_code == 200
504
        assert len(rv.data) > 0
505

506
507
508
509
510
511
    @UploadFilesBasedTests.ignore_authorization
    def test_get_calc_proc_log_signed(self, client, upload, _, test_user_signature_token):
        rv = client.get('/archive/logs/%s/0?token=%s' % (upload, test_user_signature_token))
        assert rv.status_code == 200
        assert len(rv.data) > 0

512
513
514
    @UploadFilesBasedTests.ignore_authorization
    def test_get_non_existing_archive(self, client, upload, auth_headers):
        rv = client.get('/archive/%s' % 'doesnt/exist', headers=auth_headers)
515
        assert rv.status_code == 404
Markus Scheidgen's avatar
Markus Scheidgen committed
516

517
518
519
520
    def test_get_metainfo(self, client):
        rv = client.get('/archive/metainfo/all.nomadmetainfo.json')
        assert rv.status_code == 200

Markus Scheidgen's avatar
Markus Scheidgen committed
521

522
class TestRepo(UploadFilesBasedTests):
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
    @pytest.fixture(scope='class')
    def example_elastic_calcs(
            self, elastic_infra, normalized: parsing.LocalBackend,
            test_user: coe_repo.User, other_test_user: coe_repo.User):

        clear_elastic(elastic_infra)

        calc_with_metadata = normalized.to_calc_with_metadata()

        calc_with_metadata.update(calc_id='1', uploader=test_user.to_popo(), published=True)
        search.Entry.from_calc_with_metadata(calc_with_metadata).save(refresh=True)

        calc_with_metadata.update(calc_id='2', uploader=other_test_user.to_popo(), published=True)
        search.Entry.from_calc_with_metadata(calc_with_metadata).save(refresh=True)

        calc_with_metadata.update(calc_id='3', uploader=other_test_user.to_popo(), published=False)
        search.Entry.from_calc_with_metadata(calc_with_metadata).save(refresh=True)

541
542
543
544
545
546
547
548
549
550
    @UploadFilesBasedTests.ignore_authorization
    def test_calc(self, client, upload, auth_headers):
        rv = client.get('/repo/%s/0' % upload, headers=auth_headers)
        assert rv.status_code == 200

    @UploadFilesBasedTests.ignore_authorization
    def test_non_existing_calcs(self, client, upload, auth_headers):
        rv = client.get('/repo/doesnt/exist', headers=auth_headers)
        assert rv.status_code == 404

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
    @pytest.mark.parametrize('calcs, owner, auth', [
        (2, 'all', 'none'),
        (2, 'all', 'test_user'),
        (1, 'user', 'test_user'),
        (2, 'user', 'other_test_user'),
        (0, 'staging', 'test_user'),
        (1, 'staging', 'other_test_user'),
    ])
    def test_search(self, client, example_elastic_calcs, no_warn, test_user_auth, other_test_user_auth, calcs, owner, auth):
        auth = dict(none=None, test_user=test_user_auth, other_test_user=other_test_user_auth).get(auth)
        rv = client.get('/repo/?owner=%s' % owner, headers=auth)
        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) == calcs
        if calcs > 0:
            for key in ['uploader', 'calc_id', 'formula', 'upload_id']:
                assert key in results[0]

    def test_calcs_pagination(self, client, example_elastic_calcs, no_warn):
        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

    def test_search_user_authrequired(self, client, example_elastic_calcs, no_warn):
        rv = client.get('/repo/?owner=user')
        assert rv.status_code == 401
584
585


586
class TestRaw(UploadFilesBasedTests):
Markus Scheidgen's avatar
Markus Scheidgen committed
587

588
589
    @UploadFilesBasedTests.check_authorizaton
    def test_raw_file(self, client, upload, auth_headers):
590
        url = '/raw/%s/%s' % (upload, example_file_mainfile)
591
        rv = client.get(url, headers=auth_headers)
592
593
594
        assert rv.status_code == 200
        assert len(rv.data) > 0

595
596
597
598
599
600
601
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_signed(self, client, upload, _, test_user_signature_token):
        url = '/raw/%s/%s?token=%s' % (upload, example_file_mainfile, test_user_signature_token)
        rv = client.get(url)
        assert rv.status_code == 200
        assert len(rv.data) > 0

602
603
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_missing_file(self, client, upload, auth_headers):
604
        url = '/raw/%s/does/not/exist' % upload
605
        rv = client.get(url, headers=auth_headers)
606
        assert rv.status_code == 404
607
608
609
        data = json.loads(rv.data)
        assert 'files' not in data

610
611
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_listing(self, client, upload, auth_headers):
612
        url = '/raw/%s/examples' % upload
613
        rv = client.get(url, headers=auth_headers)
614
615
616
617
        assert rv.status_code == 404
        data = json.loads(rv.data)
        assert len(data['files']) == 5

618
    @pytest.mark.parametrize('compress', [True, False])
619
620
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_wildcard(self, client, upload, auth_headers, compress):
621
        url = '/raw/%s/examples*' % upload
622
623
        if compress:
            url = '%s?compress=1' % url
624
        rv = client.get(url, headers=auth_headers)
625
626
627
628
629
630
631

        assert rv.status_code == 200
        assert len(rv.data) > 0
        with zipfile.ZipFile(io.BytesIO(rv.data)) as zip_file:
            assert zip_file.testzip() is None
            assert len(zip_file.namelist()) == len(example_file_contents)

632
633
634
635
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_wildcard_missing(self, client, upload, auth_headers):
        url = '/raw/%s/does/not/exist*' % upload
        rv = client.get(url, headers=auth_headers)
636
        assert rv.status_code == 404
637

638
639
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_missing_upload(self, client, upload, auth_headers):
640
        url = '/raw/doesnotexist/%s' % example_file_mainfile
641
        rv = client.get(url, headers=auth_headers)
642
643
        assert rv.status_code == 404

644
    @pytest.mark.parametrize('compress', [True, False])
645
646
    @UploadFilesBasedTests.check_authorizaton
    def test_raw_files(self, client, upload, auth_headers, compress):
647
        url = '/raw/%s?files=%s' % (
648
            upload, ','.join(example_file_contents))
649
650
        if compress:
            url = '%s&compress=1' % url
651
        rv = client.get(url, headers=auth_headers)
Markus Scheidgen's avatar
Markus Scheidgen committed
652

653
654
655
656
        assert rv.status_code == 200
        assert len(rv.data) > 0
        with zipfile.ZipFile(io.BytesIO(rv.data)) as zip_file:
            assert zip_file.testzip() is None
657
            assert len(zip_file.namelist()) == len(example_file_contents)
Markus Scheidgen's avatar
Markus Scheidgen committed
658

659
660
661
662
663
664
665
666
667
668
669
670
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_files_signed(self, client, upload, _, test_user_signature_token):
        url = '/raw/%s?files=%s&token=%s' % (
            upload, ','.join(example_file_contents), test_user_signature_token)
        rv = client.get(url)

        assert rv.status_code == 200
        assert len(rv.data) > 0
        with zipfile.ZipFile(io.BytesIO(rv.data)) as zip_file:
            assert zip_file.testzip() is None
            assert len(zip_file.namelist()) == len(example_file_contents)

671
    @pytest.mark.parametrize('compress', [True, False, None])
672
673
674
    @UploadFilesBasedTests.check_authorizaton
    def test_raw_files_post(self, client, upload, auth_headers, compress):
        url = '/raw/%s' % upload
675
        data = dict(files=example_file_contents)
676
677
        if compress is not None:
            data.update(compress=compress)
678
        rv = client.post(url, data=json.dumps(data), content_type='application/json', headers=auth_headers)
679
680
681
682
683

        assert rv.status_code == 200
        assert len(rv.data) > 0
        with zipfile.ZipFile(io.BytesIO(rv.data)) as zip_file:
            assert zip_file.testzip() is None
684
            assert len(zip_file.namelist()) == len(example_file_contents)
685

686
    @pytest.mark.parametrize('compress', [True, False])
687
688
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_files_missing_file(self, client, upload, auth_headers, compress):
689
        url = '/raw/%s?files=%s,missing/file.txt' % (upload, example_file_mainfile)
690
691
        if compress:
            url = '%s&compress=1' % url
692
        rv = client.get(url, headers=auth_headers)
Markus Scheidgen's avatar
Markus Scheidgen committed
693

694
695
696
697
698
        assert rv.status_code == 200
        assert len(rv.data) > 0
        with zipfile.ZipFile(io.BytesIO(rv.data)) as zip_file:
            assert zip_file.testzip() is None
            assert len(zip_file.namelist()) == 1
699

700
701
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_files_missing_upload(self, client, upload, auth_headers):
702
        url = '/raw/doesnotexist?files=shoud/not/matter.txt'
703
        rv = client.get(url, headers=auth_headers)
704

705
        assert rv.status_code == 404
706
707
708
709
710
711


def test_docs(client):
    rv = client.get('/docs/index.html')
    rv = client.get('/docs/introduction.html')
    assert rv.status_code == 200