test_api.py 25.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
18
19
import pytest
import time
import json
from mongoengine import connect
from mongoengine.connection import disconnect
20
import base64
21
22
import zipfile
import io
23
import inspect
24

25
26
27
28
29
30
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)

31
from nomad import api, coe_repo  # noqa
32
from nomad.files import UploadFiles, PublicUploadFiles  # noqa
33
from nomad.processing import Upload, Calc  # noqa
34
from nomad.coe_repo import User  # noqa
35

Markus Scheidgen's avatar
Markus Scheidgen committed
36
from tests.processing.test_data import example_files  # noqa
37
38
from tests.test_files import example_file, example_file_mainfile, example_file_contents  # noqa
from tests.test_files import create_staging_upload, create_public_upload  # noqa
39

40
# import fixtures
41
42
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
43
# from tests.test_repo import example_elastic_calc  # noqa pylint: disable=unused-import
44
from tests.test_coe_repo import assert_coe_upload  # noqa
45

46

47
@pytest.fixture(scope='function')
48
def client(mockmongo):
49
    disconnect()
Markus Scheidgen's avatar
Markus Scheidgen committed
50
    connect('users_test', host=config.mongo.host, port=config.mongo.port, is_mock=True)
51
52
53
54
55

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

    yield client
56
    Upload._get_collection().drop()
57
58


59
60
61
62
def create_auth_headers(user):
    basic_auth_str = '%s:password' % user.email
    basic_auth_bytes = basic_auth_str.encode('utf-8')
    basic_auth_base64 = base64.b64encode(basic_auth_bytes).decode('utf-8')
63
    return {
64
        'Authorization': 'Basic %s' % basic_auth_base64
65
66
67
    }


68
@pytest.fixture(scope='session')
69
def test_user_auth(test_user: User):
70
71
72
73
    return create_auth_headers(test_user)


@pytest.fixture(scope='session')
74
def test_other_user_auth(other_test_user: User):
75
    return create_auth_headers(other_test_user)
76
77


78
79
80
81
@pytest.fixture(scope='session')
def admin_user_auth(admin_user: User):
    return create_auth_headers(admin_user)

82

83
class TestAdmin:
84
85

    @pytest.mark.timeout(10)
86
    def test_reset(self, client, admin_user_auth, repository_db):
87
88
89
90
91
        rv = client.post('/admin/reset', headers=admin_user_auth)
        assert rv.status_code == 200

    # TODO disabled as this will destroy the session repository_db beyond repair.
    # @pytest.mark.timeout(10)
92
    # def test_remove(self, client, admin_user_auth, repository_db):
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    #     rv = client.post('/admin/remove', headers=admin_user_auth)
    #     assert rv.status_code == 200

    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):
        rv = client.post('/admin/doesnotexist', headers=test_user_auth)
        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,
            True)
        monkeypatch.setattr(config, 'services', new_config)
        yield None
        monkeypatch.setattr(config, 'services', old_config)

    def test_disabled(self, client, admin_user_auth, disable_reset):
        rv = client.post('/admin/reset', headers=admin_user_auth)
        assert rv.status_code == 400


123
class TestAuth:
124
    def test_xtoken_auth(self, client, test_user: User, no_warn):
125
        rv = client.get('/uploads/', headers={
126
            'X-Token': test_user.email  # the test users have their email as tokens for convinience
127
        })
128

129
        assert rv.status_code == 200
Markus Scheidgen's avatar
Markus Scheidgen committed
130

131
132
133
134
    def test_xtoken_auth_denied(self, client, no_warn):
        rv = client.get('/uploads/', headers={
            'X-Token': 'invalid'
        })
Markus Scheidgen's avatar
Markus Scheidgen committed
135

136
        assert rv.status_code == 401
137

138
139
140
    def test_basic_auth(self, client, test_user_auth, no_warn):
        rv = client.get('/uploads/', headers=test_user_auth)
        assert rv.status_code == 200
141

142
143
144
145
146
147
148
    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

149
150
151
152
153
    def test_get_token(self, client, test_user_auth, test_user: User, no_warn):
        rv = client.get('/auth/token', headers=test_user_auth)
        assert rv.status_code == 200
        assert rv.data.decode('utf-8') == test_user.get_auth_token().decode('utf-8')

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
193
194
195
196

class TestUploads:

    @pytest.fixture(scope='function')
    def proc_infra(self, repository_db, mocksearch, worker, no_warn):
        return dict(repository_db=repository_db)

    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
            if upload['completed']:
                break

        assert len(upload['tasks']) == 4
        assert upload['status'] == 'SUCCESS'
        assert upload['current_task'] == 'cleanup'
197
198
        upload_files = UploadFiles.get(upload['upload_id'])
        assert upload_files is not None
199
200
201
202
203
        calcs = upload['calcs']['results']
        for calc in calcs:
            assert calc['status'] == 'SUCCESS'
            assert calc['current_task'] == 'archiving'
            assert len(calc['tasks']) == 3
204
            assert client.get('/archive/logs/%s' % calc['archive_id'], headers=test_user_auth).status_code == 200
