def test_invalid_patch(app, test_records, test_patch):
    """Test INVALID record put request (PUT .../records/<record_id>)."""
    pid, record = test_records[0]

    with app.test_client() as client:
        url = record_url(pid)

        # Non-existing record
        res = client.patch(record_url("0"), data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 404

        # Invalid accept mime type.
        headers = [("Content-Type", "application/json-patch+json"), ("Accept", "video/mp4")]
        res = client.patch(url, data=json.dumps(test_patch), headers=headers)
        assert res.status_code == 406

        # Invalid content type
        headers = [("Content-Type", "video/mp4"), ("Accept", "application/json")]
        res = client.patch(url, data=json.dumps(test_patch), headers=headers)
        assert res.status_code == 415

        # Invalid Patch
        res = client.patch(url, data=json.dumps([{"invalid": "json-patch"}]), headers=HEADERS)
        assert res.status_code == 400

        # Invalid JSON
        res = client.patch(url, data="{", headers=HEADERS)
        assert res.status_code == 400

        # Invalid ETag
        res = client.patch(
            url, data=json.dumps(test_patch), headers={"Content-Type": "application/json-patch+json", "If-Match": '"2"'}
        )
        assert res.status_code == 412
Example #2
0
def test_rest_delete_record(app, db, es, es_acl_prepare, test_users):
    with app.test_client() as client:
        with db.session.begin_nested():
            acl = DefaultACL(name='default',
                             schemas=[RECORD_SCHEMA],
                             priority=0,
                             originator=test_users.u1,
                             operation='update')
            actor = UserActor(name='u1',
                              users=[test_users.u1],
                              acl=acl,
                              originator=test_users.u1)

            db.session.add(acl)
            db.session.add(actor)

        pid, record = create_record({'keywords': ['blah']},
                                    clz=SchemaEnforcingRecord)
        RecordIndexer().index(record)
        current_search_client.indices.refresh()
        current_search_client.indices.flush()

        login(client, test_users.u2)
        response = client.delete(record_url(pid))
        assert response.status_code == 403

        login(client, test_users.u1)
        response = client.delete(record_url(pid))
        assert response.status_code == 204

        with pytest.raises(NoResultFound):
            Record.get_record(pid.object_uuid)
def test_invalid_patch(app, es, test_records, test_patch, charset, search_url,
                       search_class):
    """Test INVALID record put request (PUT .../records/<record_id>)."""
    HEADERS = [('Accept', 'application/json'),
               ('Content-Type',
                'application/json-patch+json{0}'.format(charset))]
    pid, record = test_records[0]

    with app.test_client() as client:
        url = record_url(pid)

        # Non-existing record
        res = client.patch(record_url('0'),
                           data=json.dumps(test_patch),
                           headers=HEADERS)
        assert res.status_code == 404
        IndexFlusher(search_class).flush_and_wait()
        res = client.get(search_url)
        assert_hits_len(res, 0)

        # Invalid accept mime type.
        headers = [('Content-Type',
                    'application/json-patch+json{0}'.format(charset)),
                   ('Accept', 'video/mp4')]
        res = client.patch(url, data=json.dumps(test_patch), headers=headers)
        assert res.status_code == 406

        # Invalid content type
        headers = [('Content-Type', 'video/mp4{0}'.format(charset)),
                   ('Accept', 'application/json')]
        res = client.patch(url, data=json.dumps(test_patch), headers=headers)
        assert res.status_code == 415

        # Invalid Patch
        res = client.patch(url,
                           data=json.dumps([{
                               'invalid':
                               'json-patch{0}'.format(charset)
                           }]),
                           headers=HEADERS)
        assert res.status_code == 400

        # Invalid JSON
        res = client.patch(url, data='{', headers=HEADERS)
        assert res.status_code == 400

        # Invalid ETag
        res = client.patch(
            url,
            data=json.dumps(test_patch),
            headers={
                'Content-Type':
                'application/json-patch+json{0}'.format(charset),
                'If-Match': '"2"'
            })
        assert res.status_code == 412
def test_valid_delete(app, test_records):
    """Test VALID record delete request (DELETE .../records/<record_id>)."""
    # Test with and without headers
    for i, headers in enumerate([[], [('Accept', 'video/mp4')]]):
        pid, record = test_records[i]
        with app.test_client() as client:
            res = client.delete(record_url(pid), headers=headers)
            assert res.status_code == 204

            res = client.get(record_url(pid))
            assert res.status_code == 410
Example #5
0
def test_valid_delete(app, indexed_records):
    """Test VALID record delete request (DELETE .../records/<record_id>)."""
    # Test with and without headers
    for i, headers in enumerate([[], [('Accept', 'video/mp4')]]):
        pid, record = indexed_records[i]
        with app.test_client() as client:
            res = client.delete(record_url(pid), headers=headers)
            assert res.status_code == 204

            res = client.get(record_url(pid))
            assert res.status_code == 410
def test_invalid_patch(app, test_records, test_patch, charset):
    """Test INVALID record put request (PUT .../records/<record_id>)."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type',
         'application/json-patch+json{0}'.format(charset))
    ]
    pid, record = test_records[0]

    with app.test_client() as client:
        url = record_url(pid)

        # Non-existing record
        res = client.patch(
            record_url('0'), data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 404

        # Invalid accept mime type.
        headers = [('Content-Type',
                    'application/json-patch+json{0}'.format(charset)),
                   ('Accept', 'video/mp4')]
        res = client.patch(url, data=json.dumps(test_patch), headers=headers)
        assert res.status_code == 406

        # Invalid content type
        headers = [('Content-Type', 'video/mp4{0}'.format(charset)),
                   ('Accept', 'application/json')]
        res = client.patch(url, data=json.dumps(test_patch), headers=headers)
        assert res.status_code == 415

        # Invalid Patch
        res = client.patch(
            url,
            data=json.dumps([{'invalid': 'json-patch{0}'.format(charset)}]),
            headers=HEADERS)
        assert res.status_code == 400

        # Invalid JSON
        res = client.patch(url, data='{', headers=HEADERS)
        assert res.status_code == 400

        # Invalid ETag
        res = client.patch(
            url,
            data=json.dumps(test_patch),
            headers={
                'Content-Type': 'application/json-patch+json{0}'.format(
                    charset),
                'If-Match': '"2"'
            }
        )
        assert res.status_code == 412
def test_delete_deleted(app, test_records):
    """Test deleting a perviously deleted record."""
    pid, record = test_records[0]

    with app.test_client() as client:
        res = client.delete(record_url(pid))
        assert res.status_code == 204

        res = client.delete(record_url(pid))
        assert res.status_code == 410
        data = get_json(res)
        assert 'message' in data
        assert data['status'] == 410
Example #8
0
def test_delete_deleted(app, indexed_records):
    """Test deleting a perviously deleted record."""
    pid, record = indexed_records[0]

    with app.test_client() as client:
        res = client.delete(record_url(pid))
        assert res.status_code == 204

        res = client.delete(record_url(pid))
        assert res.status_code == 410
        data = get_json(res)
        assert 'message' in data
        assert data['status'] == 410
Example #9
0
def test_invalid_put(app, es, test_records, charset, search_url):
    """Test INVALID record put request (PUT .../records/<record_id>)."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type', 'application/json{0}'.format(charset)),
    ]

    pid, record = test_records[0]

    record['year'] = 1234
    test_data = record.dumps()

    with app.test_client() as client:
        url = record_url(pid)

        # Non-existing record
        res = client.put(record_url('0'),
                         data=json.dumps(test_data),
                         headers=HEADERS)
        assert res.status_code == 404
        res = client.get(search_url, query_string={"year": 1234})
        assert_hits_len(res, 0)

        # Invalid accept mime type.
        headers = [('Content-Type', 'application/json{0}'.format(charset)),
                   ('Accept', 'video/mp4')]
        res = client.put(url, data=json.dumps(test_data), headers=headers)
        assert res.status_code == 406

        # Invalid content type
        headers = [('Content-Type', 'video/mp4{0}'.format(charset)),
                   ('Accept', 'application/json')]
        res = client.put(url, data=json.dumps(test_data), headers=headers)
        assert res.status_code == 415

        # Invalid JSON
        res = client.put(url, data='{invalid-json', headers=HEADERS)
        assert res.status_code == 400

        # Invalid ETag
        res = client.put(url,
                         data=json.dumps(test_data),
                         headers={
                             'Content-Type':
                             'application/json{0}'.format(charset),
                             'If-Match': '"2"'
                         })
        assert res.status_code == 412
