Example #1
0
def test_decorators(app, client):

    content_type = 'application/json'
    invalid_content_type = 'text/javascript'

    @app.route('/include')
    @routing.mimetype(['application/json'])
    def mimetype_include_test():
        return 'Hello', StatusCode.OK

    @app.route('/exclude')
    @routing.mimetype([], [invalid_content_type])
    def mimetype_exclude_test():
        return 'Hello', StatusCode.OK

    resp = client.get('/include', content_type=content_type)
    assert resp.status_code == StatusCode.OK, resp.data

    resp = client.get('/include', content_type=invalid_content_type)
    assert resp.status_code == StatusCode.UNSUPPORTED_MEDIA_TYPE, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        routing.UnsupportedMediaTypeError(invalid_content_type, [content_type],
                                          []))

    resp = client.get('/exclude', content_type=content_type)
    assert resp.status_code == StatusCode.OK, resp.data

    resp = client.get('/exclude', content_type=invalid_content_type)
    assert resp.status_code == StatusCode.UNSUPPORTED_MEDIA_TYPE, resp.data
    assert resp.get_json() == handlers.error_response_json_template(
        routing.UnsupportedMediaTypeError(invalid_content_type, [],
                                          [invalid_content_type]))
Example #2
0
    def test_request_with_all_missing_required_attribute__should_return_error(
            self):
        data = remove_params(VALID_SUBSCRIBE_DATA, REQUIRED_ATTRS)
        resp = self.client.post(POST_URL,
                                data=data,
                                content_type=VALID_REQUEST_CONTENT_TYPE)
        assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
        assert resp.get_json() == error_response_json_template(
            errors.MissingAttributesError(REQUIRED_ATTRS))

        resp = self.client.post(POST_URL,
                                data=INVALID_TOPIC_DATA,
                                content_type=VALID_REQUEST_CONTENT_TYPE)
        assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
        assert resp.get_json() == error_response_json_template(
            TopicValidationError(
                'Predicates shorter than 4 elements must include wildcard as the last element'
            ))

        resp = self.client.post(POST_URL,
                                data=INVALID_CALLBACK_DATA,
                                content_type=VALID_REQUEST_CONTENT_TYPE)
        assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
        assert resp.get_json() == error_response_json_template(
            CallbackURLValidationError('URL must contain scheme'))
Example #3
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()
Example #4
0
def _test_post_message_received_empty_body(client, url=POST_URL):
    resp = client.post(url, mimetype=VALID_REQUEST_MIMETYPE)
    assert resp.mimetype == VALID_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.get_json() == error_response_json_template(
        MessageDataEmptyError())

    resp = client.post(url, json={})
    assert resp.mimetype == VALID_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.get_json() == error_response_json_template(
        MessageDataEmptyError())
Example #5
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()
        )
Example #6
0
def _test_post_message_received_unsupported_mimetype(client, url=POST_URL):
    resp = client.post(url, mimetype=INVALID_REQUEST_MIMETYPE, data={})
    assert resp.mimetype == VALID_RESPONSE_MIMETYPE
    assert resp.status_code == HTTPStatus.UNSUPPORTED_MEDIA_TYPE
    assert resp.get_json() == error_response_json_template(
        UnsupportedMediaTypeError(INVALID_REQUEST_MIMETYPE,
                                  [VALID_REQUEST_MIMETYPE], []))
Example #7
0
def _test_post_message_validation_failed(
        message_class,
        message_class_path,
        client,
        valid_data,
        url=POST_URL,
        api=""
):
    # it's pretty much impossible yet to get around from_dict validation without mocking
    require_allowed = ["sender_ref"] if api == "rx" else []
    message = message_class.from_dict(valid_data, require_allowed=require_allowed)
    message.kwargs['spurious_attr'] = 'Something suspicious'
    remove_message_params(message.kwargs, keys=message_class.required_attrs, copy_data=False, set_none=True)

    with mock.patch(message_class_path + '.from_dict') as from_dict:
        from_dict.return_value = message

        resp = client.post(url, json=valid_data)
        from_dict.assert_called_once()

        assert resp.mimetype == VALID_RESPONSE_MIMETYPE
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.get_json() == error_response_json_template(
            MessageValidationError(
                source=[
                    'spurious attr: spurious_attr',
                    'sender is not a jurisdiction: None',
                    'receiver is not a jurisdiction: None',
                    'subject is empty',
                    'obj is not a URI: None',
                    'predicate is not a URI: None'
                ]
            )
        )
Example #8
0
 def test_request__with_unknown_mode_error__should_return_error(self):
     resp = self.client.post(POST_URL,
                             data=INVALID_MODE_DATA,
                             content_type=VALID_REQUEST_CONTENT_TYPE)
     assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
     assert resp.get_json() == error_response_json_template(
         UnknownModeError(INVALID_MODE_DATA[MODE_ATTR_KEY]))
Example #9
0
 def test_request__when_subscription_not_found__should_return_error(self):
     resp = self.client.post(POST_URL,
                             data=VALID_UNSUBSCRIBE_DATA,
                             content_type=VALID_REQUEST_CONTENT_TYPE)
     assert resp.status_code == StatusCode.NOT_FOUND, resp.data
     assert resp.get_json() == error_response_json_template(
         SubscriptionNotFoundError())
