Example #1
0
def test_citation_formatter_citeproc_get(api, api_client, es, db, full_record,
                                         users):
    """Test records REST citeproc get."""
    r = Record.create(full_record)
    pid = PersistentIdentifier.create(
        'recid', '12345', object_type='rec', object_uuid=r.id,
        status=PIDStatus.REGISTERED)
    db.session.commit()
    db.session.refresh(pid)

    RecordIndexer().index_by_id(r.id)
    current_search.flush_and_refresh(index='records')
    login_user_via_session(api_client, email=users[2]['email'])

    with api.test_request_context():
        records_url = url_for('invenio_records_rest.recid_item',
                              pid_value=pid.pid_value)

    res = api_client.get(records_url,
                         query_string={'style': 'apa'},
                         headers={'Accept': 'text/x-bibliography'})
    assert res.status_code == 200
    assert 'Doe, J.' in res.get_data(as_text=True)
    assert 'Test title (Version 1.2.5).' in res.get_data(as_text=True)
    assert '(2014).' in res.get_data(as_text=True)
Example #2
0
def test_queries_permission_factory(app, db, es, event_queues, users,
                                    record_with_files_creation, api_client):
    """Test queries permission factory."""
    recid, record, _ = record_with_files_creation
    record['conceptdoi'] = '10.1234/foo.concept'
    record['conceptrecid'] = 'foo.concept'
    record.commit()
    db.session.commit()

    headers = [('Content-Type', 'application/json'),
               ('Accept', 'application/json')]
    sample_histogram_query_data = {
        "mystat": {
            "stat": "record-download",
            "params": {
                "file_key": "Test.pdf",
                "recid": recid.pid_value
            }
        }
    }
    query_url = '/stats'

    login_user_via_session(api_client, email=users[0]['email'])
    res = api_client.post(query_url, headers=headers,
                          data=json.dumps(sample_histogram_query_data))
    assert res.status_code == 403

    login_user_via_session(api_client, email=users[2]['email'])
    res = api_client.post(query_url, headers=headers,
                          data=json.dumps(sample_histogram_query_data))
    assert res.status_code == 200
Example #3
0
def test_citation_formatter_citeproc_get(api, api_client, es, db, full_record,
                                         users):
    """Test records REST citeproc get."""
    r = Record.create(full_record)
    pid = PersistentIdentifier.create(
        'recid', '12345', object_type='rec', object_uuid=r.id,
        status=PIDStatus.REGISTERED)
    db.session.commit()
    db.session.refresh(pid)

    RecordIndexer().index_by_id(r.id)
    current_search.flush_and_refresh(index='records')
    login_user_via_session(api_client, email=users[2]['email'])

    with api.test_request_context():
        records_url = url_for('invenio_records_rest.recid_item',
                              pid_value=pid.pid_value)

    res = api_client.get(records_url,
                         query_string={'style': 'apa'},
                         headers={'Accept': 'text/x-bibliography'})
    assert res.status_code == 200
    assert 'Doe, J.' in res.get_data(as_text=True)
    assert 'Test title (Version 1.2.5).' in res.get_data(as_text=True)
    assert '(2014).' in res.get_data(as_text=True)