Example #10
0
def test_default_permissions(app, default_permissions, test_data, search_url,
                             test_records, indexed_records):
    """Test default create permissions."""
    pid, record = test_records[0]
    rec_url = record_url(pid)
    data = json.dumps(test_data[0])
    h = {'Content-Type': 'application/json'}
    hp = {'Content-Type': 'application/json-patch+json'}

    with app.test_client() as client:
        args = dict(data=data, headers=h)
        pargs = dict(data=data, headers=hp)
        qs = {'user': '******'}
        uargs = dict(data=data, headers=h, query_string=qs)
        upargs = dict(data=data, headers=hp, query_string=qs)

        assert client.get(search_url).status_code == 200
        assert client.get(rec_url).status_code == 200

        assert 401 == client.post(search_url, **args).status_code
        assert 405 == client.put(search_url, **args).status_code
        assert 405 == client.patch(search_url).status_code
        assert 405 == client.delete(search_url).status_code

        assert 405 == client.post(rec_url, **args).status_code
        assert 401 == client.put(rec_url, **args).status_code
        assert 401 == client.patch(rec_url, **pargs).status_code
        assert 401 == client.delete(rec_url).status_code

        assert 403 == client.post(search_url, **uargs).status_code
        assert 403 == client.put(rec_url, **uargs).status_code
        assert 403 == client.patch(rec_url, **upargs).status_code
        assert 403 == client.delete(rec_url, query_string=qs).status_code