Example #10
0
 def test_request_with_one_missing_required_attribute__should_return_error(
         self):
     for key in REQUIRED_ATTRS:
         data = remove_params(VALID_SUBSCRIBE_DATA, keys=[key])
         resp = self.client.post(POST_URL,
                                 data=data,
                                 content_type=VALID_REQUEST_CONTENT_TYPE)
         assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
         assert resp.get_json() == error_response_json_template(
             errors.MissingAttributesError([key]))
Example #11
0
def _test_post_message_missing_required_attr(client, valid_data, url=POST_URL):
    for key in Message.required_attrs:

        data = remove_message_params(valid_data, keys=[key])
        resp = client.post(url, json=data)

        assert resp.mimetype == VALID_RESPONSE_MIMETYPE
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.get_json() == error_response_json_template(
            MessageDeserializationError(source=['\'{}\''.format(key)]))
Example #12
0
 def test_request_with_wrong_mime_type__should_return_error(self):
     # forcing correct mimetype
     for content_type in INVALID_CONTENT_TYPES:
         resp = self.client.post(POST_URL,
                                 data=VALID_SUBSCRIBE_DATA,
                                 content_type=content_type)
         assert resp.status_code == StatusCode.UNSUPPORTED_MEDIA_TYPE, resp.data
         assert resp.get_json() == error_response_json_template(
             routing.UnsupportedMediaTypeError(content_type,
                                               [VALID_REQUEST_CONTENT_TYPE],
                                               []))
Example #13
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))
Example #14
0
def test_post_error(RepoMock, client):
    repo = RepoMock.return_value
    post = repo.post
    delete = repo.delete
    # forcing correct mimetype
    for content_type in INVALID_CONTENT_TYPES:
        resp = client.post(POST_URL,
                           data=VALID_SUBSCRIBE_DATA,
                           content_type=content_type)
        assert resp.status_code == StatusCode.UNSUPPORTED_MEDIA_TYPE, resp.data
        assert resp.get_json() == error_response_json_template(
            routing.UnsupportedMediaTypeError(content_type,
                                              [VALID_REQUEST_CONTENT_TYPE],
                                              []))

    # checks missing single required attr
    for key in REQUIRED_ATTRS:
        data = remove_params(VALID_SUBSCRIBE_DATA, keys=[key])
        resp = client.post(POST_URL,
                           data=data,
                           content_type=VALID_REQUEST_CONTENT_TYPE)
        assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
        assert resp.get_json() == error_response_json_template(
            errors.MissingAttributesError([key]))

    # checks missing multiply required attrs, must return all missing
    data = remove_params(VALID_SUBSCRIBE_DATA, REQUIRED_ATTRS)
    resp = client.post(POST_URL,
                       data=data,
                       content_type=VALID_REQUEST_CONTENT_TYPE)
    assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
    assert resp.get_json() == error_response_json_template(
        errors.MissingAttributesError(REQUIRED_ATTRS))

    resp = client.post(POST_URL,
                       data=INVALID_TOPIC_DATA,
                       content_type=VALID_REQUEST_CONTENT_TYPE)
    assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
    assert resp.get_json() == error_response_json_template(
        TopicValidationError(
            'Predicates shorter than 4 elements must include wildcard as the last element'
        ))

    resp = client.post(POST_URL,
                       data=INVALID_CALLBACK_DATA,
                       content_type=VALID_REQUEST_CONTENT_TYPE)
    assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
    assert resp.get_json() == error_response_json_template(
        CallbackURLValidationError('URL must contain scheme'))

    # checks unknown mode error, if mode is not in [subscribe, unsubscribe]
    resp = client.post(POST_URL,
                       data=INVALID_MODE_DATA,
                       content_type=VALID_REQUEST_CONTENT_TYPE)
    assert resp.status_code == StatusCode.BAD_REQUEST, resp.data
    assert resp.get_json() == error_response_json_template(
        UnknownModeError(INVALID_MODE_DATA[MODE_ATTR_KEY]))

    # checks subscription exists error
    resp = client.post(POST_URL,
                       data=VALID_SUBSCRIBE_DATA,
                       content_type=VALID_REQUEST_CONTENT_TYPE)
    # let's support both conflict and fine, need to think about it more
    assert resp.status_code in (StatusCode.CONFLICT,
                                StatusCode.ACCEPTED), resp.data
    # assert resp.get_json() == error_response_json_template(
    #     SubscriptionExistsError()
    # )

    # checks unable to post error
    repo.reset_mock()
    post.return_value = None
    resp = client.post(POST_URL,
                       data=VALID_SUBSCRIBE_DATA,
                       content_type=VALID_REQUEST_CONTENT_TYPE)
    post.assert_called_once()
    assert resp.status_code == StatusCode.INTERNAL_SERVER_ERROR, resp.data
    assert resp.get_json() == error_response_json_template(
        UnableToPostSubscriptionError())

    # checks subscription not found error
    repo.reset_mock()
    delete.return_value = False
    resp = client.post(POST_URL,
                       data=VALID_UNSUBSCRIBE_DATA,
                       content_type=VALID_REQUEST_CONTENT_TYPE)
    delete.assert_called_once()
    assert resp.status_code == StatusCode.NOT_FOUND, resp.data
    assert resp.get_json() == error_response_json_template(
        SubscriptionNotFoundError())
Example #15
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)
    )
Example #16
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)
    )
Example #17
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))