Example #4
0
def test_basic_webhooks(app, db, communities, deposit, deposit_file, mocker,
                        es, deposit_url, get_json, json_auth_headers,
                        license_record, users, app_client, api_client,
                        use_webhooks_config):
    """Test community webhooks executions on inclusion request and approval."""
    test_data = dict(metadata=dict(
        upload_type='presentation',
        title='Test title',
        creators=[
            dict(name='Doe, John', affiliation='Atlantis'),
            dict(name='Smith, Jane', affiliation='Atlantis')
        ],
        description='Test Description',
        publication_date='2013-05-08',
        access_right='open',
        license='CC0-1.0',
        communities=[{
            'identifier': 'c1'
        }],
    ))
    with mock.patch(
            'zenodo.modules.communities.tasks.requests.post') as requests_mock:
        res = api_client.post(deposit_url,
                              data=json.dumps(test_data),
                              headers=json_auth_headers)
        links = get_json(res, code=201)['links']
        recid = get_json(res, code=201)['id']
        deposit_bucket = links['bucket']
        deposit_edit = links['edit']
        deposit_publish = links['publish']

        # Upload files
        res = api_client.put(deposit_bucket + '/test1.txt',
                             input_stream=BytesIO(b'testfile1'),
                             headers=json_auth_headers)
        assert res.status_code == 200
        res = api_client.put(deposit_bucket + '/test2.txt',
                             input_stream=BytesIO(b'testfile2'),
                             headers=json_auth_headers)
        assert res.status_code == 200

        # Publish deposit
        res = api_client.post(deposit_publish, headers=json_auth_headers)
        links = get_json(res, code=202)['links']
        record_url = links['record']

        calls = requests_mock.call_args_list
        assert len(calls) == 1

        login_user_via_session(app_client, email=users[1]['email'])
        res = app_client.post('/communities/c1/curaterecord/',
                              json={
                                  'action': 'accept',
                                  'recid': recid
                              })
        assert res.status_code == 200
        assert len(calls) == 2
Example #5
0
def test_deposit_create_permissions(api, api_client, db, es, users,
                                    minimal_deposit, license_record,
                                    deposit_url, locations, user_info, status):
    """Test deposit with custom field publishing."""
    if user_info:
        login_user_via_session(api_client, email=user_info['email'])
    # Test wrong term
    response = api_client.post(deposit_url, json=minimal_deposit)
    assert response.status_code == status
Example #6
0
def test_extra_formats_buckets_permissions(api, api_client, minimal_deposit,
                                           deposit_url, db, es, users,
                                           locations, json_extra_auth_headers,
                                           extra_auth_headers, license_record,
                                           user_email, status):
    """Test Files-REST permissions for the extra formats bucket and files."""
    # Create deposit

    response = api_client.post(deposit_url,
                               json=minimal_deposit,
                               headers=json_extra_auth_headers)
    data = response.json

    # Get identifier and links
    depid = data['record_id']
    links = data['links']

    # Upload 1 files
    response = api_client.put(
        links['bucket'] + '/test1.txt',
        data='ctx',
        headers=extra_auth_headers,
    )

    # Add extra_formats bucket with a file
    response = api_client.put(
        '/deposit/depositions/{0}/formats'.format(depid),
        data='foo file',
        headers=[('Content-Type', 'application/foo+xml')] + extra_auth_headers)
    dep_uuid, deposit = deposit_resolver.resolve(depid)
    if user_email:
        # Login as user
        login_user_via_session(api_client, email=user_email)
    response = api_client.get('/files/' + str(deposit.extra_formats.bucket.id))
    assert response.status_code == status

    response = api_client.put('/files/' +
                              str(deposit.extra_formats.bucket.id) +
                              '/application/foo+xml',
                              data='ctx')
    assert response.status_code == status

    # Publish deposition
    response = api_client.post(links['publish'], headers=extra_auth_headers)

    if user_email:
        # Login as user
        login_user_via_session(api_client, email=user_email)
    response = api_client.get('/files/' + str(deposit.extra_formats.bucket.id))
    assert response.status_code == status

    response = api_client.put('/files/' +
                              str(deposit.extra_formats.bucket.id) +
                              '/application/foo+xml',
                              data='ctx')
    assert response.status_code == status
Example #7
0
def test_delete_deposits_users(api, api_client, db, users, deposit, json_headers, user_info, status):
    """Test read deposit by users."""
    deposit_id = deposit["_deposit"]["id"]
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info["email"])

            res = client.delete(url_for("invenio_deposit_rest.depid_item", pid_value=deposit_id), headers=json_headers)
            assert res.status_code == status
Example #8
0
def test_read_deposits_users(api, api_client, db, users, deposit, json_headers, user_info, status, count_deposit):
    """Test read deposit by users."""
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info["email"])

            res = client.get(url_for("invenio_deposit_rest.depid_list"), headers=json_headers)
            assert res.status_code == status
            if user_info:
                data = json.loads(res.data.decode("utf-8"))
                assert len(data) == count_deposit