def test_delete_with_sqldatabase_error(app, test_records):
    """Test VALID record delete request (GET .../records/<record_id>)."""
    pid, record = test_records[0]

    with app.test_client() as client:
        def raise_error():
            raise SQLAlchemyError()
        # Force an SQLAlchemy error that will rollback the transaction.
        with patch.object(PersistentIdentifier, 'delete',
                          side_effect=raise_error):
            res = client.delete(record_url(pid))
            assert res.status_code == 500

    with app.test_client() as client:
            res = client.get(record_url(pid))
            assert res.status_code == 200
def test_get_record_no_acls_anonymous(app, db, es, es_acl_prepare, test_users):

    with db.session.begin_nested():
        # create an empty ACL in order to get the _invenio_explicit_acls filled
        acl = DefaultACL(name='test',
                         schemas=[RECORD_SCHEMA],
                         priority=0,
                         operation='get',
                         originator=test_users.u1)
        db.session.add(acl)
        actor = UserActor(name='test',
                          acl=acl,
                          users=[],
                          originator=test_users.u1)
        db.session.add(actor)

    pid, record = create_record({}, clz=SchemaEnforcingRecord)
    RecordIndexer().index(record)

    # make sure it is flushed
    current_search_client.indices.flush()

    # try to get it ...
    with app.test_client() as client:
        res = client.get(record_url(pid))
        assert res.status_code == 401  # unauthorized

    # get it directly from ES
    res = get_from_es(pid)['_source']
    assert res['control_number'] == pid.pid_value
    assert res['$schema'] == 'https://localhost/schemas/' + RECORD_SCHEMA
    assert '_invenio_explicit_acls' in res
Example #13
0
def test_valid_put_etag(app, es, test_records, content_type, search_url,
                        search_class):
    """Test concurrency control with etags."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type', content_type)
    ]

    pid, record = test_records[0]

    record['year'] = 1234

    with app.test_client() as client:
        url = record_url(pid)
        res = client.put(
            url,
            data=json.dumps(record.dumps()),
            headers={
                'Content-Type': 'application/json',
                'If-Match': '"{0}"'.format(record.revision_id)
            })
        assert res.status_code == 200
        assert get_json(client.get(url))['metadata']['year'] == 1234

        IndexFlusher(search_class).flush_and_wait()
        res = client.get(search_url, query_string={"year": 1234})
        assert_hits_len(res, 1)
Example #14
0
def test_valid_create(app, db, es, test_data, search_url, search_class,
                      content_type):
    """Test VALID record creation request (POST .../records/)."""
    with app.test_client() as client:
        HEADERS = [
            ('Accept', 'application/json'),
            ('Content-Type', content_type)
        ]
        HEADERS.append(('Content-Type', content_type))

        # Create record
        res = client.post(
            search_url, data=json.dumps(test_data[0]), headers=HEADERS)
        assert res.status_code == 201

        # Check that the returned record matches the given data
        data = get_json(res)
        for k in test_data[0].keys():
            assert data['metadata'][k] == test_data[0][k]

        # Recid has been added in control number
        assert data['metadata']['control_number']

        # Check location header
        assert res.headers['Location'] == data['links']['self']

        # Record can be retrieved.
        assert client.get(record_url(data['id'])).status_code == 200

        IndexFlusher(search_class).flush_and_wait()
        # Record shows up in search
        res = client.get(search_url,
                         query_string={"control_number":
                                       data['metadata']['control_number']})
        assert_hits_len(res, 1)
def test_invalid_put(app, es, test_records, charset, search_url):
    """Test INVALID record put request (PUT .../records/<record_id>)."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type',
         'application/json{0}'.format(charset)),
    ]

    pid, record = test_records[0]

    record['year'] = 1234
    test_data = record.dumps()

    with app.test_client() as client:
        url = record_url(pid)

        # Non-existing record
        res = client.put(
            record_url('0'), data=json.dumps(test_data), headers=HEADERS)
        assert res.status_code == 404
        res = client.get(search_url, query_string={"year": 1234})
        assert_hits_len(res, 0)

        # Invalid accept mime type.
        headers = [('Content-Type', 'application/json{0}'.format(charset)),
                   ('Accept', 'video/mp4')]
        res = client.put(url, data=json.dumps(test_data), headers=headers)
        assert res.status_code == 406

        # Invalid content type
        headers = [('Content-Type', 'video/mp4{0}'.format(charset)),
                   ('Accept', 'application/json')]
        res = client.put(url, data=json.dumps(test_data), headers=headers)
        assert res.status_code == 415

        # Invalid JSON
        res = client.put(url, data='{invalid-json', headers=HEADERS)
        assert res.status_code == 400

        # Invalid ETag
        res = client.put(
            url,
            data=json.dumps(test_data),
            headers={'Content-Type': 'application/json{0}'.format(charset),
                     'If-Match': '"2"'}
        )
        assert res.status_code == 412
