Beispiel #1
0
def document_post(country_name):
    try:
        target_country = Country(country_name)
    except Exception as e:
        raise BadCountryNameError(e)

    object_lake_repo = ObjectLakeRepo(Config.OBJECT_LAKE_CONN)
    object_acl_repo = ObjectACLRepo(Config.OBJECT_ACL_CONN)

    if len(request.files) == 0:
        raise NoInputFileError()
    elif len(request.files) > 1:
        raise TooManyFilesError(len(request.files))

    # get the first file, whatever way it's called
    file = request.files[list(request.files.keys())[0]]

    use_case = StoreObjectUseCase(
        object_acl_repo=object_acl_repo,
        object_lake_repo=object_lake_repo,
    )

    try:
        multihash = use_case.execute(fobj=file, target_country=target_country)
    except Exception as e:
        logger.exception(e)
        raise InternalServerError(e)

    return Response(json.dumps({
        "multihash": multihash,
    }),
                    mimetype='application/json',
                    status=HTTPStatus.OK)
Beispiel #2
0
def document_fetch(uri):
    if not URI(uri).is_valid_multihash():
        raise InvalidURIError()

    object_lake_repo = ObjectLakeRepo(Config.OBJECT_LAKE_CONN)
    object_acl_repo = ObjectACLRepo(Config.OBJECT_ACL_CONN)

    use_case = AuthenticatedObjectAccessUseCase(
        object_acl_repo=object_acl_repo,
        object_lake_repo=object_lake_repo,
    )

    try:
        auth_country = Country(request.auth['country'])
    except Exception as e:
        raise BadCountryNameError(e)

    try:
        document_body = use_case.execute(uri, auth_country)
    except Exception as e:
        logger.exception(e)
        raise InternalServerError(e)

    if document_body is not None:
        return Response(
            document_body,
            status=HTTPStatus.OK,
            mimetype='binary/octet-stream',  # TODO: correct mimetype?
            # TODO: some information about the file content?
        )
    else:
        raise DocumentNotFoundError(uri, auth_country)
Beispiel #3
0
def message_retrieve(reference):
    # TODO: auth
    repo = MessageLakeRepo(Config.MESSAGE_LAKE_CONN)

    use_case = GetMessageBySenderRefUseCase(repo)

    try:
        message = use_case.execute(reference)
    except Exception as e:
        if e.__class__.__name__ == 'NoSuchKey':
            message = None
        else:
            # logging.exception(e)
            # we have a handler to catch this exception
            # but in future it will be easier to decide
            # what kind of info we want to put here
            raise InternalServerError(e)

    if message:
        return Response(
            json.dumps(message, cls=ser.MessageJSONEncoder),
            status=HTTPStatus.CREATED,
            mimetype='application/json',
            # headers={'Location': message_url}
        )
    else:
        raise MessageNotFoundError(reference)
Beispiel #4
0
def message_patch(reference):
    """
    ---
    patch:
      parameters:
      - in: path
        name: reference
        schema:
          type: string
        required: true
      requestBody:
        content:
          application/json:
            schema: MessageSchema
      responses:
        200:
          description: Update a message
          content:
            application/json:
              schema: MessageSchema

    """
    # TODO: auth
    json_payload = request.get_json(silent=True)
    if not json_payload or not isinstance(json_payload, dict):
        raise MessageDataEmptyError()

    status = json_payload.get(STATUS_KEY)

    if status and status not in FINAL_STATUSES:
        raise UnexpectedMessageStatusError(json_payload.get('status'),
                                           FINAL_STATUSES + [None])

    repo = MessageLakeRepo(Config.MESSAGE_LAKE_CONN)
    publish_notifications_repo = NotificationsRepo(
        Config.PUBLISH_NOTIFICATIONS_REPO_CONN)

    use_case = PatchMessageMetadataUseCase(repo, publish_notifications_repo)
    try:
        message = use_case.execute(reference, json_payload)
    except UseCaseError as e:
        raise e
    except Exception as e:
        if e.__class__.__name__ == 'NoSuchKey':
            message = None
        else:
            # logging.exception(e)
            # we have a handler to catch this exception
            # but in future it will be easier to decide
            # what kind of info we want to put here
            raise InternalServerError(e)
    if not message:
        raise MessageNotFoundError(reference)
    return Response(
        json.dumps(message, cls=ser.MessageJSONEncoder),
        status=HTTPStatus.OK,
        mimetype='application/json',
    )
