check_short_string: Verify string before checking length.

While the previous implementation was correct, this should give better
error messages.
This commit is contained in:
Tim Abbott 2017-11-10 16:37:43 -08:00
parent 72eba6a0ce
commit a23378a304
2 changed files with 15 additions and 2 deletions

View File

@ -40,11 +40,13 @@ def check_string(var_name: str, val: object) -> Optional[str]:
return None
def check_short_string(var_name: str, val: object) -> Optional[str]:
if not isinstance(val, str):
return _('%s is not a string') % (var_name,)
max_length = 200
if len(val) >= max_length:
return _("{var_name} is longer than {max_length}.".format(
var_name=var_name, max_length=max_length))
return check_string(var_name, val)
return None
def check_int(var_name: str, val: object) -> Optional[str]:
if not isinstance(val, int):

View File

@ -36,7 +36,7 @@ from zerver.decorator import (
)
from zerver.lib.validator import (
check_string, check_dict, check_dict_only, check_bool, check_float, check_int, check_list, Validator,
check_variable_type, equals, check_none_or, check_url,
check_variable_type, equals, check_none_or, check_url, check_short_string
)
from zerver.models import \
get_realm, get_user, UserProfile, Client, Realm, Recipient
@ -452,6 +452,17 @@ class ValidatorTestCase(TestCase):
x = 4
self.assertEqual(check_string('x', x), 'x is not a string')
def test_check_short_string(self):
# type: () -> None
x = "hello" # type: Any
self.assertEqual(check_short_string('x', x), None)
x = 'x' * 201
self.assertEqual(check_short_string('x', x), 'x is longer than 200.')
x = 4
self.assertEqual(check_short_string('x', x), 'x is not a string')
def test_check_bool(self):
# type: () -> None
x = True # type: Any