Example #16
0
def test_item_get_invalid_mimetype(app, test_records):
    """Test invalid mimetype returns 406."""
    with app.test_client() as client:
        pid, record = test_records[0]

        # Check that GET with non accepted format will return 406
        res = client.get(record_url(pid), headers=[('Accept', 'video/mp4')])
        assert res.status_code == 406
def test_item_get_etag(app, test_records):
    """Test VALID record get request (GET .../records/<record_id>)."""
    with app.test_client() as client:
        pid, record = test_records[0]

        res = client.get(record_url(pid))
        assert res.status_code == 200
        etag = res.headers["ETag"]
        last_modified = res.headers["Last-Modified"]

        # Test request via etag
        res = client.get(record_url(pid), headers={"If-None-Match": etag})
        assert res.status_code == 304

        # Test request via last-modified.
        res = client.get(record_url(pid), headers={"If-Modified-Since": last_modified})
        assert res.status_code == 304
def test_invalid_patch(app, test_records, test_patch):
    """Test INVALID record put request (PUT .../records/<record_id>)."""
    pid, record = test_records[0]

    with app.test_client() as client:
        url = record_url(pid)

        # Non-existing record
        res = client.patch(record_url('0'),
                           data=json.dumps(test_patch),
                           headers=HEADERS)
        assert res.status_code == 404

        # Invalid accept mime type.
        headers = [('Content-Type', 'application/json-patch+json'),
                   ('Accept', 'video/mp4')]
        res = client.patch(url, data=json.dumps(test_patch), headers=headers)
        assert res.status_code == 406

        # Invalid content type
        headers = [('Content-Type', 'video/mp4'),
                   ('Accept', 'application/json')]
        res = client.patch(url, data=json.dumps(test_patch), headers=headers)
        assert res.status_code == 415

        # Invalid Patch
        res = client.patch(url,
                           data=json.dumps([{
                               'invalid': 'json-patch'
                           }]),
                           headers=HEADERS)
        assert res.status_code == 400

        # Invalid JSON
        res = client.patch(url, data='{', headers=HEADERS)
        assert res.status_code == 400

        # Invalid ETag
        res = client.patch(url,
                           data=json.dumps(test_patch),
                           headers={
                               'Content-Type': 'application/json-patch+json',
                               'If-Match': '"2"'
                           })
        assert res.status_code == 412
Example #19
0
def test_item_get_etag(app, test_records):
    """Test VALID record get request (GET .../records/<record_id>)."""
    with app.test_client() as client:
        pid, record = test_records[0]

        res = client.get(record_url(pid))
        assert res.status_code == 200
        etag = res.headers['ETag']
        last_modified = res.headers['Last-Modified']

        # Test request via etag
        res = client.get(record_url(pid), headers={'If-None-Match': etag})
        assert res.status_code == 304

        # Test request via last-modified.
        res = client.get(
            record_url(pid), headers={'If-Modified-Since': last_modified})
        assert res.status_code == 304
Example #20
0
def test_delete_with_sqldatabase_error(app, indexed_records):
    """Test VALID record delete request (GET .../records/<record_id>)."""
    pid, record = indexed_records[0]

    with app.test_client() as client:

        def raise_error():
            raise SQLAlchemyError()

        # Force an SQLAlchemy error that will rollback the transaction.
        with patch.object(PersistentIdentifier,
                          'delete',
                          side_effect=raise_error):
            res = client.delete(record_url(pid))
            assert res.status_code == 500

    with app.test_client() as client:
        res = client.get(record_url(pid))
        assert res.status_code == 200
def test_validation_error(app, test_records):
    """Test when record validation fail."""
    pid, record = test_records[0]

    record['year'] = 1234

    with app.test_client() as client:
        url = record_url(pid)
        res = client.put(url, data=json.dumps(record.dumps()), headers=HEADERS)
        assert res.status_code == 400
Example #22
0
def test_api_views(app, prefixed_es, db, test_data, search_url, search_class):
    """Test REST API views behavior."""
    suffix = current_search.current_suffix

    with app.test_client() as client:
        HEADERS = [
            ('Accept', 'application/json'),
            ('Content-Type', 'application/json'),
        ]

        # Create record
        res = client.post(
            search_url, data=json.dumps(test_data[0]), headers=HEADERS)
        recid = get_json(res)['id']
        assert res.status_code == 201

        # Flush and check indices
        IndexFlusher(search_class).flush_and_wait()
        result = prefixed_es.search(index='test-invenio-records-rest')
        assert len(result['hits']['hits']) == 1
        record_doc = result['hits']['hits'][0]
        assert record_doc['_index'] == \
            'test-invenio-records-rest-testrecord' + suffix
        assert record_doc['_type'] == 'testrecord' if lt_es7 else '_doc'

        # Fetch the record
        assert client.get(record_url(recid)).status_code == 200
        # Record shows up in search
        res = client.get(search_url)
        assert_hits_len(res, 1)

        # Delete the record
        res = client.delete(record_url(recid))
        IndexFlusher(search_class).flush_and_wait()
        result = prefixed_es.search(index='test-invenio-records-rest')
        assert len(result['hits']['hits']) == 0

        # Deleted record should return 410
        assert client.get(record_url(recid)).status_code == 410
        # Record doesn't show up in search
        res = client.get(search_url)
        assert_hits_len(res, 0)
def test_put_on_deleted(app, test_records):
    """Test putting to a deleted record."""
    # create the record using the internal API
    pid, record = test_records[0]

    with app.test_client() as client:
        url = record_url(pid)
        assert client.delete(url).status_code == 204

        res = client.put(url, data='{}', headers=HEADERS)
        assert res.status_code == 410
