Skip to content

Commit 427415a

Browse files
committed
chore(validator): refine error msg of lenght validator
1 parent d4229e5 commit 427415a

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

data_spec_validator/spec/validators.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -370,8 +370,12 @@ def validate(value, extra, data) -> Tuple[bool, Union[Exception, str]]:
370370
RuntimeError('Lower boundary cannot less than 0 for length validator'),
371371
)
372372

373-
ok = lower_bound <= len(value) <= upper_bound if upper_bound else lower_bound <= len(value)
374-
info = '' if ok else ValueError(f'Length of {repr(value)} must be between {lower_bound} and {upper_bound}')
373+
if upper_bound:
374+
ok = lower_bound <= len(value) <= upper_bound
375+
info = '' if ok else ValueError(f'Length of {repr(value)} must be between {lower_bound} and {upper_bound}')
376+
else:
377+
ok = lower_bound <= len(value)
378+
info = '' if ok else ValueError(f'Length of {repr(value)} must be greater than {lower_bound}')
375379
return ok, info
376380

377381

test/test_spec.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,24 @@ class LengthSpec:
246246
nok_data = dict(length_field='exceed')
247247
assert is_something_error(ValueError, validate_data_spec, nok_data, LengthSpec)
248248

249+
# assert error message
250+
with self.assertRaises(ValueError) as e:
251+
validate_data_spec(dict(length_field='ah'), LengthSpec)
252+
253+
expected_error_msg = "field: LengthSpec.length_field, reason: Length of 'ah' must be between 3 and 5"
254+
self.assertEqual(str(e.exception), expected_error_msg)
255+
256+
def test_length__without_upper_limit(self):
257+
class LengthSpec:
258+
length_field = Checker([LENGTH], LENGTH=dict(min=3))
259+
260+
# assert error message
261+
with self.assertRaises(ValueError) as e:
262+
validate_data_spec(dict(length_field='ah'), LengthSpec)
263+
264+
expected_error_msg = "field: LengthSpec.length_field, reason: Length of 'ah' must be greater than 3"
265+
self.assertEqual(str(e.exception), expected_error_msg)
266+
249267
def test_decimal_place(self):
250268
class DecimalPlaceSpec:
251269
decimal_place_field = Checker([DECIMAL_PLACE], DECIMAL_PLACE=4)

0 commit comments

Comments
 (0)