Example #9
0
def test_closed_access_record_serializer(api, users, json_headers, user_info,
                                         closed_access_record):
    """Test closed access record serialisation of the search result."""
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info['email'])
            res = client.get(url_for('invenio_records_rest.recid_list'),
                             headers=json_headers)

            r = json.loads(res.data.decode('utf-8'))
            assert r[0]['links'].get('bucket', None) is None
            assert len(r[0].get('files', [])) == 0
Example #10
0
def test_delete_deposits_users(api, api_client, db, es, users, deposit,
                               json_headers, user_info, status):
    """Test read deposit by users."""
    deposit_id = deposit['_deposit']['id']
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info['email'])

            res = client.delete(url_for('invenio_deposit_rest.depid_item',
                                        pid_value=deposit_id),
                                headers=json_headers)
            assert res.status_code == status
Example #11
0
def test_closed_access_record_serializer(api, users, json_headers,
                                         closed_access_record, user_info,
                                         bucket_link, files):
    """Test closed access record serialisation using records API."""
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info['email'])
            res = client.get(url_for('invenio_records_rest.recid_item',
                                     pid_value=closed_access_record['recid']),
                             headers=json_headers)
            r = json.loads(res.data.decode('utf-8'))
            assert r['links'].get('bucket', None) == bucket_link
            assert len(r.get('files', [])) == files
def test_extra_formats_permissions(
        api, api_client, db, users, deposit, extra_auth_headers,
        user_email, status, use_scope):
    if use_scope:
        user_headers = extra_auth_headers
    else:
        user_headers = []

    if user_email:
        # Login as user
        login_user_via_session(api_client, email=user_email)
    response = api_client.options(
        '/deposit/depositions/{0}/formats'.format(deposit['recid']),
        headers=user_headers)
    assert response.status_code == status
Example #13
0
def test_read_deposits_users(api, api_client, db, users, deposit, json_headers,
                             user_info, status, count_deposit):
    """Test read deposit by users."""
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info['email'])

            res = client.get(url_for('invenio_deposit_rest.depid_list'),
                             headers=json_headers)
            assert res.status_code == status
            if user_info:
                data = json.loads(res.data.decode('utf-8'))
                assert len(data) == count_deposit
Example #14
0
def test_extra_formats_permissions(api, api_client, db, users, deposit,
                                   extra_auth_headers, user_email, status,
                                   use_scope):
    if use_scope:
        user_headers = extra_auth_headers
    else:
        user_headers = []

    if user_email:
        # Login as user
        login_user_via_session(api_client, email=user_email)
    response = api_client.options('/deposit/depositions/{0}/formats'.format(
        deposit['recid']),
                                  headers=user_headers)
    assert response.status_code == status
Example #15
0
def test_read_deposit_users(api, api_client, db, users, deposit, json_headers,
                            user_info, status):
    """Test read deposit by users."""
    deposit_id = deposit['_deposit']['id']
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info['email'])

            res = client.get(
                url_for('invenio_deposit_rest.depid_item',
                        pid_value=deposit_id),
                headers=json_headers
            )
            assert res.status_code == status
Example #16
0
def test_closed_access_record_search_serializer(
        api, users, json_headers, user_info, closed_access_record):
    """Test closed access record serialisation of the search result."""
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info['email'])
            res = client.get(
                url_for('invenio_records_rest.recid_list'),
                headers=json_headers
            )

            r = json.loads(res.data.decode('utf-8'))
            assert r[0]['links'].get('bucket', None) is None
            assert len(r[0].get('files', [])) == 0
Example #17
0
def test_closed_access_record_serializer(api, users, json_headers,
                                         closed_access_record,
                                         user_info, bucket_link, files):
    """Test closed access record serialisation using records API."""
    with api.test_request_context():
        with api.test_client() as client:
            if user_info:
                # Login as user
                login_user_via_session(client, email=user_info['email'])
            res = client.get(
                url_for('invenio_records_rest.recid_item',
                        pid_value=closed_access_record['recid']),
                headers=json_headers
            )
            r = json.loads(res.data.decode('utf-8'))
            assert r['links'].get('bucket', None) == bucket_link
            assert len(r.get('files', [])) == files
Example #18
0
def test_429_template(use_flask_limiter, app, app_client, db, users,
                      user_email, requests_num, status_code, es):
    """Test flask limiter behaviour."""
    if user_email:
        # Login as user
        login_user_via_session(app_client, email=user_email)

    for x in range(0, requests_num):
        response = app_client.get('/search')
        assert response.status_code == 200

    response = app_client.get('/search')
    assert response.status_code == status_code

    response = app_client.get('/')
    assert response.status_code == 200

    if not user_email:
        response = app_client.get('/login')
        assert response.status_code == 200
Example #19
0
def test_send_support_email(app, db, es, users):
    """Test mail sending."""
    with app.extensions['mail'].record_messages() as outbox:
        with app.test_client() as client:
            res = client.get(url_for('zenodo_pages.support'))
            assert res.status_code == 200

            res = client.get(
                url_for('zenodo_pages.support')
            )
            assert b('recaptcha') in res.data
            assert res.status_code == 200

            res = client.post(
                url_for('zenodo_pages.support'),
                data=dict()
            )
            assert res.status_code == 200
            assert b('field-name has-error') in res.data
            assert b('field-email has-error') in res.data
            assert b('field-subject has-error') in res.data
            assert b('field-description has-error') in res.data
            assert b('field-attachments has-error') not in res.data

            form = MultiDict(dict(
                name='Aman',
                email='*****@*****.**',
                subject='hello',
                issue_category='tech-support',
                description='Please help us! Troubleshoot our problem.'
            ))

            res = client.post(
                url_for('zenodo_pages.support'),
                data=form
            )
            assert b('has-error') not in res.data
            assert len(outbox) == 2
            sent_msg = outbox[0]
            assert sent_msg.sender == 'Aman <*****@*****.**>'
            assert sent_msg.subject == '[tech-support]: hello'
            assert sent_msg.reply_to == '*****@*****.**'
            assert 'Aman <*****@*****.**>' in sent_msg.body

            sent_msg = outbox[1]
            assert sent_msg.sender == 'Zenodo <*****@*****.**>'
            assert sent_msg.subject == 'Zenodo Support'
            assert sent_msg.body == (
                'Thank you for contacting Zenodo support.'
                '\n\nWe have received your message, and we will do our best '
                'to get back to you as soon as possible.\nThis is an '
                'automated confirmation of your request, please do not reply '
                'to this email.\n\nZenodo Support\n'
                'https://zenodo.org\n'
            )

            form = MultiDict(dict(
                name='Foo',
                email='*****@*****.**',
                subject='Bar',
                issue_category='tech-support',
                description='Please help us! Troubleshoot our problem.'
            ))
            test_file = BytesIO(b('My other file contents'))
            test_file2 = BytesIO(b('Another My other file contents'))
            form.add('attachments', (test_file, 'file2.txt'))
            form.add('attachments', (test_file2, 'test3.txt'))
            res = client.post(
                url_for('zenodo_pages.support'),
                data=form,
                content_type='multipart/form-data',
                follow_redirects=True
            )
            assert len(outbox) == 4
            sent_msg = outbox[2]
            file1 = sent_msg.attachments[0]
            assert file1.filename == 'file2.txt'
            assert file1.data == b('My other file contents')
            file2 = sent_msg.attachments[1]
            assert file2.filename == 'test3.txt'
            assert file2.data == b('Another My other file contents')

            login_user_via_session(client, email=users[1]['email'])
            res = client.get(
                url_for('zenodo_pages.support')
            )
            assert b('*****@*****.**') in res.data
            assert b('recaptcha') not in res.data

            form = MultiDict(dict(
                name='Foo',
                subject='Bar',
                issue_category='tech-support',
                description='Please help us! Troubleshoot our problem.'
            ))
            res = client.post(
                url_for('zenodo_pages.support'),
                data=form
            )
            assert len(outbox) == 6
            sent_msg = outbox[4]
            assert 'From: Foo <*****@*****.**> (2)' in sent_msg.body

            test_file = BytesIO(b('My file contents'))
            form.add('attachments', (test_file, 'file1.txt'))
            res = client.post(
                url_for('zenodo_pages.support'),
                data=form,
                content_type='multipart/form-data',
                follow_redirects=True
            )
            assert len(outbox) == 8
            sent_msg = outbox[6]
            file1 = sent_msg.attachments[0]
            assert file1.filename == 'file1.txt'
            assert file1.data == b('My file contents')

            form = MultiDict(dict(
                name='Foo',
                subject='Bar',
                issue_category='tech-support',
                description='Please help us! Troubleshoot our problem.'
            ))
            test_file = BytesIO(b('My other file contents'))
            test_file2 = BytesIO(b('Another My other file contents'))
            form.add('attachments', (test_file, 'file2.txt'))
            form.add('attachments', (test_file2, 'test3.txt'))
            res = client.post(
                url_for('zenodo_pages.support'),
                data=form,
                content_type='multipart/form-data',
                follow_redirects=True
            )
            assert len(outbox) == 10
            sent_msg = outbox[8]
            file1 = sent_msg.attachments[0]
            assert file1.filename == 'file2.txt'
            assert file1.data == b('My other file contents')
            file2 = sent_msg.attachments[1]
            assert file2.filename == 'test3.txt'
            assert file2.data == b('Another My other file contents')