def test_patch_deleted(app, test_records, test_patch):
    """Test patching deleted record."""
    pid, record = test_records[0]

    with app.test_client() as client:
        # Delete record.
        url = record_url(pid)
        assert client.delete(url).status_code == 204

        # check patch response for deleted resource
        res = client.patch(url, data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 410
def test_validation_error(app, test_records, content_type):
    """Test when record validation fail."""
    HEADERS = [('Accept', 'application/json'), ('Content-Type', content_type)]

    pid, record = test_records[0]

    record['year'] = 1234

    with app.test_client() as client:
        url = record_url(pid)
        res = client.put(url, data=json.dumps(record.dumps()), headers=HEADERS)
        assert res.status_code == 400
def test_patch_deleted(app, test_records, test_patch):
    """Test patching deleted record."""
    pid, record = test_records[0]

    with app.test_client() as client:
        # Delete record.
        url = record_url(pid)
        assert client.delete(url).status_code == 204

        # check patch response for deleted resource
        res = client.patch(url, data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 410
Example #27
0
def test_patch_deleted(app, test_records, test_patch, content_type):
    """Test patching deleted record."""
    HEADERS = [('Accept', 'application/json'), ('Content-Type', content_type)]
    pid, record = test_records[0]

    with app.test_client() as client:
        # Delete record.
        url = record_url(pid)
        assert client.delete(url).status_code == 204

        # check patch response for deleted resource
        res = client.patch(url, data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 410
def test_get_record_no_acls_authenticated(app, db, es, es_acl_prepare,
                                          test_users):
    pid, record = create_record({}, clz=SchemaEnforcingRecord)
    RecordIndexer().index(record)

    # make sure it is flushed
    current_search_client.indices.flush()

    # try to get it ...
    with app.test_client() as client:
        login(client, test_users.u1)
        res = client.get(record_url(pid))
        assert res.status_code == 403  # Forbidden
def test_put_on_deleted(app, test_records, content_type):
    """Test putting to a deleted record."""
    HEADERS = [('Accept', 'application/json'), ('Content-Type', content_type)]

    # create the record using the internal API
    pid, record = test_records[0]

    with app.test_client() as client:
        url = record_url(pid)
        assert client.delete(url).status_code == 204

        res = client.put(url, data='{}', headers=HEADERS)
        assert res.status_code == 410
def test_invalid_put(app, test_records):
    """Test INVALID record put request (PUT .../records/<record_id>)."""
    pid, record = test_records[0]

    record['year'] = 1234
    test_data = record.dumps()

    with app.test_client() as client:
        url = record_url(pid)

        # Non-existing record
        res = client.put(
            record_url('0'), data=json.dumps(test_data), headers=HEADERS)
        assert res.status_code == 404

        # Invalid accept mime type.
        headers = [('Content-Type', 'application/json'),
                   ('Accept', 'video/mp4')]
        res = client.put(url, data=json.dumps(test_data), headers=headers)
        assert res.status_code == 406

        # Invalid content type
        headers = [('Content-Type', 'video/mp4'),
                   ('Accept', 'application/json')]
        res = client.put(url, data=json.dumps(test_data), headers=headers)
        assert res.status_code == 415

        # Invalid JSON
        res = client.put(url, data='{invalid-json', headers=HEADERS)
        assert res.status_code == 400

        # Invalid ETag
        res = client.put(
            url,
            data=json.dumps(test_data),
            headers={'Content-Type': 'application/json', 'If-Match': '"2"'}
        )
        assert res.status_code == 412
def test_validation_error(app, test_records, test_patch):
    """Test VALID record patch request (PATCH .../records/<record_id>)."""
    pid, record = test_records[0]

    # Check that
    assert record.patch(test_patch)

    with app.test_client() as client:
        # Check that patch and record is not the same value for year.
        url = record_url(pid)
        previous_year = get_json(client.get(url))["metadata"]["year"]

        # Patch record
        res = client.patch(url, data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 400
def test_validation_error(app, test_records, test_patch):
    """Test VALID record patch request (PATCH .../records/<record_id>)."""
    pid, record = test_records[0]

    # Check that
    assert record.patch(test_patch)

    with app.test_client() as client:
        # Check that patch and record is not the same value for year.
        url = record_url(pid)
        previous_year = get_json(client.get(url))['metadata']['year']

        # Patch record
        res = client.patch(url, data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 400
def test_validation_error(app, test_records, content_type):
    """Test when record validation fail."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type', content_type)
    ]

    pid, record = test_records[0]

    record['year'] = 1234

    with app.test_client() as client:
        url = record_url(pid)
        res = client.put(url, data=json.dumps(record.dumps()), headers=HEADERS)
        assert res.status_code == 400
Example #34
0
def test_old_signature_backward_compatibility(app, test_records):
    """Check that the old Links_factory signature is still supported.

    This old signature was links_factory(pid), without "record" and "**kwargs"
    parameters.
    """
    # blueprint = create_blueprint(config)
    with app.test_client() as client:
        pid, record = test_records[0]

        res = client.get(record_url(pid))
        assert res.status_code == 200

        # Check metadata
        data = get_json(res)
        assert data['links']['test_link'] == 'http://old_links_factory.com'
def test_patch_deleted(app, test_records, test_patch, content_type):
    """Test patching deleted record."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type', content_type)
    ]
    pid, record = test_records[0]

    with app.test_client() as client:
        # Delete record.
        url = record_url(pid)
        assert client.delete(url).status_code == 204

        # check patch response for deleted resource
        res = client.patch(url, data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 410
Example #36
0
def test_old_signature_backward_compatibility(app, test_records):
    """Check that the old Links_factory signature is still supported.

    This old signature was links_factory(pid), without "record" and "**kwargs"
    parameters.
    """
    # blueprint = create_blueprint(config)
    with app.test_client() as client:
        pid, record = test_records[0]

        res = client.get(record_url(pid))
        assert res.status_code == 200

        # Check metadata
        data = get_json(res)
        assert data['links']['test_link'] == 'http://old_links_factory.com'
def test_valid_put(app, test_records):
    """Test VALID record patch request (PATCH .../records/<record_id>)."""
    pid, record = test_records[0]

    record['year'] = 1234

    with app.test_client() as client:
        url = record_url(pid)
        res = client.put(url, data=json.dumps(record.dumps()), headers=HEADERS)
        assert res.status_code == 200

        # Check that the returned record matches the given data
        assert get_json(res)['metadata']['year'] == 1234

        # Retrieve record via get request
        assert get_json(client.get(url))['metadata']['year'] == 1234
def test_put_on_deleted(app, test_records, content_type):
    """Test putting to a deleted record."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type', content_type)
    ]

    # create the record using the internal API
    pid, record = test_records[0]

    with app.test_client() as client:
        url = record_url(pid)
        assert client.delete(url).status_code == 204

        res = client.put(url, data='{}', headers=HEADERS)
        assert res.status_code == 410
def test_valid_put_etag(app, test_records):
    """Test concurrency control with etags."""
    pid, record = test_records[0]

    record['year'] = 1234

    with app.test_client() as client:
        url = record_url(pid)
        res = client.put(
            url,
            data=json.dumps(record.dumps()),
            headers={
                'Content-Type': 'application/json',
                'If-Match': '"{0}"'.format(record.revision_id)
            })
        assert res.status_code == 200

        assert get_json(client.get(url))['metadata']['year'] == 1234
def test_create_record_no_acls_authenticated(app, db, es, es_acl_prepare,
                                             test_users):
    with app.test_client() as client:

        with db.session.begin_nested():
            # create an empty ACL in order to get the _invenio_explicit_acls filled
            acl = DefaultACL(name='test',
                             schemas=[RECORD_SCHEMA],
                             priority=0,
                             operation='get',
                             originator=test_users.u1)
            db.session.add(acl)
            actor = UserActor(name='test',
                              acl=acl,
                              users=[],
                              originator=test_users.u1)
            db.session.add(actor)

        login(client, test_users.u1)
        response = client.post(records_url(),
                               data=json.dumps({
                                   'title': 'blah',
                                   'contributors': []
                               }),
                               content_type='application/json')
        # print("Response", response.get_data(as_text=True))
        assert response.status_code == 201

        created_record_metadata = get_json(response)['metadata']

        # check that ACLs are not leaking
        assert 'invenio_explicit_acls' not in created_record_metadata

        pid = PersistentIdentifier.get(
            'recid', created_record_metadata['control_number'])
        res = get_from_es(pid)['_source']

        assert res['control_number'] == pid.pid_value
        assert res['$schema'] == 'https://localhost/schemas/' + RECORD_SCHEMA
        assert '_invenio_explicit_acls' in res

        # still can not get it
        res = client.get(record_url(pid))
        assert res.status_code == 403  # Forbidden
Example #41
0
def test_valid_patch(app, test_records, test_patch, content_type):
    """Test VALID record patch request (PATCH .../records/<record_id>)."""
    HEADERS = [('Accept', 'application/json'), ('Content-Type', content_type)]
    pid, record = test_records[0]

    # Check that
    assert record.patch(test_patch)

    with app.test_client() as client:
        # Check that patch and record is not the same value for year.
        url = record_url(pid)
        previous_year = get_json(client.get(url))['metadata']['year']

        # Patch record
        res = client.patch(url, data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 200

        # Check that year changed.
        assert previous_year != get_json(client.get(url))['metadata']['year']
def test_validation_error(app, test_records, test_patch, content_type):
    """Test VALID record patch request (PATCH .../records/<record_id>)."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type', content_type)
    ]
    pid, record = test_records[0]

    # Check that
    assert record.patch(test_patch)

    with app.test_client() as client:
        # Check that patch and record is not the same value for year.
        url = record_url(pid)
        previous_year = get_json(client.get(url))['metadata']['year']

        # Patch record
        res = client.patch(url, data=json.dumps(test_patch), headers=HEADERS)
        assert res.status_code == 400
def test_get_record_without_enabled_acl(app, db, es):
    pid, record = create_record({}, clz=SchemaEnforcingRecord)
    RecordIndexer().index(record)

    # make sure it is flushed
    current_search_client.indices.flush()

    # try to get it ...
    with app.test_client() as client:
        res = client.get(record_url(pid))
        assert res.status_code == 200
        assert get_json(res)['metadata'] == {
            'control_number': pid.pid_value,
            '$schema': 'https://localhost/schemas/records/record-v1.0.0.json'
        }

    # get it directly from ES
    res = get_from_es(pid)['_source']
    assert res['control_number'] == pid.pid_value
    assert res['$schema'] == 'https://localhost/schemas/' + RECORD_SCHEMA
Example #44
0
def test_valid_put(app, es, test_records, content_type, search_url,
                   search_class):
    """Test VALID record patch request (PATCH .../records/<record_id>)."""
    HEADERS = [('Accept', 'application/json'), ('Content-Type', content_type)]

    pid, record = test_records[0]

    record['year'] = 1234

    with app.test_client() as client:
        url = record_url(pid)
        res = client.put(url, data=json.dumps(record.dumps()), headers=HEADERS)
        assert res.status_code == 200

        # Check that the returned record matches the given data
        assert get_json(res)['metadata']['year'] == 1234
        IndexFlusher(search_class).flush_and_wait()
        res = client.get(search_url, query_string={"year": 1234})
        assert_hits_len(res, 1)
        # Retrieve record via get request
        assert get_json(client.get(url))['metadata']['year'] == 1234
def test_valid_create(app, db, test_data, search_url):
    """Test VALID record creation request (POST .../records/)."""
    with app.test_client() as client:
        # Create record
        res = client.post(
            search_url, data=json.dumps(test_data[0]), headers=HEADERS)
        assert res.status_code == 201

        # Check that the returned record matches the given data
        data = get_json(res)
        for k in test_data[0].keys():
            assert data['metadata'][k] == test_data[0][k]

        # Recid has been added in control number
        assert data['metadata']['control_number']

        # Check location header
        assert res.headers['Location'] == data['links']['self']

        # Record can be retrieved.
        assert client.get(record_url(data['id'])).status_code == 200
Example #46
0
def test_item_get(app, test_records):
    """Test record retrieval."""
    with app.test_client() as client:
        pid, record = test_records[0]

        res = client.get(record_url(pid))
        assert res.status_code == 200
        assert res.headers['ETag'] == '"{}"'.format(record.revision_id)

        # Check metadata
        data = get_json(res)
        for k in ['id', 'created', 'updated', 'metadata', 'links']:
            assert k in data

        assert data['id'] == int(pid.pid_value)
        assert data['metadata'] == record.dumps()

        # Check self links
        client.get(to_relative_url(data['links']['self']))
        assert res.status_code == 200
        assert data == get_json(res)
def test_item_get(app, test_records):
    """Test record retrieval."""
    with app.test_client() as client:
        pid, record = test_records[0]

        res = client.get(record_url(pid))
        assert res.status_code == 200
        assert res.headers["ETag"] == '"{}"'.format(record.revision_id)

        # Check metadata
        data = get_json(res)
        for k in ["id", "created", "updated", "metadata", "links"]:
            assert k in data

        assert data["id"] == int(pid.pid_value)
        assert data["metadata"] == record.dumps()

        # Check self links
        client.get(to_relative_url(data["links"]["self"]))
        assert res.status_code == 200
        assert data == get_json(res)
def test_valid_put(app, es, test_records, content_type, search_url,
                   search_class):
    """Test VALID record patch request (PATCH .../records/<record_id>)."""
    HEADERS = [
        ('Accept', 'application/json'),
        ('Content-Type', content_type)
    ]

    pid, record = test_records[0]

    record['year'] = 1234

    with app.test_client() as client:
        url = record_url(pid)
        res = client.put(url, data=json.dumps(record.dumps()), headers=HEADERS)
        assert res.status_code == 200

        # Check that the returned record matches the given data
        assert get_json(res)['metadata']['year'] == 1234
        IndexFlusher(search_class).flush_and_wait()
        res = client.get(search_url, query_string={"year": 1234})
        assert_hits_len(res, 1)
        # Retrieve record via get request
        assert get_json(client.get(url))['metadata']['year'] == 1234
def test_put_on_deleted(app, db, es, test_data, content_type, search_url,
                        search_class):
    """Test putting to a deleted record."""
    with app.test_client() as client:
        HEADERS = [
            ('Accept', 'application/json'),
            ('Content-Type', content_type)
        ]
        HEADERS.append(('Content-Type', content_type))

        # Create record
        res = client.post(
            search_url, data=json.dumps(test_data[0]), headers=HEADERS)
        assert res.status_code == 201

        url = record_url(get_json(res)['id'])
        assert client.delete(url).status_code == 204
        IndexFlusher(search_class).flush_and_wait()
        res = client.get(search_url,
                         query_string={'title': test_data[0]['title']})
        assert_hits_len(res, 0)

        res = client.put(url, data='{}', headers=HEADERS)
        assert res.status_code == 410