Example #1
0
def test_handle_error_reraises_errors(web_request):
    p = Parser()
    with pytest.raises(ValidationError):
        p.handle_error(
            ValidationError("error raised"),
            web_request,
            Schema(),
            error_status_code=422,
            error_headers={},
        )
Example #2
0
def test_custom_error_handler(parse_json, web_request):
    class CustomError(Exception):
        pass

    def error_handler(error):
        raise CustomError(error)
    parse_json.side_effect = ValidationError('parse_json failed')
    p = Parser(error_handler=error_handler)
    with pytest.raises(CustomError):
        p.parse({'foo': fields.Field()}, web_request)
Example #3
0
    def _deserialize(self, value, attr, data, **kwargs):

        # deserialize into the OperationType enum instance corresponding to the value
        try:
            return MetaTransaction.OperationType(value)
        except ValueError:
            raise ValidationError(
                f"Could not parse attribute {attr}: {value} has to be one of "
                f"{[operation_type.value for operation_type in MetaTransaction.OperationType]}"
            )
Example #4
0
def validate_card_existent(id):
    """
    Check card existent.
    :param id: Parent card ID
    """
    card = Card.query.get(id)

    if not card:
        raise \
            ValidationError('Invalid parent card id.')
Example #5
0
def validate_ownership(id):
    """
    Check if user has access to the parent card.
    :param id: Parent card ID
    """
    card = Card.query.get(id)

    if card:
        if not card.owner_id == current_user.id:
            raise \
                ValidationError('You do not have access to use this card.')
Example #6
0
def _items_per_page_validator(arg):
    """
    Validator for a pagination items_per_page number.

    Args:
        arg (object): The object to validate as an integer greater than or
            equal to 1 and less or equal to 250.

    Returns:
        int: The validated argument.

    Raises:
        ValueError: If the integer is smaller than 1 or it can't be cast to an
            int.
    """
    arg = int(arg)
    if arg < 1:
        raise ValidationError("Value must be greater than or equal to 1.")
    if arg > 250:
        raise ValidationError("Value must be less than or equal to 250.")
    return arg
Example #7
0
def test_custom_error_handler(parse_json, web_request):
    class CustomError(Exception):
        pass

    def error_handler(error, req, schema, status_code, headers):
        assert isinstance(schema, Schema)
        raise CustomError(error)

    parse_json.side_effect = ValidationError("parse_json failed")
    p = Parser(error_handler=error_handler)
    with pytest.raises(CustomError):
        p.parse({"foo": fields.Field()}, web_request)
Example #8
0
def __request_id_validator(request_id: str) -> None:
    # Replay attack detection specs of Salesforce's cache-only service:
    # https://developer.salesforce.com/docs/atlas.en-us.securityImplGuide.meta/
    #   securityImplGuide/security_pe_byok_cache_replay.htm
    trace_enter(inspect.currentframe())

    request_id_length = 32

    if len(request_id) != request_id_length:
        err_msg = ('requestId/nonce length must be %s alphanummeric '
                   'chars.' % request_id_length)
        logger.error(err_msg)
        trace_exit(inspect.currentframe(), err_msg)
        raise ValidationError(err_msg, status_code=422)

    result = re.match('^[a-zA-Z0-9]+$', request_id)

    if not result:
        err_msg = ('requestId/nonce must consist of alphanummeric chars only.')
        logger.error(err_msg)
        trace_exit(inspect.currentframe(), err_msg)
        raise ValidationError(err_msg, status_code=422)
Example #9
0
def test_custom_error_handler_decorator(parse_json, web_request):
    class CustomError(Exception):
        pass

    parse_json.side_effect = ValidationError('parse_json failed')

    parser = Parser()

    @parser.error_handler
    def handle_error(error, req):
        raise CustomError(error)

    with pytest.raises(CustomError):
        parser.parse({'foo': fields.Field()}, web_request)
Example #10
0
def validate_strong_password(password):
    """
    Validate request parser password.

    :param password: Input password
    """

    # Validation rules
    xp = re.compile(r'^(?=.*?\d)(?=.*?[A-Z])(?=.*?[a-z])[\S]{6,}$')

    # Match password
    if not xp.match(password):
        raise ValidationError('Enter a combination of at least 6 numbers,'
                              '(upper and lowercase) letters.')
Example #11
0
 def _deserialize(self, value, attr, data, **kwargs):
     if not isinstance(value, (str, bytes)):
         raise self.make_error("invalid")
     try:
         res_list = []
         if isinstance(value, bytes):
             value = value.decode("utf-8")
         value = value.replace(" ", "")
         value_list = value.split(self.split_str) if value else []
         for v in value_list:
             res_list.append(self.trans_type(v))
         return res_list
     except Exception as e:
         raise ValidationError(str(e))
Example #12
0
  def _validated(self, value):
    try:
      if "_" in value:
        s1 = value.split(":")
        chrom = s1[0]
        pos, alleles = s1[1].split("_")
        pos = int(pos)
        ref, alt = alleles.split("/")
      else:
        chrom, pos, ref, alt = value.split(":")
        pos = int(pos)
    except:
      raise ValidationError("Invalid variant {}, should be of format: CHROM:POS_REF/ALT or CHROM:POS:REF:ALT".format(value))

    if chrom.startswith("chr"):
      raise ValidationError("Variant chromosome should not contain 'chr': " + value)

    if not all((x in VariantField.alleles for x in ref)):
      raise ValidationError("Variant {} had invalid alleles".format(value))

    if not all((x in VariantField.alleles for x in alt)):
      raise ValidationError("Variant {} had invalid alleles".format(value))

    return value
Example #13
0
def test_handle_error_called_when_parsing_raises_error(handle_error, web_request):
    # handle_error must raise an error to be valid
    handle_error.side_effect = ValidationError("parsing failed")

    def always_fail(*args, **kwargs):
        raise ValidationError("error occurred")

    p = Parser()
    assert handle_error.call_count == 0
    with pytest.raises(ValidationError):
        p.parse({"foo": fields.Field()}, web_request, validate=always_fail)
    assert handle_error.call_count == 1
    with pytest.raises(ValidationError):
        p.parse({"foo": fields.Field()}, web_request, validate=always_fail)
    assert handle_error.call_count == 2
Example #14
0
def test_custom_error_handler_decorator(parse_json, web_request):
    class CustomError(Exception):
        pass

    parse_json.side_effect = ValidationError("parse_json failed")

    parser = Parser()

    @parser.error_handler
    def handle_error(error, req, schema):
        assert isinstance(schema, Schema)
        raise CustomError(error)

    with pytest.raises(CustomError):
        parser.parse({"foo": fields.Field()}, web_request)
Example #15
0
def deserialize_query_filter(value, value_type):
    value = value.strip()
    if len(value) == 0:
        raise ValidationError('empty value')
    if len(value) > 1 and ((value[0] == '"' and value[-1] == '"') or
                           (value[0] == '\'' and value[-1] == '\'')):
        operator = '$eq'
        value = value[1:-1]
        return {operator: value}
    elements = value.split(':')
    if len(elements) == 1:
        operator = '$eq'
        value = elements[0]
    elif len(elements) == 2:
        operator = '${}'.format(elements[0].lower())
        value = elements[1]
        if operator not in ['$eq', '$ne', '$gt', '$lt', '$gte', '$lte']:
            raise ValidationError('unknown operator')
    else:
        raise ValidationError('too many values')
    try:
        if value_type == int:
            value = int(value)
        elif value_type == long:
            value = long(value)
        elif value_type == float:
            value = float(value)
        elif value_type == str:
            if len(value) > 1 and ((value[0] == '"' and value[-1] == '"') or
                                   (value[0] == '\'' and value[-1] == '\'')):
                value = value[1:-1]
        else:
            raise ValidationError('unsupported value type')
    except:
        raise ValidationError('invalid value type')
    return {operator: value}
Example #16
0
def test_abort_has_serializable_data():
    with pytest.raises(HTTPException) as excinfo:
        abort(400, message='custom error message')
    serialized_error = json.dumps(excinfo.value.data)
    error = json.loads(serialized_error)
    assert isinstance(error, dict)
    assert error['message'] == 'custom error message'

    with pytest.raises(HTTPException) as excinfo:
        abort(400, message='custom error message',
            exc=ValidationError('custom error message'))
    serialized_error = json.dumps(excinfo.value.data)
    error = json.loads(serialized_error)
    assert isinstance(error, dict)
    assert error['message'] == 'custom error message'
Example #17
0
def test_custom_error_handler_decorator(web_request):
    class CustomError(Exception):
        pass

    mock_schema = mock.Mock(spec=Schema)
    mock_schema.strict = True
    mock_schema.load.side_effect = ValidationError("parsing json failed")
    parser = Parser()

    @parser.error_handler
    def handle_error(error, req, schema, status_code, headers):
        assert isinstance(schema, Schema)
        raise CustomError(error)

    with pytest.raises(CustomError):
        parser.parse(mock_schema, web_request)
Example #18
0
def test_custom_error_handler_must_reraise(web_request):
    class CustomError(Exception):
        pass

    mock_schema = mock.Mock(spec=Schema)
    mock_schema.strict = True
    mock_schema.load.side_effect = ValidationError("parsing json failed")
    parser = Parser()

    @parser.error_handler
    def handle_error(error, req, schema, *, error_status_code, error_headers):
        pass

    # because the handler above does not raise a new error, the parser should
    # raise a ValueError -- indicating a programming error
    with pytest.raises(ValueError):
        parser.parse(mock_schema, web_request)
Example #19
0
def test_abort_has_serializable_data():
    with pytest.raises(SanicException) as excinfo:
        abort(400, message="custom error message")
    serialized_error = json.dumps(excinfo.value.data)
    error = json.loads(serialized_error)
    assert isinstance(error, dict)
    assert error["message"] == "custom error message"

    with pytest.raises(SanicException) as excinfo:
        abort(
            400,
            message="custom error message",
            exc=ValidationError("custom error message"),
        )
    serialized_error = json.dumps(excinfo.value.data)
    error = json.loads(serialized_error)
    assert isinstance(error, dict)
    assert error["message"] == "custom error message"
Example #20
0
def test_abort_has_serializable_data():
    try:
        abort(400, message="custom error message")
    except HandleValidationError as err:
        serialized_error = json.dumps(err.data)

        error = json.loads(serialized_error)
        assert isinstance(error, dict)
        assert error["message"] == "custom error message"

    try:
        abort(
            400,
            message="custom error message",
            exc=ValidationError("custom error message"),
        )
    except HandleValidationError as excinfo:
        serialized_error = json.dumps(excinfo.data)
        error = json.loads(serialized_error)
        assert isinstance(error, dict)
        assert error["message"] == "custom error message"
Example #21
0
def always_fail(val):
    raise ValidationError('something went wrong',
                          status_code=401,
                          extra='woops')
Example #22
0
def must_exist_in_db(val):
    if val != 1:
        raise ValidationError("id not exist")
Example #23
0
def is_a_valid_object_id(val):
    try:
        ObjectId(val)
    except InvalidId as exc:
        raise ValidationError(str(exc), status_code=400)
Example #24
0
 def always_fail(value):
     raise ValidationError("something went wrong", status_code=400)
Example #25
0
 def always_fail(value):
     raise ValidationError("something went wrong")
Example #26
0
def radius_gte_zero(val):
    if val < 0:
        raise ValidationError("radius must greater than equal 0")
Example #27
0
 def __call__(self, value):
     if value.lstrip('-') not in self.values:
         raise ValidationError('Cannot sort on value "{0}"'.format(value),
                               status_code=422)
Example #28
0
def _validate_natural(value):
    if value < 0:
        raise ValidationError('Must be a natural number')
Example #29
0
def validate_category_id(val):
    cid = Category.query.get(val)
    if not cid:
        raise ValidationError("分类不存在")
Example #30
0
    def _deserialize(self, value, attr, data, **kwargs):
        if not is_address(value):
            raise ValidationError(
                f"Could not parse attribute {attr}: Invalid address {value}")

        return to_checksum_address(value)