Beispiel #5
0
def test_patch_error(NotificationsRepoMock, MessageLakeRepoMock, client):

    invalid_mimetype = "application/x-www-form-urlencoded"

    resp = client.patch(PATCH_URL.format(MESSAGE_REFERENCE),
                        data={},
                        mimetype=invalid_mimetype)

    assert resp.status_code == HTTPStatus.UNSUPPORTED_MEDIA_TYPE
    assert resp.content_type == VALID_RESPONSE_MIMETYPE
    assert resp.get_json() == error_response_json_template(
        UnsupportedMediaTypeError(invalid_mimetype, ['application/json'], []))

    resp = client.patch(PATCH_URL.format(MESSAGE_REFERENCE), json={})

    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.content_type == VALID_RESPONSE_MIMETYPE
    assert resp.get_json() == error_response_json_template(
        MessageDataEmptyError())

    invalid_status = "Clearly some invalid status"
    resp = client.patch(PATCH_URL.format(MESSAGE_REFERENCE),
                        json={"status": invalid_status})

    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.content_type == VALID_RESPONSE_MIMETYPE
    assert resp.get_json() == error_response_json_template(
        UnexpectedMessageStatusError(invalid_status,
                                     VALID_PATCH_STATUSES + [None]))

    message_lake_repo = MessageLakeRepoMock.return_value
    message_lake_repo.get.side_effect = NoSuchKey()
    resp = client.patch(PATCH_URL.format(MESSAGE_REFERENCE),
                        json={"status": VALID_PATCH_STATUSES[0]})

    message_lake_repo.get.assert_called_once()

    assert resp.status_code == HTTPStatus.NOT_FOUND
    assert resp.content_type == VALID_RESPONSE_MIMETYPE
    assert resp.get_json() == error_response_json_template(
        MessageNotFoundError(MESSAGE_REFERENCE))

    # testing random exception from use case
    message_lake_repo.reset_mock()
    message_lake_repo.get.side_effect = None

    with mock.patch(PATCH_MESSAGE_METADATA_USE_CASE) as UseCase:
        uc = UseCase.return_value
        uc.execute.side_effect = RandomException()
        resp = client.patch(PATCH_URL.format(MESSAGE_REFERENCE),
                            json={"status": VALID_PATCH_STATUSES[0]})

        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.content_type == VALID_RESPONSE_MIMETYPE
        assert resp.get_json() == error_response_json_template(
            InternalServerError(uc.execute.side_effect))
        uc.execute.assert_called_once()
Beispiel #6
0
def test_post_error(client):

    # just to prevent creation of the actual repo
    with mock.patch(BC_INBOX_REPO) as RepoMock:
        _test_post_message_received_unsupported_mimetype(client, url=POST_URL)
        _test_post_message_received_empty_body(client, url=POST_URL)

        _test_post_message_missing_required_attr(client, VALID_MESSAGE_DATA_DICT, url=POST_URL)

        _test_post_message_validation_failed(
            Message,
            MESSAGE_CLASS,
            client,
            VALID_MESSAGE_DATA_DICT,
            url=POST_URL
        )

    with mock.patch(BC_INBOX_REPO) as RepoMock:
        # Repo exceptions may contain sensitive info.
        # Maybe their str should not be passed as message
        # and logged internally instead

        # testing random repo specific exception response
        post = RepoMock.return_value.post
        post.side_effect = Exception('Repo Specific Exception')

        resp = client.post(POST_URL, json=VALID_MESSAGE_DATA_DICT)

        post.assert_called_once()

        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.content_type == VALID_RESPONSE_MIMETYPE
        assert resp.get_json() == error_response_json_template(
            InternalServerError(post.side_effect)
        )
        # testing expected repo inablity to post message
        # when post returns None
        post.reset_mock()
        post.return_value = None
        post.side_effect = None

        resp = client.post(POST_URL, json=VALID_MESSAGE_DATA_DICT)

        post.assert_called_once()

        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.content_type == VALID_RESPONSE_MIMETYPE
        assert resp.get_json() == error_response_json_template(
            UnableWriteToInboxError()
        )
Beispiel #7
0
def document_fetch(uri):
    if not URI(uri).is_valid_multihash():
        raise InvalidURIError()

    object_lake_repo = ObjectLakeRepo(Config.OBJECT_LAKE_CONN)
    object_acl_repo = ObjectACLRepo(Config.OBJECT_ACL_CONN)

    use_case = AuthenticatedObjectAccessUseCase(
        object_acl_repo=object_acl_repo,
        object_lake_repo=object_lake_repo,
    )

    request_auth = getattr(request, "auth", None)
    if request_auth and 'country' in request_auth:
        try:
            auth_country = Country(request_auth['country'])
        except Exception as e:
            raise BadCountryNameError(e)
    else:
        # no auth is provided, trust the GET request
        # assuming JWT will handle it
        # TODO: ensure that the auth provided allows access from that country
        try:
            auth_country = Country(request.args["as_country"])
        except Exception as e:
            raise BadCountryNameError(e)

    try:
        document_body = use_case.execute(uri, auth_country)
    except Exception as e:
        logger.exception(e)
        raise InternalServerError(e)

    if document_body is not None:
        return Response(
            document_body,
            status=HTTPStatus.OK,
            mimetype='binary/octet-stream',  # TODO: correct mimetype?
            # TODO: some information about the file content?
        )
    else:
        raise DocumentNotFoundError(uri, auth_country)
Beispiel #8
0
def test_get_error(RepoMock, client):

    instance = RepoMock.return_value
    instance.get.side_effect = NoSuchKey()

    resp = client.get(GET_URL.format(MESSAGE_REFERENCE))
    instance.get.assert_called_once()
    assert resp.mimetype == VALID_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.NOT_FOUND
    assert resp.get_json() == error_response_json_template(
        MessageNotFoundError(MESSAGE_REFERENCE))

    instance.get.reset_mock()

    instance.get.side_effect = RandomException()
    resp = client.get(GET_URL.format(MESSAGE_REFERENCE))
    instance.get.assert_called_once()
    assert resp.mimetype == VALID_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
    assert resp.get_json() == error_response_json_template(
        InternalServerError(instance.get.side_effect))
Beispiel #9
0
def document_post(jurisdiction_name):
    """
    ---
    post:
      parameters:
      - in: path
        name: jurisdiction_name
        required: true
        schema:
          type: string
      requestBody:
        content:
          application/binary:
            schema:
                format: binary
                type: string
      responses:
        200:
          content:
            application/json:
              schema:
                properties:
                  multihash:
                    format: uuid
                    type: string
                type: object
          description: Returns document id
    """
    try:
        target_jurisdiction = Jurisdiction(jurisdiction_name)
    except Exception as e:
        raise BadJurisdictionNameError(e)

    object_lake_repo = ObjectLakeRepo(Config.OBJECT_LAKE_CONN)
    object_acl_repo = ObjectACLRepo(Config.OBJECT_ACL_CONN)

    if len(request.files) == 0:
        raise NoInputFileError()
    elif len(request.files) > 1:
        raise TooManyFilesError(len(request.files))

    # get the first file, whatever way it's called
    file = request.files[list(request.files.keys())[0]]

    use_case = StoreObjectUseCase(
        object_acl_repo=object_acl_repo,
        object_lake_repo=object_lake_repo,
    )

    try:
        multihash = use_case.execute(fobj=file,
                                     target_jurisdiction=target_jurisdiction)
    except Exception as e:
        logger.exception(e)
        raise InternalServerError(e)

    return Response(json.dumps({
        "multihash": multihash,
    }),
                    mimetype='application/json',
                    status=HTTPStatus.OK)
Beispiel #10
0
def document_fetch(uri):
    """
    ---
    get:
      parameters:
      - in: path
        name: uri
        required: true
        schema:
          format: uuid
          type: string
      responses:
        200:
          content:
            application/binary:
              schema:
                format: binary
                type: string
          description: Returns document
    """
    if not URI(uri).is_valid_multihash():
        raise InvalidURIError()

    object_lake_repo = ObjectLakeRepo(Config.OBJECT_LAKE_CONN)
    object_acl_repo = ObjectACLRepo(Config.OBJECT_ACL_CONN)

    use_case = AuthenticatedObjectAccessUseCase(
        object_acl_repo=object_acl_repo,
        object_lake_repo=object_lake_repo,
    )

    request_auth = getattr(request, "auth", None)
    if request_auth and 'jurisdiction' in request_auth:
        try:
            auth_jurisdiction = Jurisdiction(request_auth['jurisdiction'])
        except Exception as e:
            raise BadJurisdictionNameError(e)
    else:
        # no auth is provided, trust the GET request
        # assuming JWT will handle it
        # TODO: ensure that the auth provided allows access from that country
        try:
            auth_jurisdiction = Jurisdiction(request.args["as_jurisdiction"])
        except Exception as e:
            raise BadJurisdictionNameError(e)

    try:
        document_body = use_case.execute(uri, auth_jurisdiction)
    except Exception as e:
        logger.exception(e)
        raise InternalServerError(e)

    if document_body is not None:
        return Response(
            document_body,
            status=HTTPStatus.OK,
            mimetype='binary/octet-stream',  # TODO: correct mimetype?
            # TODO: some information about the file content?
        )
    else:
        raise DocumentNotFoundError(uri, auth_jurisdiction)
Beispiel #11
0
def test_error_handlers(app, client):

    generic_http_use_case_error_instance = CustomUseCaseError(
        generic_http_error=True)
    use_case_error_instance = CustomUseCaseError()

    custom_error_instance = ValidationError()
    generic_http_error_instance = exceptions.NotFound()
    internal_server_error_exception_instance = Exception('Error')
    errors_list_instance = ErrorsList(custom_error_instance,
                                      custom_error_instance)

    @app.route('/post-method', methods=['POST'])
    def post_method():
        return 'Hello'

    @app.route('/errors-list')
    def errors_list():
        raise errors_list_instance

    @app.route('/generic-http-error')
    def generic_http_error():
        raise generic_http_error_instance

    @app.route('/internal-server-error')
    def internal_server_error():
        raise internal_server_error_exception_instance

    @app.route('/custom-error')
    def custom_error():
        raise custom_error_instance

    @app.route('/use-case-error')
    def use_case_error():
        raise use_case_error_instance

    @app.route('/generic-http-use-case-error')
    def generic_http_use_case_error():
        raise generic_http_use_case_error_instance

    # testing flask defaul error wrapping
    resp = client.get('/post-method')
    assert resp.status_code == StatusCode.METHOD_NOT_ALLOWED, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        GenericHTTPError(StatusCode.METHOD_NOT_ALLOWED))

    # testing werkzeug error thrown manually
    resp = client.get('/generic-http-error')
    assert resp.status_code == StatusCode.NOT_FOUND, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        GenericHTTPError(generic_http_error_instance))

    # testing internal exception error
    resp = client.get('/internal-server-error')
    assert resp.status_code == StatusCode.INTERNAL_SERVER_ERROR, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        InternalServerError(internal_server_error_exception_instance))

    # testing custom error
    resp = client.get('/custom-error')
    assert resp.status_code == custom_error_instance.status_code, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        custom_error_instance)

    # testing several errors response
    resp = client.get('/errors-list')
    assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        *errors_list_instance.errors)

    # testing use case error
    resp = client.get('/use-case-error')
    assert resp.status_code == use_case_error_instance.status, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        UseCaseError(use_case_error_instance))

    # testing use case
    resp = client.get('/generic-http-use-case-error')
    assert resp.status_code == generic_http_use_case_error_instance.status, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        GenericHTTPError(generic_http_use_case_error_instance.status,
                         detail=generic_http_use_case_error_instance.detail,
                         source=generic_http_use_case_error_instance.source))
Beispiel #12
0
def test_basic_errors():

    assert UseCaseError(CustomUseCaseError()).to_dict() == {
        TITLE_KEY: 'Custom Use Case Error',
        STATUS_KEY: 'Bad Request',
        CODE_KEY: 'use-case-error',
        DETAIL_KEY: CustomUseCaseError.detail,
        SOURCE_KEY: CustomUseCaseError.source
    }

    assert ValidationError(**ERROR_KWARGS).to_dict() == {
        STATUS_KEY: 'Bad Request',
        CODE_KEY: 'validation-error',
        TITLE_KEY: 'Validation Error',
        **ERROR_KWARGS
    }

    assert MissingAttributesError(['1', '2', '3']).to_dict() == {
        TITLE_KEY: 'Missing Attributes Error',
        CODE_KEY: 'missing-attributes-error',
        STATUS_KEY: 'Bad Request',
        DETAIL_KEY: "Missing required attributes: ['1', '2', '3'].",
        SOURCE_KEY: ['1', '2', '3']
    }

    assert InternalServerError(Exception('Test')).to_dict() == {
        STATUS_KEY: 'Internal Server Error',
        CODE_KEY: 'internal-server-error',
        TITLE_KEY: 'Internal Server Error',
        SOURCE_KEY: [{
            'type': Exception.__name__,
            'str': str(Exception('Test'))
        }],
        DETAIL_KEY: 'Unexpected server error occured.'
    }

    # testing generation of required fields using werkzeug.exceptions
    # used for error handler generic http excetions formatting
    assert GenericHTTPError(exceptions.MethodNotAllowed()).to_dict() == {
        STATUS_KEY: 'Method Not Allowed',
        CODE_KEY: 'generic-http-error',
        TITLE_KEY: 'Method Not Allowed'
    }

    # testing equality between 3 different creation methods
    assert GenericHTTPError(
        exceptions.NotFound()).to_dict() == GenericHTTPError(404).to_dict()
    assert GenericHTTPError(
        exceptions.NotFound()).to_dict() == GenericHTTPError(
            StatusCode.NOT_FOUND).to_dict()
    # testing exception cases
    with pytest.raises(ValueError) as e:
        GenericHTTPError(0)
        assert str(
            e
        ) == 'Non generic HTTP exception. Can\'t find class for status: "0"'
    with pytest.raises(TypeError) as e:
        GenericHTTPError("Not Found")
        assert str(e) == (
            'GenericHTTPError "exception" kwarg must be the instance of:' +
            "['werkzeug.exceptions.HTTPException', 'http.HTTPStatus', 'int']")
    # testing extension of standard errors
    not_found_extended_dict = GenericHTTPError(exceptions.NotFound(),
                                               detail='Something',
                                               source=['Something']).to_dict()

    assert not_found_extended_dict == {
        STATUS_KEY: 'Not Found',
        CODE_KEY: 'generic-http-error',
        TITLE_KEY: 'Not Found',
        DETAIL_KEY: 'Something',
        SOURCE_KEY: ['Something']
    }
    # this way of creation is my favorite
    assert not_found_extended_dict == GenericHTTPError(StatusCode.NOT_FOUND,
                                                       detail='Something',
                                                       source=['Something'
                                                               ]).to_dict()
    # this one is ok, but it's always better to use constants
    assert not_found_extended_dict == GenericHTTPError(404,
                                                       detail='Something',
                                                       source=['Something'
                                                               ]).to_dict()

    # using enum item object
    assert not_found_extended_dict == GenericHTTPError(StatusCode(404),
                                                       detail='Something',
                                                       source=['Something'
                                                               ]).to_dict()

    with pytest.raises(ValueError) as e:
        ErrorsList(Exception('Hello'), GenericHTTPError(404))
    assert str(e.value) == 'All errors should be the instance of BaseError'
Beispiel #13
0
def test_get_document_errors(ObjectLakeRepoMock, ObjectACLRepoMock, client):

    # # testing unauthorized
    # resp = client.get(DOCUMENT_GET_URL.format(VALID_DOCUMENT_URI))
    # assert resp.status_code == HTTPStatus.UNAUTHORIZED

    # testing invalid URI error
    resp = client.get(
        DOCUMENT_GET_URL.format(INVALID_DOCUMENT_URI),
        headers=VALID_AUTH_HEADERS
    )

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE, resp.data
    assert resp.status_code == HTTPStatus.BAD_REQUEST, resp.data
    assert resp.get_json() == error_response_json_template(
        InvalidURIError()
    )

    # testing invalid country auth headers
    try:
        Country(INVALID_COUNTRY_NAME)
    except Exception as e:
        country_exception = e

    resp = client.get(
        DOCUMENT_GET_URL.format(VALID_DOCUMENT_URI),
        headers=INVALID_AUTH_HEADERS
    )

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE, resp.data
    assert resp.status_code == HTTPStatus.BAD_REQUEST, resp.data
    assert resp.get_json() == error_response_json_template(
        BadCountryNameError(country_exception)
    )

    search = ObjectACLRepoMock.return_value.search
    get_body = ObjectLakeRepoMock.return_value.get_body

    # testing not authenticated user
    search.return_value = []

    resp = client.get(
        DOCUMENT_GET_URL.format(VALID_DOCUMENT_URI),
        headers=VALID_AUTH_HEADERS
    )

    search.assert_called_once()
    get_body.assert_not_called()

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE, resp.data
    assert resp.status_code == HTTPStatus.NOT_FOUND, resp.data
    assert resp.get_json() == error_response_json_template(
        DocumentNotFoundError(
            VALID_DOCUMENT_URI,
            Country(VALID_COUNTRY_NAME)
        )
    )

    # testing unexpected acl repo error
    search.reset_mock()
    get_body.reset_mock()
    search.side_effect = Exception('Very bad times indeed')

    resp = client.get(
        DOCUMENT_GET_URL.format(VALID_DOCUMENT_URI),
        headers=VALID_AUTH_HEADERS
    )

    search.assert_called_once()
    get_body.assert_not_called()

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE, resp.data
    assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR, resp.data
    assert resp.get_json() == error_response_json_template(
        InternalServerError(search.side_effect)
    )

    # testing expected lake repo error
    class NoSuchKey(Exception):
        pass

    search.reset_mock()
    get_body.reset_mock()
    search.side_effect = None
    search.return_value = [Country(VALID_COUNTRY_NAME)]
    get_body.side_effect = NoSuchKey

    resp = client.get(
        DOCUMENT_GET_URL.format(VALID_DOCUMENT_URI),
        headers=VALID_AUTH_HEADERS
    )

    search.assert_called_once()
    get_body.assert_called_once()

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE, resp.data
    assert resp.status_code == HTTPStatus.NOT_FOUND, resp.data
    assert resp.get_json() == error_response_json_template(
        DocumentNotFoundError(
            VALID_DOCUMENT_URI,
            Country(VALID_COUNTRY_NAME)
        )
    )

    # testing get_body return None
    # Can it even happen? Or we should consider NoSuchKey
    # error to be only way to get None as a result
    # of the use case?

    search.reset_mock()
    get_body.reset_mock()
    search.return_value = [Country(VALID_COUNTRY_NAME)]
    get_body.side_effect = None
    get_body.return_value = None

    resp = client.get(
        DOCUMENT_GET_URL.format(VALID_DOCUMENT_URI),
        headers=VALID_AUTH_HEADERS
    )

    search.assert_called_once()
    get_body.assert_called_once()

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE, resp.data
    assert resp.status_code == HTTPStatus.NOT_FOUND, resp.data
    assert resp.get_json() == error_response_json_template(
        DocumentNotFoundError(
            VALID_DOCUMENT_URI,
            Country(VALID_COUNTRY_NAME)
        )
    )

    # testing unexpected lake repo error
    search.reset_mock()
    get_body.reset_mock()
    search.return_value = [Country(VALID_COUNTRY_NAME)]
    get_body.side_effect = Exception('Bad times came')

    resp = client.get(
        DOCUMENT_GET_URL.format(VALID_DOCUMENT_URI),
        headers=VALID_AUTH_HEADERS
    )

    search.assert_called_once()
    get_body.assert_called_once()

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE, resp.data
    assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR, resp.data
    assert resp.get_json() == error_response_json_template(
        InternalServerError(get_body.side_effect)
    )
