ConfigurableParameter: safer val length check

validate_val() calls len() to check the value against allow_len,
min_len and max_len. len() requires the object to have a __len__()
method, which integers do not — calling len() on an int raises
TypeError.

Fix this by checking for __len__ first: if present, use len(val) as
usual; otherwise fall back to len(str(val)), which gives the number
of decimal digits for integer values.

Change-Id: Ibe91722ed1477b00d20ef5e4e7abd9068ff2f3e4
Jenkins: skip-card-test
This commit is contained in:
Neels Hofmeyr
2026-01-25 19:50:31 +01:00
committed by Vadim Yanitskiy
parent 98af3dd2e9
commit c5e7e59928
+12 -6
View File
@@ -190,19 +190,25 @@ class ConfigurableParameter(abc.ABC, metaclass=ClassVarMeta):
elif isinstance(val, io.BytesIO):
val = val.getvalue()
if hasattr(val, '__len__'):
val_len = len(val)
else:
# e.g. int length
val_len = len(str(val))
if cls.allow_len is not None:
l = cls.allow_len
# cls.allow_len could be one int, or a tuple of ints. Wrap a single int also in a tuple.
if not isinstance(l, (tuple, list)):
l = (l,)
if len(val) not in l:
raise ValueError(f'length must be one of {cls.allow_len}, not {len(val)}: {val!r}')
if val_len not in l:
raise ValueError(f'length must be one of {cls.allow_len}, not {val_len}: {val!r}')
if cls.min_len is not None:
if len(val) < cls.min_len:
raise ValueError(f'length must be at least {cls.min_len}, not {len(val)}: {val!r}')
if val_len < cls.min_len:
raise ValueError(f'length must be at least {cls.min_len}, not {val_len}: {val!r}')
if cls.max_len is not None:
if len(val) > cls.max_len:
raise ValueError(f'length must be at most {cls.max_len}, not {len(val)}: {val!r}')
if val_len > cls.max_len:
raise ValueError(f'length must be at most {cls.max_len}, not {val_len}: {val!r}')
return val
@classmethod