From dcd62f92fb6093a77c65af267b6b2c844d3d46de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20H=C3=B6nig?= Date: Sun, 7 Jan 2018 18:55:39 +0100 Subject: [PATCH] validator.py: Extend functionality of check_dict(). With this commit, check_dict() can be used to verify that all keys and/or values of a dict are of a certain type. --- zerver/lib/validator.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py index a2291aef31..5b4733b33b 100644 --- a/zerver/lib/validator.py +++ b/zerver/lib/validator.py @@ -90,7 +90,8 @@ def check_list(sub_validator: Optional[Validator], length: Optional[int]=None) - return None return f -def check_dict(required_keys: Iterable[Tuple[str, Validator]], +def check_dict(required_keys: Iterable[Tuple[str, Validator]]=[], + value_validator: Validator=None, _allow_only_listed_keys: bool=False) -> Validator: def f(var_name: str, val: object) -> Optional[str]: if not isinstance(val, dict): @@ -105,6 +106,13 @@ def check_dict(required_keys: Iterable[Tuple[str, Validator]], if error: return error + if value_validator: + for key in val: + vname = '%s contains a value that' % (var_name,) + error = value_validator(vname, val[key]) + if error: + return error + if _allow_only_listed_keys: delta_keys = set(val.keys()) - set(x[0] for x in required_keys) if len(delta_keys) != 0: