Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added LimitedLengthStringField #234

Merged
merged 4 commits into from
Jun 28, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions plenum/common/messages/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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")