Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

validator: Add generic check_or.

seiwailaib5847905413c
diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py
index 9c84d41b585..143247e9fcc 100644
--- a/zerver/lib/validator.py
+++ b/zerver/lib/validator.py
@@ -38,6 +38,7 @@ from typing import (
Optional,
Set,
Tuple,
+ TypeVar,
Union,
cast,
overload,
@@ -494,3 +495,21 @@ def check_string_or_int(var_name: str, val: object) -> Union[str, int]:
return val
raise ValidationError(_("{var_name} is not a string or integer").format(var_name=var_name))
+
+
+TypeA = TypeVar("TypeA")
+TypeB = TypeVar("TypeB")
+
+
+def check_or(
+ sub_validator1: Validator[TypeA], sub_validator2: Validator[TypeB]
+) -> Validator[Union[TypeA, TypeB]]:
+ def f(var_name: str, val: object) -> Union[TypeA, TypeB]:
+ try:
+ return sub_validator1(var_name, val)
+ except ValidationError:
+ pass
+
+ return sub_validator2(var_name, val)
+
+ return f
diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py
index d1a494ba950..fc3d4184eb0 100644
--- a/zerver/tests/test_decorators.py
+++ b/zerver/tests/test_decorators.py
@@ -68,6 +68,7 @@ from zerver.lib.validator import (
check_int_in,
check_list,
check_none_or,
+ check_or,
check_short_string,
check_string,
check_string_fixed_length,
@@ -1037,6 +1038,25 @@ class ValidatorTestCase(ZulipTestCase):
with self.assertRaisesRegex(ValidationError, r"x is not a string or integer"):
check_string_or_int("x", x)
+ def test_check_or(self) -> None:
+ x: Any = "valid"
+ check_or(check_string_in(["valid"]), check_url)("x", x)
+
+ x = "http://zulip-bots.example.com/"
+ check_or(check_string_in(["valid"]), check_url)("x", x)
+
+ x = "invalid"
+ with self.assertRaisesRegex(ValidationError, r"x is not a URL"):
+ check_or(check_string_in(["valid"]), check_url)("x", x)
+
+ x = "http://127.0.0"
+ with self.assertRaisesRegex(ValidationError, r"x is not a URL"):
+ check_or(check_string_in(["valid"]), check_url)("x", x)
+
+ x = 1
+ with self.assertRaisesRegex(ValidationError, r"x is not a string"):
+ check_or(check_string_in(["valid"]), check_url)("x", x)
+
class DeactivatedRealmTest(ZulipTestCase):
def test_send_deactivated_realm(self) -> None: