diff --git a/plenum/common/messages/fields.py b/plenum/common/messages/fields.py index f16a6024ff..7c3237b88b 100644 --- a/plenum/common/messages/fields.py +++ b/plenum/common/messages/fields.py @@ -90,6 +90,22 @@ def _specific_validation(self, val): return 'empty string' +class LimitedLengthStringField(FieldBase): + _base_types = (str,) + + def __init__(self, max_length: int, **kwargs): + assert max_length > 0, 'should be greater than 0' + super().__init__(**kwargs) + self._max_length = max_length + + def _specific_validation(self, val): + if not val: + return 'empty string' + if len(val) > self._max_length: + val = val[:100] + ('...' if len(val) > 100 else '') + return '{} is longer than {} symbols'.format(val, self._max_length) + + class SignatureField(FieldBase): _base_types = (str, type(None)) # TODO do nothing because EmptySignature should be raised somehow diff --git a/plenum/test/input_validation/fields_validation/test_limited_length_string_field.py b/plenum/test/input_validation/fields_validation/test_limited_length_string_field.py new file mode 100644 index 0000000000..b3b1d7c065 --- /dev/null +++ b/plenum/test/input_validation/fields_validation/test_limited_length_string_field.py @@ -0,0 +1,22 @@ +import pytest +from plenum.common.messages.fields import LimitedLengthStringField + + +def test_incorrect_max_length(): + with pytest.raises(Exception): + LimitedLengthStringField(max_length=0) + + +def test_empty_string(): + validator = LimitedLengthStringField(max_length=1) + assert validator.validate("") + + +def test_valid_string(): + validator = LimitedLengthStringField(max_length=1) + assert not validator.validate("x") + + +def test_long_string(): + validator = LimitedLengthStringField(max_length=1) + assert validator.validate("xx")