205
206

        if upload['calcs']['pagination']['total'] > 1:
207
            rv = client.get('%s?page=2&per_page=1&order_by=status' % upload_endpoint, headers=test_user_auth)
208
209
210
211
            assert rv.status_code == 200
            upload = self.assert_upload(rv.data)
            assert len(upload['calcs']['results']) == 1

212
    def assert_unstage(self, client, test_user_auth, upload_id, proc_infra, meta_data={}):
213
214
215
216
        rv = client.get('/uploads/%s' % upload_id, headers=test_user_auth)
        upload = self.assert_upload(rv.data)
        empty_upload = upload['calcs']['pagination']['total'] == 0

217
218
219
        rv = client.post(
            '/uploads/%s' % upload_id,
            headers=test_user_auth,
220
            data=json.dumps(dict(operation='unstage', meta_data=meta_data)),
221
            content_type='application/json')
222
        assert rv.status_code == 200
223

224
225
226
227
228
229
230
231
232
233
        self.assert_upload_does_not_exist(client, upload_id, test_user_auth)
        assert_coe_upload(upload_id, empty=empty_upload, meta_data=meta_data)

    def assert_upload_does_not_exist(self, client, upload_id: str, test_user_auth):
        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
234

235
236
237
238
239
240
241
    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

242
243
    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
244

245
246
        assert rv.status_code == 200
        self.assert_uploads(rv.data, count=0)
Markus Scheidgen's avatar
Markus Scheidgen committed
247

248
249
250
    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
251

252
    @pytest.mark.timeout(30)
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    @pytest.mark.parametrize('file', example_files)
    @pytest.mark.parametrize('mode', ['multipart', 'stream', 'local_path'])
    @pytest.mark.parametrize('name', [None, 'test_name'])
    def test_put(self, client, test_user_auth, proc_infra, file, mode, name):
        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
274

275
276
277
278
279
        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)
280

281
        self.assert_processing(client, test_user_auth, upload['upload_id'])
282

283
284
285
    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
286

287
288
289
290
291
292
293
    def test_delete_during_processing(self, client, test_user_auth, proc_infra):
        rv = client.put('/uploads/?local_path=%s' % example_file, headers=test_user_auth)
        upload = self.assert_upload(rv.data)
        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'])

294
    def test_delete_unstaged(self, client, test_user_auth, proc_infra, clean_repository_db):
295
296
297
298
299
        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)
300
        assert rv.status_code == 404
301
302
303
304
305
306
307

    def test_delete(self, client, test_user_auth, proc_infra):
        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
308
        self.assert_upload_does_not_exist(client, upload['upload_id'], test_user_auth)
309

310
    @pytest.mark.parametrize('example_file', example_files)
311
    def test_post(self, client, test_user_auth, example_file, proc_infra, clean_repository_db):
312
313
314
315
        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)
316

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    def test_post_metadata(
            self, client, proc_infra, admin_user_auth, test_user_auth, test_user,
            other_test_user, clean_repository_db):
        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'])

        meta_data = dict(comment='test comment')
        self.assert_unstage(client, admin_user_auth, upload['upload_id'], proc_infra, meta_data)

    def test_post_metadata_forbidden(self, client, proc_infra, test_user_auth, clean_repository_db):
        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,
            data=json.dumps(dict(operation='unstage', meta_data=dict(_pid=256))),
            content_type='application/json')
        assert rv.status_code == 401

    # TODO validate metadata (or all input models in API for that matter)
    # def test_post_bad_metadata(self, client, proc_infra, test_user_auth, clean_repository_db):
    #     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,
    #         data=json.dumps(dict(operation='unstage', meta_data=dict(doesnotexist='hi'))),
    #         content_type='application/json')
    #     assert rv.status_code == 400

350

351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
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
446
447
448
449
450
451
452
453
# class TestRepo:
#     def test_calc(self, client, example_elastic_calc, no_warn):
#         rv = client.get(
#             '/repo/%s/%s' % (example_elastic_calc.upload_hash, example_elastic_calc.calc_hash))
#         assert rv.status_code == 200

#     def test_non_existing_calcs(self, client):
#         rv = client.get('/repo/doesnt/exist')
#         assert rv.status_code == 404

#     def test_calcs(self, client, example_elastic_calc, no_warn):
#         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

#     def test_calcs_pagination(self, client, example_elastic_calc, 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_calcs_user(self, client, example_elastic_calc, test_user_auth, no_warn):
#         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

#     def test_calcs_user_authrequired(self, client, example_elastic_calc, no_warn):
#         rv = client.get('/repo/?owner=user')
#         assert rv.status_code == 401

#     def test_calcs_user_invisible(self, client, example_elastic_calc, test_other_user_auth, no_warn):
#         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


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
454

455
456
457
458
459
460
461
    @pytest.fixture(scope='function')
    def test_data(self, request, clean_repository_db, no_warn, test_user, other_test_user):
        # delete potential old test files
        for _ in [0, 1]:
            upload_files = UploadFiles.get('test_upload')
            if upload_files:
                upload_files.delete()
462

463
        in_staging, restricted, for_uploader = request.param
464