Example #20
0
def test_send_support_email(app, db, es, users):
    """Test mail sending."""
    with app.extensions['mail'].record_messages() as outbox:
        with app.test_client() as client:
            res = client.get(url_for('zenodo_support.support'))
            assert res.status_code == 200

            with recaptcha_enabled(app):
                res = client.get(url_for('zenodo_support.support'))
                assert b('recaptcha') in res.data
                assert res.status_code == 200

            res = client.post(url_for('zenodo_support.support'), data=dict())
            assert res.status_code == 200
            assert b('field-name has-error') in res.data
            assert b('field-email has-error') in res.data
            assert b('field-subject has-error') in res.data
            assert b('field-description has-error') in res.data
            assert b('field-attachments has-error') not in res.data

            form = MultiDict(
                dict(name='Aman',
                     email='*****@*****.**',
                     subject='hello',
                     issue_category='tech-support',
                     description='Please help us! Troubleshoot our problem.'))

            res = client.post(url_for('zenodo_support.support'), data=form)
            assert b('has-error') not in res.data
            assert len(outbox) == 2
            sent_msg = outbox[0]
            assert sent_msg.sender == 'Aman <*****@*****.**>'
            assert sent_msg.subject == '[tech-support]: hello'
            assert sent_msg.reply_to == '*****@*****.**'
            assert 'Aman <*****@*****.**>' in sent_msg.body

            sent_msg = outbox[1]
            assert sent_msg.sender == 'Zenodo <*****@*****.**>'
            assert sent_msg.subject == 'Zenodo Support'
            assert sent_msg.body == (
                'Thank you for contacting Zenodo support.'
                '\n\nWe have received your message, and we will do our best '
                'to get back to you as soon as possible.\nThis is an '
                'automated confirmation of your request, please do not reply '
                'to this email.\n\nZenodo Support\n'
                'https://zenodo.org\n')

            form = MultiDict(
                dict(name='Foo',
                     email='*****@*****.**',
                     subject='Bar',
                     issue_category='tech-support',
                     description='Please help us! Troubleshoot our problem.'))
            test_file = BytesIO(b('My other file contents'))
            test_file2 = BytesIO(b('Another My other file contents'))
            form.add('attachments', (test_file, 'file2.txt'))
            form.add('attachments', (test_file2, 'test3.txt'))
            res = client.post(url_for('zenodo_support.support'),
                              data=form,
                              content_type='multipart/form-data',
                              follow_redirects=True)
            assert len(outbox) == 4
            sent_msg = outbox[2]
            file1 = sent_msg.attachments[0]
            assert file1.filename == 'file2.txt'
            assert file1.data == b('My other file contents')
            file2 = sent_msg.attachments[1]
            assert file2.filename == 'test3.txt'
            assert file2.data == b('Another My other file contents')

            login_user_via_session(client, email=users[1]['email'])

            with recaptcha_enabled(app):
                res = client.get(url_for('zenodo_support.support'))
                assert b('*****@*****.**') in res.data
                assert b('recaptcha') not in res.data

            form = MultiDict(
                dict(name='Foo',
                     subject='Bar',
                     issue_category='tech-support',
                     description='Please help us! Troubleshoot our problem.'))
            res = client.post(url_for('zenodo_support.support'), data=form)
            assert len(outbox) == 6
            sent_msg = outbox[4]
            assert 'From: Foo <*****@*****.**> (2)' in sent_msg.body

            test_file = BytesIO(b('My file contents'))
            form.add('attachments', (test_file, 'file1.txt'))
            res = client.post(url_for('zenodo_support.support'),
                              data=form,
                              content_type='multipart/form-data',
                              follow_redirects=True)
            assert len(outbox) == 8
            sent_msg = outbox[6]
            file1 = sent_msg.attachments[0]
            assert file1.filename == 'file1.txt'
            assert file1.data == b('My file contents')

            form = MultiDict(
                dict(name='Foo',
                     subject='Bar',
                     issue_category='tech-support',
                     description='Please help us! Troubleshoot our problem.'))
            test_file = BytesIO(b('My other file contents'))
            test_file2 = BytesIO(b('Another My other file contents'))
            form.add('attachments', (test_file, 'file2.txt'))
            form.add('attachments', (test_file2, 'test3.txt'))
            res = client.post(url_for('zenodo_support.support'),
                              data=form,
                              content_type='multipart/form-data',
                              follow_redirects=True)
            assert len(outbox) == 10
            sent_msg = outbox[8]
            file1 = sent_msg.attachments[0]
            assert file1.filename == 'file2.txt'
            assert file1.data == b('My other file contents')
            file2 = sent_msg.attachments[1]
            assert file2.filename == 'test3.txt'
            assert file2.data == b('Another My other file contents')