Beispiel #14
0
def test_post_document_errors(ObjectLakeRepoMock, ObjectACLRepoMock, client):

    resp = client.post(
        INVALID_POST_REQUEST_COUNTRY_URL,
        mimetype=INVALID_POST_REQUEST_MIMETYPE,
        data={}
    )

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.UNSUPPORTED_MEDIA_TYPE
    assert resp.get_json() == error_response_json_template(
        UnsupportedMediaTypeError(
            INVALID_POST_REQUEST_MIMETYPE,
            [VALID_POST_REQUEST_MIMETYPE],
            []
        )
    )

    try:
        Country(INVALID_COUNTRY_NAME)
    except Exception as e:
        country_exception = e

    resp = client.post(
        INVALID_POST_REQUEST_COUNTRY_URL,
        mimetype=VALID_POST_REQUEST_MIMETYPE,
        data={}
    )

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.get_json() == error_response_json_template(
        BadCountryNameError(country_exception)
    )

    resp = client.post(
        VALID_POST_REQUEST_COUNTRY_URL,
        mimetype=VALID_POST_REQUEST_MIMETYPE,
        data={}
    )

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.get_json() == error_response_json_template(
        NoInputFileError()
    )

    resp = client.post(
        VALID_POST_REQUEST_COUNTRY_URL,
        mimetype=VALID_POST_REQUEST_MIMETYPE,
        data=get_too_many_post_request_files()
    )

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.get_json() == error_response_json_template(
        TooManyFilesError(2)
    )

    allow_access_to = ObjectACLRepoMock.return_value.allow_access_to
    post_from_file_obj = ObjectLakeRepoMock.return_value.post_from_file_obj

    allow_access_to.side_effect = Exception('Very bad thing: ACL')
    post_from_file_obj.side_effect = Exception('Very bad thing: Lake')

    resp = client.post(
        VALID_POST_REQUEST_COUNTRY_URL,
        mimetype=VALID_POST_REQUEST_MIMETYPE,
        data=get_valid_post_request_files()
    )

    allow_access_to.assert_called_once()

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
    assert resp.get_json() == error_response_json_template(
        InternalServerError(allow_access_to.side_effect)
    )

    allow_access_to.reset_mock()
    allow_access_to.side_effect = None

    resp = client.post(
        VALID_POST_REQUEST_COUNTRY_URL,
        mimetype=VALID_POST_REQUEST_MIMETYPE,
        data=get_valid_post_request_files()
    )

    allow_access_to.assert_called_once()
    post_from_file_obj.assert_called_once()

    assert resp.mimetype == VALID_ERROR_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
    assert resp.get_json() == error_response_json_template(
        InternalServerError(post_from_file_obj.side_effect)
    )
Beispiel #15
0
def UnableToPostSubscriptionError():
    return InternalServerError(detail='Unable to post data to repository', )