465
466
467
468
        if in_staging:
            authorized = for_uploader
        else:
            authorized = not restricted or for_uploader
469

470
471
472
473
474
475
        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
476

477
478
479
480
481
482
483
484
485
486
487
488
        calc_specs = 'r' if restricted else 'p'
        if in_staging:
            Upload.create(user=test_user, upload_id='test_upload', upload_hash='test_upload')
            upload_files = create_staging_upload('test_upload', calc_specs=calc_specs)
        else:
            upload_files = create_public_upload('test_upload', calc_specs=calc_specs)
            clean_repository_db.begin()
            coe_upload = coe_repo.Upload(
                upload_name='test_upload',
                user_id=test_user.user_id, is_processed=True)
            clean_repository_db.add(coe_upload)
            clean_repository_db.commit()
489

490
        yield 'test_upload', authorized, auth_headers
491

492
        upload_files.delete()
493
494


495
496
497
498
class TestArchive(UploadFilesBasedTests):
    @UploadFilesBasedTests.check_authorizaton
    def test_get(self, client, upload, auth_headers):
        rv = client.get('/archive/%s/0' % upload, headers=auth_headers)
499
        assert rv.status_code == 200
500
        assert json.loads(rv.data) is not None
501

502
503
504
    @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)
505
        assert rv.status_code == 200
506
        assert len(rv.data) > 0
507

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

513
514
515
516
    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
517

518
class TestRaw(UploadFilesBasedTests):
Markus Scheidgen's avatar
Markus Scheidgen committed
519

520
521
    @UploadFilesBasedTests.check_authorizaton
    def test_raw_file(self, client, upload, auth_headers):
522
        url = '/raw/%s/%s' % (upload, example_file_mainfile)
523
        rv = client.get(url, headers=auth_headers)
524
525
526
        assert rv.status_code == 200
        assert len(rv.data) > 0

527
528
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_missing_file(self, client, upload, auth_headers):
529
        url = '/raw/%s/does/not/exist' % upload
530
        rv = client.get(url, headers=auth_headers)
531
        assert rv.status_code == 404
532
533
534
        data = json.loads(rv.data)
        assert 'files' not in data

535
536
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_listing(self, client, upload, auth_headers):
537
        url = '/raw/%s/examples' % upload
538
        rv = client.get(url, headers=auth_headers)
539
540
541
542
        assert rv.status_code == 404
        data = json.loads(rv.data)
        assert len(data['files']) == 5

543
    @pytest.mark.parametrize('compress', [True, False])
544
545
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_wildcard(self, client, upload, auth_headers, compress):
546
        url = '/raw/%s/examples*' % upload
547
548
        if compress:
            url = '%s?compress=1' % url
549
        rv = client.get(url, headers=auth_headers)
550
551
552
553
554
555
556

        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)

557
558
559
560
    @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)
561
        assert rv.status_code == 404
562

563
564
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_file_missing_upload(self, client, upload, auth_headers):
565
        url = '/raw/doesnotexist/%s' % example_file_mainfile
566
        rv = client.get(url, headers=auth_headers)
567
568
        assert rv.status_code == 404

569
    @pytest.mark.parametrize('compress', [True, False])
570
571
    @UploadFilesBasedTests.check_authorizaton
    def test_raw_files(self, client, upload, auth_headers, compress):
572
        url = '/raw/%s?files=%s' % (
573
            upload, ','.join(example_file_contents))
574
575
        if compress:
            url = '%s&compress=1' % url
576
        rv = client.get(url, headers=auth_headers)
Markus Scheidgen's avatar
Markus Scheidgen committed
577

578
579
580
581
        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
582
            assert len(zip_file.namelist()) == len(example_file_contents)
Markus Scheidgen's avatar
Markus Scheidgen committed
583

584
    @pytest.mark.parametrize('compress', [True, False, None])
585
586
587
    @UploadFilesBasedTests.check_authorizaton
    def test_raw_files_post(self, client, upload, auth_headers, compress):
        url = '/raw/%s' % upload
588
        data = dict(files=example_file_contents)
589
590
        if compress is not None:
            data.update(compress=compress)
591
        rv = client.post(url, data=json.dumps(data), content_type='application/json', headers=auth_headers)
592
593
594
595
596

        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
597
            assert len(zip_file.namelist()) == len(example_file_contents)
598

599
    @pytest.mark.parametrize('compress', [True, False])
600
601
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_files_missing_file(self, client, upload, auth_headers, compress):
602
        url = '/raw/%s?files=%s,missing/file.txt' % (upload, example_file_mainfile)
603
604
        if compress:
            url = '%s&compress=1' % url
605
        rv = client.get(url, headers=auth_headers)
Markus Scheidgen's avatar
Markus Scheidgen committed
606

607
608
609
610
611
        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
612

613
614
    @UploadFilesBasedTests.ignore_authorization
    def test_raw_files_missing_upload(self, client, upload, auth_headers):
615
        url = '/raw/doesnotexist?files=shoud/not/matter.txt'
616
        rv = client.get(url, headers=auth_headers)
617

618
        assert rv.status_code == 404
619
620
621
622
623
624


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