def test_extra_formats_buckets_permissions(
        api, api_client, minimal_deposit, deposit_url, db, es, users,
        locations, json_extra_auth_headers, extra_auth_headers, license_record,
        user_email, status
        ):
    """Test Files-REST permissions for the extra formats bucket and files."""
    # Create deposit

    response = api_client.post(
        deposit_url, json=minimal_deposit, headers=json_extra_auth_headers)
    data = response.json

    # Get identifier and links
    depid = data['record_id']
    links = data['links']

    # Upload 1 files
    response = api_client.put(
        links['bucket'] + '/test1.txt',
        data='ctx',
        headers=extra_auth_headers,
    )

    # Add extra_formats bucket with a file
    response = api_client.put(
            '/deposit/depositions/{0}/formats'.format(depid),
            data='foo file',
            headers=[('Content-Type', 'application/foo+xml')] +
            extra_auth_headers
        )
    dep_uuid, deposit = deposit_resolver.resolve(depid)
    if user_email:
        # Login as user
        login_user_via_session(api_client, email=user_email)
    response = api_client.get(
        '/files/' + str(deposit.extra_formats.bucket.id)
    )
    assert response.status_code == status

    response = api_client.put(
        '/files/' + str(deposit.extra_formats.bucket.id) +
        '/application/foo+xml',
        data='ctx'
    )
    assert response.status_code == status

    # Publish deposition
    response = api_client.post(links['publish'], headers=extra_auth_headers)

    if user_email:
        # Login as user
        login_user_via_session(api_client, email=user_email)
    response = api_client.get(
        '/files/' + str(deposit.extra_formats.bucket.id)
    )
    assert response.status_code == status

    response = api_client.put(
        '/files/' + str(deposit.extra_formats.bucket.id) +
        '/application/foo+xml',
        data='ctx'
    )
    assert response.status_code == status